Skip to main content

http_query/
client.rs

1//! An async QUERY client built on [`reqwest`].
2
3use crate::consts::{query_method, HEADER_CONTENT_TYPE, MEDIA_TYPE_JSON};
4use crate::error::{Error, Result};
5use crate::response::Discovery;
6use reqwest::{Body, Client as HttpClient, Method, Response, Url};
7use serde::de::DeserializeOwned;
8use serde::Serialize;
9
10/// An async client for sending HTTP QUERY requests.
11///
12/// The client wraps a [`reqwest::Client`]; clone it freely (it is cheap and
13/// shares the underlying connection pool).
14#[derive(Clone, Debug)]
15pub struct Client {
16    http: HttpClient,
17    base_url: Option<Url>,
18}
19
20impl Client {
21    /// Creates a client with a default [`reqwest::Client`].
22    pub fn new() -> Self {
23        Client {
24            http: HttpClient::new(),
25            base_url: None,
26        }
27    }
28
29    /// Creates a client wrapping an existing [`reqwest::Client`].
30    pub fn with_http_client(http: HttpClient) -> Self {
31        Client {
32            http,
33            base_url: None,
34        }
35    }
36
37    /// Sets a base URL used to resolve relative request URLs.
38    pub fn with_base_url(mut self, base: &str) -> Result<Self> {
39        self.base_url = Some(Url::parse(base).map_err(|e| Error::Invalid(e.to_string()))?);
40        Ok(self)
41    }
42
43    fn resolve(&self, url: &str) -> Result<Url> {
44        match &self.base_url {
45            Some(base) => base.join(url).map_err(|e| Error::Invalid(e.to_string())),
46            None => Url::parse(url).map_err(|e| Error::Invalid(e.to_string())),
47        }
48    }
49
50    /// Sends a QUERY request with a raw body and the given content type.
51    pub async fn query(
52        &self,
53        url: &str,
54        content_type: &str,
55        body: impl Into<Body>,
56    ) -> Result<Response> {
57        let target = self.resolve(url)?;
58        let resp = self
59            .http
60            .request(query_method(), target)
61            .header(HEADER_CONTENT_TYPE, content_type)
62            .body(body)
63            .send()
64            .await?;
65        Ok(resp)
66    }
67
68    /// Sends a QUERY request with a string body.
69    pub async fn query_string(
70        &self,
71        url: &str,
72        content_type: &str,
73        body: impl Into<String>,
74    ) -> Result<Response> {
75        self.query(url, content_type, body.into()).await
76    }
77
78    /// Sends a QUERY request whose body is `value` serialized to JSON.
79    pub async fn query_json<T: Serialize + ?Sized>(
80        &self,
81        url: &str,
82        value: &T,
83    ) -> Result<Response> {
84        let body = serde_json::to_vec(value)?;
85        self.query(url, MEDIA_TYPE_JSON, body).await
86    }
87
88    /// Sends a JSON QUERY request and decodes a JSON response, validating the
89    /// status first.
90    pub async fn query_json_into<T, R>(&self, url: &str, value: &T) -> Result<R>
91    where
92        T: Serialize + ?Sized,
93        R: DeserializeOwned,
94    {
95        let resp = self.query_json(url, value).await?;
96        let resp = check_status(resp).await?;
97        Ok(resp.json::<R>().await?)
98    }
99
100    /// Issues an `OPTIONS` request and reports QUERY support from the response.
101    pub async fn options(&self, url: &str) -> Result<Discovery> {
102        let target = self.resolve(url)?;
103        let resp = self.http.request(Method::OPTIONS, target).send().await?;
104        Ok(Discovery::from_headers(resp.headers()))
105    }
106
107    /// Performs a GET on the stored result of the query (`Content-Location`,
108    /// RFC 10008 §2.3), resolved against the original request URL.
109    pub async fn fetch_result(&self, resp: &Response) -> Result<Response> {
110        self.fetch_relative(
111            resp,
112            crate::consts::HEADER_CONTENT_LOCATION,
113            Error::NoQueryResult,
114        )
115        .await
116    }
117
118    /// Performs a GET on the equivalent resource (`Location`, RFC 10008 §2.4),
119    /// which re-runs the query without resending the body.
120    pub async fn fetch_equivalent(&self, resp: &Response) -> Result<Response> {
121        self.fetch_relative(
122            resp,
123            crate::consts::HEADER_LOCATION,
124            Error::NoEquivalentResource,
125        )
126        .await
127    }
128
129    async fn fetch_relative(
130        &self,
131        resp: &Response,
132        header: &str,
133        missing: Error,
134    ) -> Result<Response> {
135        let reference = resp
136            .headers()
137            .get(header)
138            .and_then(|value| value.to_str().ok());
139        let reference = match reference {
140            Some(reference) => reference,
141            None => return Err(missing),
142        };
143        let target = resp
144            .url()
145            .join(reference)
146            .map_err(|e| Error::Invalid(e.to_string()))?;
147        Ok(self.http.get(target).send().await?)
148    }
149}
150
151impl Default for Client {
152    fn default() -> Self {
153        Self::new()
154    }
155}
156
157/// Validates a response's status, turning a non-2xx status into
158/// [`Error::Status`] (consuming the body for the error message).
159pub async fn check_status(resp: Response) -> Result<Response> {
160    if resp.status().is_success() {
161        Ok(resp)
162    } else {
163        let status = resp.status().as_u16();
164        let body = resp.text().await.unwrap_or_default();
165        Err(Error::Status { status, body })
166    }
167}