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
//! Representation of HTTP API response

use log::{error, warn};
use reqwest::Response;
use serde::de::DeserializeOwned;

use crate::models::errors::{ApiError, ErrorResponse};

/// Representation of HTTP API response.
///
/// Wraps Reqwest lib's Response
pub struct HttpResponse {
    inner: Response,
}

impl HttpResponse {
    pub fn new(inner: Response) -> Self {
        Self { inner }
    }

    pub fn is_success(&self) -> bool {
        self.inner.status().is_success()
    }

    pub async fn deserialize<T: DeserializeOwned>(self) -> Result<T, ApiError> {
        if self.is_success() {
            Ok(self.json().await?)
        } else {
            let err_response_res: Result<ErrorResponse, ApiError> = self.json().await;
            match err_response_res {
                Ok(error_response) => {
                    let api_error =
                        ApiError::with_response_errors("Error response", &error_response.errors);
                    warn!("{:?}", api_error);
                    Err(api_error)
                }
                Err(e) => {
                    let msg = format!("Error deserializing response errors: {}", e);
                    error!("{}", msg);
                    Err(ApiError::new(&msg))
                }
            }
        }
    }

    async fn json<T: DeserializeOwned>(self) -> Result<T, ApiError> {
        self.inner.json().await.map_err(|e| {
            let msg = format!("Error deserializing: {}", e);
            error!("{}", msg);
            ApiError::new(&msg)
        })
    }
}