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
//! `reqwest` based `pretend` client
//!
//! Feature `blocking` enables the blocking client.

#![warn(missing_docs)]
#![deny(unsafe_code)]

#[cfg(feature = "blocking")]
mod blocking;

pub use reqwest;

#[cfg(feature = "blocking")]
pub use blocking::*;

use pretend::client::{async_trait, Bytes, Client as PClient, Method};
use pretend::{Error, HeaderMap, Response as PResponse, Result, Url};
use reqwest::Client as RClient;
use std::mem;

/// `reqwest` based `pretend` client
#[derive(Default)]
pub struct Client {
    client: RClient,
}

impl Client {
    /// Constructor with custom client
    ///
    /// This constructor creates a client implementation
    /// for `pretend` wrapping the supplied `reqwest` client.
    pub fn new(client: RClient) -> Self {
        Client { client }
    }
}

#[async_trait]
impl PClient for Client {
    async fn execute(
        &self,
        method: Method,
        url: Url,
        headers: HeaderMap,
        body: Option<Bytes>,
    ) -> Result<PResponse<Bytes>> {
        let mut builder = self.client.request(method, url).headers(headers);
        if let Some(body) = body {
            builder = builder.body(body);
        }
        let response = builder.send().await;
        let mut response = response.map_err(|err| Error::Response(Box::new(err)))?;

        let status = response.status();
        let headers = mem::take(response.headers_mut());

        let bytes = response.bytes().await;
        let bytes = bytes.map_err(|err| Error::Body(Box::new(err)))?;

        Ok(PResponse::new(status, headers, bytes))
    }
}