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
use crate::{enums::RequestType, errors::ClientError};
use url::Url;

/// An array of HTTP response codes which indicate a successful response
const HTTP_SUCCESS_CODES: [u16; 2] = [200, 204];

/// Represents an HTTP client which is capable of executing
/// [Endpoints][crate::endpoint::Endpoint] by sending the [Request] generated
/// by the Endpoint and returning a [Response].
pub trait Client {
    /// Sends the given [Request] and returns a [Response]. Implementations
    /// should consolidate all errors into the [ClientError] type.
    fn send(&self, req: crate::client::Request) -> Result<crate::client::Response, ClientError>;

    /// Returns the base URL the client is configured with. This is used for
    /// creating the fully qualified URLs used when executing
    /// [Endpoints][crate::endpoint::Endpoint].
    fn base(&self) -> &str;

    /// This method provides a common interface to
    /// [Endpoints][crate::endpoint::Endpoint] for execution.
    fn execute(&self, req: Request) -> Result<Vec<u8>, ClientError> {
        log::info!(
            "Client sending {:#?} request to {} with {} bytes of data",
            req.method,
            req.url,
            req.data.len()
        );
        let response = self.send(req)?;

        log::info!(
            "Client received {} response from {} with {} bytes of body data",
            response.code,
            response.url,
            response.content.len()
        );

        // Check response
        if !HTTP_SUCCESS_CODES.contains(&response.code) {
            return Err(ClientError::ServerResponseError {
                url: response.url.to_string(),
                code: response.code,
                content: response.content,
            });
        }

        // Parse response content
        Ok(response.content)
    }
}

/// Represents an HTTP request
#[derive(Debug, Clone)]
pub struct Request {
    pub url: Url,
    pub method: RequestType,
    pub data: Vec<u8>,
}

/// Represents an HTTP response
#[derive(Debug, Clone)]
pub struct Response {
    pub url: Url,
    pub code: u16,
    pub content: Vec<u8>,
}