deribit_http/message/
response.rs

1//! HTTP response message handling
2
3use crate::error::HttpError;
4use crate::model::response::api_response::{ApiResponse, HttpResponse};
5use crate::model::types::ApiError;
6use pretty_simple_display::{DebugPretty, DisplaySimple};
7use serde::{Deserialize, Serialize};
8
9/// Response handler for HTTP messages
10#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize)]
11pub struct HttpResponseHandler;
12
13impl HttpResponseHandler {
14    /// Create a new response handler
15    pub fn new() -> Self {
16        Self
17    }
18
19    /// Parse HTTP response
20    pub fn parse_response<T>(&self, response: &HttpResponse) -> Result<ApiResponse<T>, HttpError>
21    where
22        T: for<'de> Deserialize<'de>,
23    {
24        if response.status >= 400 {
25            return Err(HttpError::RequestFailed(format!(
26                "HTTP {} - {}",
27                response.status, response.body
28            )));
29        }
30
31        serde_json::from_str(&response.body).map_err(|e| HttpError::InvalidResponse(e.to_string()))
32    }
33
34    /// Check if response is successful
35    pub fn is_success(&self, response: &HttpResponse) -> bool {
36        response.status >= 200 && response.status < 300
37    }
38
39    /// Extract error from API response
40    pub fn extract_error<'a, T>(&self, api_response: &'a ApiResponse<T>) -> Option<&'a ApiError> {
41        api_response.error.as_ref()
42    }
43
44    /// Extract result from API response
45    pub fn extract_result<'a, T>(&self, api_response: &'a ApiResponse<T>) -> Option<&'a T> {
46        api_response.result.as_ref()
47    }
48
49    /// Handle rate limiting
50    pub fn handle_rate_limit(&self, response: &HttpResponse) -> Result<(), HttpError> {
51        if response.status == 429 {
52            return Err(HttpError::RateLimitExceeded);
53        }
54        Ok(())
55    }
56
57    /// Handle authentication errors
58    pub fn handle_auth_error(&self, response: &HttpResponse) -> Result<(), HttpError> {
59        if response.status == 401 || response.status == 403 {
60            return Err(HttpError::AuthenticationFailed(
61                "Authentication failed or expired".to_string(),
62            ));
63        }
64        Ok(())
65    }
66}
67
68impl Default for HttpResponseHandler {
69    fn default() -> Self {
70        Self::new()
71    }
72}