1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
#[cfg(feature = "jsonrpc")]
use crate::jsonrpc::{JsonRpcError, JsonRpcRequest, JsonRpcResult, JsonRpcTarget};
use crate::{
    http::{HTTPBody, HTTPResponse},
    target::Target,
};

use async_trait::async_trait;
use reqwest::{Client, Error};
use serde::de::DeserializeOwned;

#[async_trait]
pub trait ProviderType<T: Target> {
    /// request to target and return http response
    async fn request(&self, target: T) -> Result<HTTPResponse, Error>;
}

#[async_trait]
pub trait JsonProviderType<T: Target>: ProviderType<T> {
    /// request and deserialize response to json using serde
    async fn request_json<U: DeserializeOwned>(&self, target: T) -> Result<U, Error>;
}

#[cfg(feature = "jsonrpc")]
#[async_trait]
pub trait JsonRpcProviderType<T: Target>: ProviderType<T> {
    /// batch isomorphic JSON-RPC requests
    async fn batch<U: DeserializeOwned>(
        &self,
        targets: Vec<T>,
    ) -> Result<Vec<JsonRpcResult<U>>, JsonRpcError>;
}

pub type EndpointFn<T> = fn(target: &T) -> String;
pub struct Provider<T: Target> {
    /// endpoint closure to customize the endpoint (url / path)
    endpoint_fn: Option<EndpointFn<T>>,
    client: Client,
}

#[async_trait]
impl<T> ProviderType<T> for Provider<T>
where
    T: Target + Send,
{
    async fn request(&self, target: T) -> Result<HTTPResponse, Error> {
        let mut request = self.request_builder(&target);
        request = request.body(target.body().inner);
        request.send().await
    }
}

#[async_trait]
impl<T> JsonProviderType<T> for Provider<T>
where
    T: Target + Send,
{
    async fn request_json<U: DeserializeOwned>(&self, target: T) -> Result<U, Error> {
        let response = self.request(target).await?;
        let body = response.json::<U>().await?;
        Ok(body)
    }
}

#[cfg(feature = "jsonrpc")]
#[async_trait]
impl<T> JsonRpcProviderType<T> for Provider<T>
where
    T: JsonRpcTarget + Send,
{
    async fn batch<U: DeserializeOwned>(
        &self,
        targets: Vec<T>,
    ) -> Result<Vec<JsonRpcResult<U>>, JsonRpcError> {
        if targets.is_empty() {
            return Err(JsonRpcError {
                code: -32600,
                message: "Invalid Request".into(),
            });
        }

        let target = &targets[0];
        let mut request = self.request_builder(target);
        let mut requests = Vec::<JsonRpcRequest>::new();
        for (k, v) in targets.iter().enumerate() {
            let request = JsonRpcRequest::new(v.method_name(), v.params(), k as u64);
            requests.push(request);
        }

        request = request.body(HTTPBody::from_array(&requests).inner);
        let response = request.send().await?;
        let body = response.json::<Vec<JsonRpcResult<U>>>().await?;
        Ok(body)
    }
}

impl<T> Provider<T>
where
    T: Target,
{
    pub fn new(endpoint_fn: EndpointFn<T>) -> Self {
        let client = reqwest::Client::new();
        Self {
            client,
            endpoint_fn: Some(endpoint_fn),
        }
    }

    pub(crate) fn request_url(&self, target: &T) -> String {
        let mut url = format!("{}{}", target.base_url(), target.path());
        if let Some(func) = &self.endpoint_fn {
            url = func(target);
        }
        url
    }

    pub(crate) fn request_builder(&self, target: &T) -> reqwest::RequestBuilder {
        let url = self.request_url(target);
        let mut request = self.client.request(target.method().into(), url);
        let query_map = target.query();
        if !query_map.is_empty() {
            request = request.query(&query_map);
        }
        if !target.headers().is_empty() {
            for (k, v) in target.headers() {
                request = request.header(k, v);
            }
        }
        request
    }
}

impl<T> Default for Provider<T>
where
    T: Target,
{
    fn default() -> Self {
        Self {
            client: reqwest::Client::new(),
            endpoint_fn: None,
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        http::{HTTPBody, HTTPMethod},
        provider::Provider,
        target::Target,
    };
    use serde::{Deserialize, Serialize};
    use std::collections::HashMap;

    #[derive(Serialize, Deserialize)]
    struct Person {
        name: String,
        age: u8,
        phones: Vec<String>,
    }

    enum HttpBin {
        Get,
        Post,
    }

    impl Target for HttpBin {
        fn base_url(&self) -> &'static str {
            "https://httpbin.org"
        }

        fn method(&self) -> HTTPMethod {
            match self {
                HttpBin::Get => HTTPMethod::GET,
                HttpBin::Post => HTTPMethod::POST,
            }
        }

        fn path(&self) -> &'static str {
            match self {
                HttpBin::Get => "/get",
                HttpBin::Post => "/post",
            }
        }

        fn query(&self) -> HashMap<&'static str, &'static str> {
            HashMap::default()
        }

        fn headers(&self) -> HashMap<&'static str, &'static str> {
            HashMap::default()
        }

        fn body(&self) -> HTTPBody {
            match self {
                HttpBin::Get => HTTPBody::default(),
                HttpBin::Post => HTTPBody::from(&Person {
                    name: "test".to_string(),
                    age: 20,
                    phones: vec!["1234567890".to_string()],
                }),
            }
        }
    }

    #[test]
    fn test_test_endpoint_closure() {
        let provider = Provider::<HttpBin>::default();
        assert_eq!(
            provider.request_url(&HttpBin::Get),
            "https://httpbin.org/get"
        );

        let provider = Provider::<HttpBin>::new(|_: &HttpBin| "http://httpbin.org".to_string());
        assert_eq!(provider.request_url(&HttpBin::Post), "http://httpbin.org");
    }
}