1use 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#[derive(Clone, Debug)]
15pub struct Client {
16 http: HttpClient,
17 base_url: Option<Url>,
18}
19
20impl Client {
21 pub fn new() -> Self {
23 Client {
24 http: HttpClient::new(),
25 base_url: None,
26 }
27 }
28
29 pub fn with_http_client(http: HttpClient) -> Self {
31 Client {
32 http,
33 base_url: None,
34 }
35 }
36
37 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 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 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 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 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 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 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 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
157pub 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}