use std::borrow::Cow;
#[cfg(any(feature = "async", doc))]
use async_trait::async_trait;
use serde::de::DeserializeOwned;
#[cfg(any(feature = "ureq", doc))]
use crate::ureq_client::handle_ureq_response;
use crate::errors::HttpError;
pub trait Endpoint {
type Output: DeserializeOwned;
fn method(&self) -> &str {
"GET"
}
fn endpoint(&self) -> Cow<'static, str>;
fn url(&self) -> Result<url::Url, HttpError> {
Ok(url::Url::parse(&self.endpoint()).unwrap())
}
#[cfg(any(feature = "ureq", doc))]
fn ureq_client(&self, client: &ureq::Agent) -> Result<Self::Output, HttpError> {
let url_endpoint = self.url()?;
handle_ureq_response(client.request(self.method(), url_endpoint.as_str()).call())
}
#[cfg(any(feature = "ureq", doc))]
fn ureq(&self, token: &str) -> Result<Self::Output, HttpError> {
use crate::constants::TOKEN_KEY;
let url_endpoint = self.url()?;
handle_ureq_response(
ureq::request(self.method(), url_endpoint.as_str())
.set(TOKEN_KEY, token)
.call(),
)
}
#[cfg(any(all(feature = "reqwest", feature = "sync"), doc))]
fn reqwest_client(&self, client: &reqwest::blocking::Client) -> Result<Self::Output, HttpError> {
let url_endpoint = self.url()?;
crate::reqwest_blocking_client::handle_reqwest_response_blocking::<Self::Output>(
client.get(url_endpoint.as_str()).send(),
)
}
#[cfg(any(all(feature = "reqwest", feature = "sync"), doc))]
fn reqwest(&self, token: &str) -> Result<Self::Output, HttpError> {
use http::header;
use crate::constants::TOKEN_KEY;
let url_endpoint = self.url()?;
let mut headers = header::HeaderMap::new();
headers.insert(TOKEN_KEY, header::HeaderValue::from_str(token).unwrap());
let client = reqwest::blocking::ClientBuilder::new()
.default_headers(headers)
.build()
.unwrap();
crate::reqwest_blocking_client::handle_reqwest_response_blocking::<Self::Output>(
client.get(url_endpoint.as_str()).send(),
)
}
}
#[cfg(any(all(feature = "reqwest", feature = "async"), doc))]
#[async_trait]
pub trait EndpointAsync: Endpoint {
#[cfg(any(all(feature = "reqwest", feature = "async"), doc))]
async fn reqwest_client_async(
&self,
client: &reqwest::Client,
) -> Result<Self::Output, HttpError> {
let url_endpoint = self.url()?;
crate::reqwest_async_client::handle_reqwest_response::<Self::Output>(
client.get(url_endpoint.as_str()).send().await,
)
.await
}
#[cfg(any(all(feature = "reqwest", feature = "async"), doc))]
async fn reqwest_async(&self, token: &str) -> Result<Self::Output, HttpError> {
let url_endpoint = self.url()?;
let mut headers = http::header::HeaderMap::new();
headers.insert(
crate::constants::TOKEN_KEY,
http::header::HeaderValue::from_str(token).unwrap(),
);
let client = reqwest::ClientBuilder::new()
.default_headers(headers)
.build()
.unwrap();
crate::reqwest_async_client::handle_reqwest_response::<Self::Output>(
client.get(url_endpoint.as_str()).send().await,
)
.await
}
}