use reqwest::Client;
use crate::clients::error::EngineError;
const ENGINE_API_ENDPOINT: &str = "/atlas_engine/api/v1";
#[derive(Clone)]
pub struct ApiClient {
pub http_client: Client,
engine_url: String,
auth_token: String,
}
impl ApiClient {
pub fn new(engine_url: &str, auth_token: &str) -> ApiClient {
let http_client = Client::new();
ApiClient {
http_client,
engine_url: engine_url.to_string(),
auth_token: auth_token.to_string(),
}
}
pub fn get_engine_url(&self) -> &str {
&self.engine_url
}
pub fn get_engine_api_endpoint(&self) -> &str {
ENGINE_API_ENDPOINT
}
pub fn get_auth_token(&self) -> &str {
&self.auth_token
}
pub async fn get<T>(&self, url: &str) -> Result<T, EngineError>
where
T: serde::de::DeserializeOwned,
{
let response = self
.http_client
.get(url)
.header("Authorization", self.get_auth_token())
.send()
.await?;
match response.status() {
reqwest::StatusCode::OK => Ok(response.json::<T>().await?),
_ => Err(response.json::<EngineError>().await?),
}
}
pub async fn post<T>(
&self,
url: &str,
body: Option<&serde_json::Value>,
) -> Result<T, EngineError>
where
T: serde::de::DeserializeOwned + Default,
{
let response = match body {
Some(body) => {
self.http_client
.post(url)
.header("Authorization", self.get_auth_token())
.json(body)
.send()
.await?
}
None => {
self.http_client
.post(url)
.header("Authorization", self.get_auth_token())
.send()
.await?
}
};
match response.status().as_u16() {
200..=299 => match response.content_length().unwrap_or_default() {
0 => Ok(serde_json::from_str("{}").unwrap_or_default()),
_ => Ok(response.json::<T>().await?),
},
_ => Err(response.json::<EngineError>().await?),
}
}
pub async fn delete<T>(&self, url: &str) -> Result<T, EngineError>
where
T: serde::de::DeserializeOwned + Default,
{
let response = self
.http_client
.delete(url)
.header("Authorization", self.get_auth_token())
.send()
.await?;
match response.status().as_u16() {
200..=299 => match response.content_length().unwrap_or_default() {
0 => Ok(serde_json::from_str("{}").unwrap_or_default()),
_ => Ok(response.json::<T>().await?),
},
_ => Err(response.json::<EngineError>().await?),
}
}
}