use crate::error::HttpError;
use crate::model::response::api_response::{ApiResponse, HttpResponse};
use crate::model::types::ApiError;
use pretty_simple_display::{DebugPretty, DisplaySimple};
use serde::{Deserialize, Serialize};
#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize)]
pub struct HttpResponseHandler;
impl HttpResponseHandler {
pub fn new() -> Self {
Self
}
pub fn parse_response<T>(&self, response: &HttpResponse) -> Result<ApiResponse<T>, HttpError>
where
T: for<'de> Deserialize<'de>,
{
if response.status >= 400 {
return Err(HttpError::RequestFailed(format!(
"HTTP {} - {}",
response.status, response.body
)));
}
serde_json::from_str(&response.body).map_err(|e| HttpError::InvalidResponse(e.to_string()))
}
pub fn is_success(&self, response: &HttpResponse) -> bool {
response.status >= 200 && response.status < 300
}
pub fn extract_error<'a, T>(&self, api_response: &'a ApiResponse<T>) -> Option<&'a ApiError> {
api_response.error.as_ref()
}
pub fn extract_result<'a, T>(&self, api_response: &'a ApiResponse<T>) -> Option<&'a T> {
api_response.result.as_ref()
}
pub fn handle_rate_limit(&self, response: &HttpResponse) -> Result<(), HttpError> {
if response.status == 429 {
return Err(HttpError::RateLimitExceeded);
}
Ok(())
}
pub fn handle_auth_error(&self, response: &HttpResponse) -> Result<(), HttpError> {
if response.status == 401 || response.status == 403 {
return Err(HttpError::AuthenticationFailed(
"Authentication failed or expired".to_string(),
));
}
Ok(())
}
}
impl Default for HttpResponseHandler {
fn default() -> Self {
Self::new()
}
}