reqwest_enum/
jsonrpc.rs

1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3
4#[derive(Debug, Serialize, Deserialize)]
5pub struct JsonRpcRequest {
6    pub jsonrpc: &'static str,
7    pub id: JsonRpcId,
8    pub method: &'static str,
9    pub params: Vec<Value>,
10}
11
12impl JsonRpcRequest {
13    pub fn new(method: &'static str, params: Vec<Value>, id: u64) -> Self {
14        Self {
15            jsonrpc: "2.0",
16            id: JsonRpcId::Integer(id),
17            method,
18            params,
19        }
20    }
21}
22
23impl From<JsonRpcRequest> for reqwest::Body {
24    fn from(val: JsonRpcRequest) -> Self {
25        serde_json::to_vec(&val).unwrap().into()
26    }
27}
28
29#[derive(Debug, Serialize, Deserialize)]
30pub struct JsonRpcResponse<T> {
31    pub id: JsonRpcId,
32    pub jsonrpc: String,
33    pub result: T,
34}
35
36#[derive(Debug, Serialize, Deserialize)]
37pub struct JsonRpcErrorResponse {
38    pub jsonrpc: String,
39    pub id: JsonRpcId,
40    pub error: JsonRpcError,
41}
42
43#[derive(Debug, Serialize, Deserialize)]
44pub struct JsonRpcError {
45    pub code: i64,
46    pub message: String,
47}
48
49impl std::error::Error for JsonRpcError {}
50
51impl From<reqwest::Error> for JsonRpcError {
52    fn from(err: reqwest::Error) -> Self {
53        JsonRpcError {
54            code: -32603,
55            message: format!("Internal error ({})", err),
56        }
57    }
58}
59
60impl From<crate::Error> for JsonRpcError {
61    fn from(err: crate::Error) -> Self {
62        match err {
63            crate::Error::Reqwest(e) => {
64                // Reuse the existing From<reqwest::Error> for JsonRpcError
65                e.into()
66            }
67            #[cfg(feature = "middleware")]
68            crate::Error::ReqwestMiddleware(e) => JsonRpcError {
69                code: -32603, // Internal error
70                message: format!("Middleware error: {}", e),
71            },
72            crate::Error::SerdeJson(e) => JsonRpcError {
73                code: -32603, // Internal error (could also be Parse error -32700 depending on context)
74                message: format!("Serialization/deserialization error: {}", e),
75            },
76        }
77    }
78}
79
80impl std::fmt::Display for JsonRpcError {
81    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82        write!(f, "{} ({})", self.message, self.code)
83    }
84}
85
86#[derive(Debug, Serialize, Deserialize)]
87#[serde(untagged)]
88pub enum JsonRpcResult<T> {
89    Value(JsonRpcResponse<T>),
90    Error(JsonRpcErrorResponse),
91}
92
93#[derive(Debug, Serialize, Deserialize)]
94#[serde(untagged)]
95pub enum JsonRpcId {
96    Integer(u64),
97    String(String),
98}