use crate::error::ApiError;
use anyhow::{anyhow, Context, Result};
use reqwest::StatusCode;
use serde::de::DeserializeOwned;
use serde_json::from_str;
use std::any::type_name;
pub struct Response(pub reqwest::Response);
impl Response {
pub async fn json<T: DeserializeOwned>(self) -> Result<T> {
let body = self.0.text().await.context("Cannot load body as a text")?;
from_str(&body).map_err(|error| {
anyhow!(error).context(format!("Cannot parse {} from {}", type_name::<T>(), body))
})
}
pub async fn error_for_status(self) -> Result<Self> {
let Err(error) = self.0.error_for_status_ref() else {
return Ok(self);
};
let status = self.0.status();
let body = self
.0
.text()
.await
.context("Cannot load error response from server")?;
let api_error = if status == StatusCode::UNAUTHORIZED {
ApiError {
error_code: "UNAUTHORIZED".to_owned(),
message: body,
}
} else {
from_str::<ApiError>(&body)
.with_context(|| format!("Cannot parse ApiError from {}", body))?
};
Err(anyhow!(error).context(api_error))
}
}