aboutsummaryrefslogtreecommitdiffstats
path: root/crates/api-auth/src/client.rs
blob: d696162f7ff0908e4360ebf2c3273c96865a86f7 (plain)
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
use std::pin::Pin;
use std::{future::Future, ops::Deref};

#[cfg(not(target_arch = "wasm32"))]
use oauth2::HttpResponse;
use oauth2::{AsyncHttpClient, HttpClientError, HttpRequest, http};

#[derive(Clone)]
pub struct AuthHttpClient(reqwest::Client);

impl Deref for AuthHttpClient {
    type Target = reqwest::Client;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl From<reqwest::Client> for AuthHttpClient {
    fn from(value: reqwest::Client) -> Self {
        Self(value)
    }
}

impl<'c> AsyncHttpClient<'c> for AuthHttpClient {
    type Error = HttpClientError<reqwest::Error>;

    #[cfg(target_arch = "wasm32")]
    type Future = Pin<Box<dyn Future<Output = Result<HttpResponse, Self::Error>> + 'c>>;
    #[cfg(not(target_arch = "wasm32"))]
    type Future =
        Pin<Box<dyn Future<Output = Result<HttpResponse, Self::Error>> + Send + Sync + 'c>>;

    fn call(&'c self, request: HttpRequest) -> Self::Future {
        Box::pin(async move {
            let response = self
                .0
                .execute(request.try_into().map_err(Box::new)?)
                .await
                .map_err(Box::new)?;

            let mut builder = http::Response::builder().status(response.status());

            #[cfg(not(target_arch = "wasm32"))]
            {
                builder = builder.version(response.version());
            }

            for (name, value) in response.headers().iter() {
                builder = builder.header(name, value);
            }

            builder
                .body(response.bytes().await.map_err(Box::new)?.to_vec())
                .map_err(HttpClientError::Http)
        })
    }
}