Skip to main content

rig_reqwest/
middleware.rs

1//! The middleware client: a `reqwest_middleware` client the transport sends
2//! through.
3
4use rig_http::http_client::{
5    HttpClientExt, LazyBody, MultipartForm, Request, Response, Result, StreamingResponse,
6};
7use rig_http::wasm_compat::WasmCompatSend;
8
9use super::{
10    Bytes, Error, Execute, Payload, into_response, into_streaming_response, multipart_form,
11    send_with,
12};
13
14/// A configured middleware client implementing [`HttpClientExt`].
15///
16/// Build the inner client with `reqwest_middleware::ClientBuilder`, then wrap
17/// it with `From<ClientWithMiddleware>`.
18#[cfg_attr(
19    docsrs,
20    doc(cfg(any(
21        feature = "reqwest-middleware-rustls",
22        feature = "reqwest-middleware-native-tls"
23    )))
24)]
25#[derive(Clone, Debug)]
26pub struct ReqwestMiddlewareClient(reqwest_middleware::ClientWithMiddleware);
27
28impl ReqwestMiddlewareClient {
29    /// Take the inner client back.
30    #[must_use]
31    pub fn into_inner(self) -> reqwest_middleware::ClientWithMiddleware {
32        self.0
33    }
34}
35
36impl From<reqwest_middleware::ClientWithMiddleware> for ReqwestMiddlewareClient {
37    fn from(client: reqwest_middleware::ClientWithMiddleware) -> Self {
38        Self(client)
39    }
40}
41
42impl AsRef<reqwest_middleware::ClientWithMiddleware> for ReqwestMiddlewareClient {
43    fn as_ref(&self) -> &reqwest_middleware::ClientWithMiddleware {
44        &self.0
45    }
46}
47
48impl Execute for ReqwestMiddlewareClient {
49    fn execute(
50        &self,
51        parts: http::request::Parts,
52        payload: Result<Payload>,
53    ) -> Result<impl Future<Output = Result<reqwest::Response>> + WasmCompatSend + 'static> {
54        let request = self
55            .0
56            .request(parts.method, parts.uri.to_string())
57            .headers(parts.headers);
58        let request = match payload? {
59            Payload::Bytes(bytes) => request.body(bytes),
60            Payload::Form(form) => request.multipart(form),
61        };
62        Ok(async move { request.send().await.map_err(Error::instance) })
63    }
64}
65
66http_client_ext!(ReqwestMiddlewareClient);