use std::sync::Arc;
use serde::de::DeserializeOwned;
use serde_json::Value;
use crate::http::{HttpClient, ReqwestHttpClient};
pub(crate) struct ProviderHttpEngine {
api_key: String,
base_url: String,
http: Arc<dyn HttpClient>,
}
impl ProviderHttpEngine {
pub(crate) fn new(api_key: impl Into<String>, base_url: impl Into<String>) -> Self {
Self::with_http(api_key, base_url, Arc::new(ReqwestHttpClient::new()))
}
pub(crate) fn with_http(
api_key: impl Into<String>,
base_url: impl Into<String>,
http: Arc<dyn HttpClient>,
) -> Self {
Self {
api_key: api_key.into(),
base_url: base_url.into().trim_end_matches('/').to_string(),
http,
}
}
pub(crate) fn base_url(&self) -> &str {
&self.base_url
}
pub(crate) fn bearer_post<Resp: DeserializeOwned>(
&self,
url: &str,
body: &Value,
) -> Result<Resp, ProviderHttpError> {
let headers = [("Authorization", format!("Bearer {}", self.api_key))];
let value = self
.http
.post_json(url, &headers, body)
.map_err(|err| ProviderHttpError::Transport(err.to_string()))?;
serde_json::from_value(value).map_err(|err| ProviderHttpError::Parse(err.to_string()))
}
}
pub(crate) enum ProviderHttpError {
Transport(String),
Parse(String),
}