http_api_reqwest_client/
lib.rs

1pub use http_api_client;
2pub use reqwest;
3
4use core::time::Duration;
5
6use http_api_client::{async_trait, Body, Request, Response};
7pub use http_api_client::{Client, RetryableClient};
8use reqwest::{Client as ReqwestHttpClient, Error as ReqwestError, Request as ReqwestRequest};
9
10#[derive(Debug, Clone)]
11pub struct ReqwestClient {
12    pub http_client: ReqwestHttpClient,
13}
14
15impl ReqwestClient {
16    pub fn new() -> Result<Self, ReqwestError> {
17        Ok(Self::with(
18            ReqwestHttpClient::builder()
19                .connect_timeout(Duration::from_secs(5))
20                .timeout(Duration::from_secs(30))
21                .build()?,
22        ))
23    }
24
25    pub fn with(http_client: ReqwestHttpClient) -> Self {
26        Self { http_client }
27    }
28}
29
30#[async_trait]
31impl Client for ReqwestClient {
32    type RespondError = ReqwestError;
33
34    async fn respond(&self, request: Request<Body>) -> Result<Response<Body>, Self::RespondError> {
35        let res_reqwest = self
36            .http_client
37            .execute(ReqwestRequest::try_from(request)?)
38            .await?;
39
40        let res = Response::new(());
41        let (mut head, _) = res.into_parts();
42        head.status = res_reqwest.status();
43        head.version = res_reqwest.version();
44        head.headers = res_reqwest.headers().to_owned();
45
46        let body = res_reqwest.bytes().await?.to_vec();
47
48        let res = Response::from_parts(head, body);
49
50        Ok(res)
51    }
52}
53
54#[async_trait]
55impl RetryableClient for ReqwestClient {
56    async fn sleep(&self, dur: Duration) {
57        tokio::time::sleep(dur).await;
58    }
59}