pretend_reqwest/
lib.rs

1//! `reqwest` based `pretend` client
2//!
3//! Feature `blocking` enables the blocking client.
4
5#![warn(missing_docs)]
6#![forbid(unsafe_code)]
7
8#[cfg(feature = "blocking")]
9mod blocking;
10
11pub use reqwest;
12
13#[cfg(feature = "blocking")]
14pub use blocking::*;
15
16use pretend::client::{async_trait, Bytes, Client as PClient, Method};
17use pretend::{Error, HeaderMap, Response as PResponse, Result, Url};
18use reqwest::Client as RClient;
19use std::mem;
20
21/// `reqwest` based `pretend` client
22#[derive(Clone, Debug, Default)]
23pub struct Client {
24    client: RClient,
25}
26
27impl Client {
28    /// Constructor with custom client
29    ///
30    /// This constructor creates a client implementation
31    /// for `pretend` wrapping the supplied `reqwest` client.
32    pub fn new(client: RClient) -> Self {
33        Client { client }
34    }
35}
36
37#[async_trait]
38impl PClient for Client {
39    async fn execute(
40        &self,
41        method: Method,
42        url: Url,
43        headers: HeaderMap,
44        body: Option<Bytes>,
45    ) -> Result<PResponse<Bytes>> {
46        let mut builder = self.client.request(method, url).headers(headers);
47        if let Some(body) = body {
48            builder = builder.body(body);
49        }
50        let response = builder.send().await;
51        let mut response = response.map_err(Error::response)?;
52
53        let status = response.status();
54        let headers = mem::take(response.headers_mut());
55
56        let bytes = response.bytes().await;
57        let bytes = bytes.map_err(Error::body)?;
58
59        Ok(PResponse::new(status, headers, bytes))
60    }
61}