use reqwest::Response;
use serde::{Deserialize, de::DeserializeOwned};
use thiserror::Error;
#[derive(Error, Debug)]
pub enum ApiError {
#[error("Fail `{0:?}`")]
Fail(FailError),
#[error("Fail `{0}`")]
Reqwest(#[from] reqwest::Error),
}
#[derive(Debug, Deserialize)]
struct FailResponse {
error: FailError,
}
#[derive(Debug, Deserialize)]
pub struct FailError {
pub code: u16,
pub message: String,
}
pub(crate) async fn check_response<T: DeserializeOwned>(response: Response) -> Result<T, ApiError> {
if response.status() != 200 {
let error = response.json::<FailResponse>().await?;
Err(ApiError::Fail(error.error))
} else {
response.json().await.map_err(Into::into)
}
}