use crate::consts::{query_method, HEADER_CONTENT_TYPE, MEDIA_TYPE_JSON};
use crate::error::{Error, Result};
use crate::response::Discovery;
use reqwest::{Body, Client as HttpClient, Method, Response, Url};
use serde::de::DeserializeOwned;
use serde::Serialize;
#[derive(Clone, Debug)]
pub struct Client {
http: HttpClient,
base_url: Option<Url>,
}
impl Client {
pub fn new() -> Self {
Client {
http: HttpClient::new(),
base_url: None,
}
}
pub fn with_http_client(http: HttpClient) -> Self {
Client {
http,
base_url: None,
}
}
pub fn with_base_url(mut self, base: &str) -> Result<Self> {
self.base_url = Some(Url::parse(base).map_err(|e| Error::Invalid(e.to_string()))?);
Ok(self)
}
fn resolve(&self, url: &str) -> Result<Url> {
match &self.base_url {
Some(base) => base.join(url).map_err(|e| Error::Invalid(e.to_string())),
None => Url::parse(url).map_err(|e| Error::Invalid(e.to_string())),
}
}
pub async fn query(
&self,
url: &str,
content_type: &str,
body: impl Into<Body>,
) -> Result<Response> {
let target = self.resolve(url)?;
let resp = self
.http
.request(query_method(), target)
.header(HEADER_CONTENT_TYPE, content_type)
.body(body)
.send()
.await?;
Ok(resp)
}
pub async fn query_string(
&self,
url: &str,
content_type: &str,
body: impl Into<String>,
) -> Result<Response> {
self.query(url, content_type, body.into()).await
}
pub async fn query_json<T: Serialize + ?Sized>(
&self,
url: &str,
value: &T,
) -> Result<Response> {
let body = serde_json::to_vec(value)?;
self.query(url, MEDIA_TYPE_JSON, body).await
}
pub async fn query_json_into<T, R>(&self, url: &str, value: &T) -> Result<R>
where
T: Serialize + ?Sized,
R: DeserializeOwned,
{
let resp = self.query_json(url, value).await?;
let resp = check_status(resp).await?;
Ok(resp.json::<R>().await?)
}
pub async fn options(&self, url: &str) -> Result<Discovery> {
let target = self.resolve(url)?;
let resp = self.http.request(Method::OPTIONS, target).send().await?;
Ok(Discovery::from_headers(resp.headers()))
}
pub async fn fetch_result(&self, resp: &Response) -> Result<Response> {
self.fetch_relative(
resp,
crate::consts::HEADER_CONTENT_LOCATION,
Error::NoQueryResult,
)
.await
}
pub async fn fetch_equivalent(&self, resp: &Response) -> Result<Response> {
self.fetch_relative(
resp,
crate::consts::HEADER_LOCATION,
Error::NoEquivalentResource,
)
.await
}
async fn fetch_relative(
&self,
resp: &Response,
header: &str,
missing: Error,
) -> Result<Response> {
let reference = resp
.headers()
.get(header)
.and_then(|value| value.to_str().ok());
let reference = match reference {
Some(reference) => reference,
None => return Err(missing),
};
let target = resp
.url()
.join(reference)
.map_err(|e| Error::Invalid(e.to_string()))?;
Ok(self.http.get(target).send().await?)
}
}
impl Default for Client {
fn default() -> Self {
Self::new()
}
}
pub async fn check_status(resp: Response) -> Result<Response> {
if resp.status().is_success() {
Ok(resp)
} else {
let status = resp.status().as_u16();
let body = resp.text().await.unwrap_or_default();
Err(Error::Status { status, body })
}
}