use reqwest::{Client, Response};
use serde::Serialize;
use crate::config::Auth0Config;
use crate::error::AppError;
pub struct HttpClient {
client: Client,
base_url: String,
}
impl HttpClient {
pub fn new(config: &Auth0Config) -> Self {
Self {
client: Client::new(),
base_url: format!("https://{}", config.auth0_domain),
}
}
fn url(&self, path: &str) -> String {
format!("{}{}", self.base_url.trim_end_matches('/'), path)
}
pub async fn get(&self, path: &str) -> Result<Response, AppError> {
Ok(self.client.get(self.url(path)).send().await?)
}
pub async fn get_authorized(&self, path: &str, bearer_token: &str) -> Result<Response, AppError> {
Ok(self
.client
.get(self.url(path))
.bearer_auth(bearer_token)
.send()
.await?)
}
pub async fn post<B: Serialize>(&self, path: &str, body: &B) -> Result<Response, AppError> {
Ok(self.client.post(self.url(path)).json(body).send().await?)
}
pub async fn post_authorized<B: Serialize>(
&self,
path: &str,
body: &B,
bearer_token: &str,
) -> Result<Response, AppError> {
Ok(self
.client
.post(self.url(path))
.bearer_auth(bearer_token)
.json(body)
.send()
.await?)
}
pub async fn put<B: Serialize>(&self, path: &str, body: &B) -> Result<Response, AppError> {
Ok(self.client.put(self.url(path)).json(body).send().await?)
}
pub async fn patch<B: Serialize>(&self, path: &str, body: &B) -> Result<Response, AppError> {
Ok(self.client.patch(self.url(path)).json(body).send().await?)
}
pub async fn patch_authorized<B: Serialize>(
&self,
path: &str,
body: &B,
bearer_token: &str,
) -> Result<Response, AppError> {
Ok(self
.client
.patch(self.url(path))
.bearer_auth(bearer_token)
.json(body)
.send()
.await?)
}
pub async fn delete(&self, path: &str) -> Result<Response, AppError> {
Ok(self.client.delete(self.url(path)).send().await?)
}
}