deribit_http/message/
response.rs1use 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#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize)]
11pub struct HttpResponseHandler;
12
13impl HttpResponseHandler {
14 pub fn new() -> Self {
16 Self
17 }
18
19 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 pub fn is_success(&self, response: &HttpResponse) -> bool {
36 response.status >= 200 && response.status < 300
37 }
38
39 pub fn extract_error<'a, T>(&self, api_response: &'a ApiResponse<T>) -> Option<&'a ApiError> {
41 api_response.error.as_ref()
42 }
43
44 pub fn extract_result<'a, T>(&self, api_response: &'a ApiResponse<T>) -> Option<&'a T> {
46 api_response.result.as_ref()
47 }
48
49 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 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}