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
use crate::{errors::{CrateResult, Error}, utils::handle_response};
use reqwest::{IntoUrl, Response, StatusCode, Url};
use serde::{Serialize, de::DeserializeOwned};
pub struct RestApiClientBuilder<ApiErrorType>
where
ApiErrorType: DeserializeOwned + ToString + Clone
{
http_client: reqwest::Client,
api_base_url: Result<Url, reqwest::Error>,
refresh_token_path: Option<String>,
placeholder: Option<ApiErrorType>
}
impl<ApiErrorType> RestApiClientBuilder<ApiErrorType>
where
ApiErrorType: DeserializeOwned + ToString + Clone
{
pub fn new<T: IntoUrl>(http_client: reqwest::Client, api_base_url: T) -> Self {
Self{
http_client: http_client,
api_base_url: api_base_url.into_url(),
refresh_token_path: None,
placeholder: None
}
}
pub fn build(self) -> CrateResult<RestApiClient<ApiErrorType>> {
Ok(
RestApiClient{
http_client: self.http_client,
api_base_url: self.api_base_url?,
placeholder: None
}
)
}
}
#[derive(Clone)]
pub struct RestApiClient<ApiErrorType>
where
ApiErrorType: DeserializeOwned + ToString + Clone
{
http_client: reqwest::Client,
api_base_url: Url,
placeholder: Option<ApiErrorType>
}
impl<ApiErrorType> RestApiClient<ApiErrorType>
where
ApiErrorType: DeserializeOwned + ToString + Clone
{
pub async fn get<ResponseDataType>(&self, path: &str) -> CrateResult<ResponseDataType>
where
ResponseDataType: DeserializeOwned
{
let url = self.api_base_url.to_string() + path;
let response = self.http_client.get(url).send().await?;
handle_response::<ResponseDataType, ApiErrorType>(response).await
}
pub async fn post<RequestDataType, ResponseDataType>(&self, request_data: RequestDataType, path: &str) -> CrateResult<ResponseDataType>
where
RequestDataType: Serialize,
ResponseDataType: DeserializeOwned
{
let url = self.api_base_url.to_string() + path;
let response = self.http_client.post(url).json(&request_data).send().await?;
handle_response::<ResponseDataType, ApiErrorType>(response).await
}
}