iamgroot/
jsonrpc.rs

1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3
4const V2: &str = "2.0";
5
6#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
7pub struct Request {
8    pub jsonrpc: String,
9    pub method: String,
10    #[serde(skip_serializing_if = "Option::is_none")]
11    pub params: Option<Value>,
12    #[serde(skip_serializing_if = "Option::is_none")]
13    pub id: Option<Id>,
14}
15
16impl Request {
17    pub fn new(method: String, params: Value) -> Self {
18        Self {
19            jsonrpc: V2.to_string(),
20            method,
21            params: Some(params),
22            id: None,
23        }
24    }
25
26    pub fn with_id(self, id: Id) -> Self {
27        Self {
28            id: Some(id),
29            ..self
30        }
31    }
32}
33
34#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
35pub struct Response {
36    pub jsonrpc: String,
37    #[serde(skip_serializing_if = "Option::is_none")]
38    pub result: Option<Value>,
39    #[serde(skip_serializing_if = "Option::is_none")]
40    pub error: Option<Error>,
41    #[serde(skip_serializing_if = "Option::is_none")]
42    pub id: Option<Id>,
43}
44
45impl Response {
46    pub fn result(value: Value) -> Self {
47        Self {
48            jsonrpc: V2.to_string(),
49            result: Some(value),
50            error: None,
51            id: None,
52        }
53    }
54
55    pub fn error(code: i64, message: &str) -> Self {
56        Self {
57            jsonrpc: V2.to_string(),
58            result: None,
59            error: Some(Error {
60                code,
61                message: message.to_string(),
62            }),
63            id: None,
64        }
65    }
66
67    pub fn with_id(self, id: Id) -> Self {
68        Self {
69            id: Some(id),
70            ..self
71        }
72    }
73}
74
75#[derive(
76    Clone, Debug, Deserialize, Serialize, Eq, PartialEq, thiserror::Error,
77)]
78#[error("JSON-RPC error: code={code} message='{message}'")]
79pub struct Error {
80    pub code: i64,
81    pub message: String,
82}
83
84impl Error {
85    pub fn new(code: i64, message: String) -> Self {
86        Self { code, message }
87    }
88}
89
90#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
91#[serde(untagged)]
92pub enum Id {
93    Number(i64),
94    String(String),
95}