use reqwest;
use serde::de::DeserializeOwned;
use crate::Error;
const API_BASE: &str = "https://api.minehut.com/";
pub(crate) async fn req_data<T: DeserializeOwned>(path: &str) -> Result<T, Error> {
let path = match path.starts_with("https") {
false => format!("{}{}", API_BASE, path),
true => path.to_string()
};
let res = reqwest::get(&path).await.map_err(Error::Http)?;
if res.status() != 200{
return Err(Error::FailedOp(format!("Failed to get data from \"{path}\"")))
}
let body: T = res.json().await.map_err(Error::Json)?;
Ok(body)
}
pub(crate) async fn req_client_data<T>(mh_client: &crate::Client, path: &str) -> Result<T, Error>
where T: DeserializeOwned
{
let client = reqwest::Client::new();
let res = client.get(format!("{}{}", API_BASE, path))
.header("authorization", &mh_client.auth_token)
.header("x-session-id", &mh_client.session_id)
.send()
.await.map_err(Error::Http)?;
if res.status() != 200 {
return Err(Error::FailedOp(format!{"Failed to get data from \"{path}\""}))
}
let body: T = res.json().await.map_err(Error::Json)?;
Ok(body)
}
pub(crate) async fn post(mh_client: &crate::Client, path: &str) -> Result<(), Error> {
let client = reqwest::Client::new();
let res = client.post(&format!("{}{}", API_BASE, path))
.header("authorization", &mh_client.auth_token)
.header("x-session-id", &mh_client.session_id)
.send().await.map_err(Error::Http)?;
if res.status() != 200 {
return Err(Error::FailedOp(format!("Failed to post data at \"{path}\"")));
}
Ok(())
}