http_adapter_reqwest/
lib.rs

1//! # HTTP adapter implementation for [`reqwest`](https://crates.io/crates/reqwest)
2//!
3//! For more details refer to [`http-adapter`](https://crates.io/crates/http-adapter)
4
5use std::fmt::Debug;
6
7use http_body_util::BodyExt;
8pub use reqwest;
9
10use http_adapter::async_trait::async_trait;
11use http_adapter::http::{Request, Response};
12use http_adapter::HttpClientAdapter;
13
14#[derive(Clone, Debug)]
15pub struct ReqwestAdapter {
16	client: reqwest::Client,
17}
18
19impl ReqwestAdapter {
20	pub fn new(client: reqwest::Client) -> Self {
21		Self { client }
22	}
23}
24
25impl Default for ReqwestAdapter {
26	#[inline]
27	fn default() -> Self {
28		Self {
29			client: reqwest::Client::new(),
30		}
31	}
32}
33
34#[inline]
35fn from_request<B: Into<reqwest::Body>>(request: Request<B>) -> Result<reqwest::Request, reqwest::Error> {
36	request.try_into()
37}
38
39#[inline]
40async fn to_response(res: reqwest::Response) -> Result<Response<Vec<u8>>, reqwest::Error> {
41	let mut res = Response::from(res);
42	let body_bytes = res.body_mut().collect().await?.to_bytes().to_vec();
43	Ok(res.map(move |_| body_bytes))
44}
45
46#[async_trait]
47impl HttpClientAdapter for ReqwestAdapter {
48	type Error = reqwest::Error;
49
50	async fn execute(&self, request: Request<Vec<u8>>) -> Result<Response<Vec<u8>>, Self::Error> {
51		let res = self.client.execute(from_request(request)?).await?;
52		to_response(res).await
53	}
54}