pub mod endpoints;
use crate::client::endpoints::{Endpoint, BASE_URL};
use crate::errors::{ApiError, BrawlError};
use reqwest::Client;
pub struct BrawlClient {
pub(crate) http: Client,
pub(crate) api_key: String,
}
impl BrawlClient {
pub fn new(api_key: impl Into<String>) -> Self {
let client = Client::new();
Self {
http: client,
api_key: api_key.into(),
}
}
pub(crate) async fn fetch<T>(&self, endpoint: Endpoint) -> Result<T, BrawlError>
where
T: serde::de::DeserializeOwned,
{
let url = format!("{}{}", BASE_URL, endpoint);
let response = self
.http
.get(url)
.bearer_auth(&self.api_key)
.header(
"User-Agent",
format!("{}/{}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION")),
)
.send()
.await
.map_err(BrawlError::Network)?;
let status = response.status();
if status.is_success() {
response
.json::<T>()
.await
.map_err(BrawlError::Serialization)
} else {
let err_body = response
.json::<ApiError>()
.await
.map_err(BrawlError::Serialization)?;
Err(BrawlError::Api(err_body))
}
}
}