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
use reqwest::{Response, StatusCode};
use crate::{
api_client::ApiClient,
error::{ApiError, ResultApi},
};
impl ApiClient {
/// Handle the response from a request, checking the status code and returning the response if successful.
///
/// # Arguments
/// * `path` - The path of the request.
/// * `response` - The response from the request.
///
/// # Returns
/// * `ResultApi<Response>` - The response from the request if successful, otherwise an error.
pub(crate) async fn handle_response(
&self,
path: &str,
response: Response,
) -> ResultApi<Response> {
let status = response.status();
self.check_status(status, path)?;
Ok(response)
}
fn check_status(&self, status: StatusCode, endpoint: &str) -> ResultApi<()> {
if status == StatusCode::UNAUTHORIZED {
return Err(ApiError::Unauthorized);
}
if !status.is_success() {
return Err(ApiError::HttpStatus {
status,
endpoint: endpoint.to_string(),
});
}
Ok(())
}
/// Parse the JSON response from a request.
///
/// # Arguments
/// * `response` - The response from the request.
///
/// # Returns
/// * `ResultApi<T>` - The parsed JSON response if successful, otherwise an error.
pub(crate) async fn parse_json<T: serde::de::DeserializeOwned>(
&self,
response: Response,
) -> ResultApi<T> {
let body = response.text().await?;
let mut deserializer = serde_json::Deserializer::from_str(&body);
serde_path_to_error::deserialize::<_, T>(&mut deserializer).map_err(|err| {
ApiError::JsonParseDetailed {
error: format!("path: {}, error: {}", err.path(), err.inner()),
}
})
}
}