async_json_rpc/
objects.rs1use serde::{Deserialize, Serialize};
2pub use serde_json::Error as JsonError;
3
4#[derive(Clone, Debug, PartialEq, Deserialize)]
6pub struct RpcError {
7 pub code: i32,
9 pub message: String,
11 pub data: Option<serde_json::Value>,
13}
14
15#[derive(Debug, Clone, PartialEq, Serialize)]
17pub struct Request {
18 pub method: String,
19 pub params: serde_json::Value,
20 pub id: serde_json::Value,
21 pub jsonrpc: String,
22}
23
24impl Request {
25 pub fn build() -> RequestBuilder {
26 RequestBuilder::default()
27 }
28}
29
30#[derive(Default)]
31pub struct RequestBuilder {
32 id: Option<serde_json::Value>,
33 method: Option<String>,
34 params: Option<serde_json::Value>,
35 json_rpc: Option<String>,
36}
37
38#[derive(Debug)]
39pub struct IncompleteRequest;
40
41impl RequestBuilder {
42 pub fn method<S: Into<String>>(mut self, method: S) -> Self {
43 self.method = Some(method.into());
44 self
45 }
46
47 pub fn id<I: Into<serde_json::Value>>(mut self, id: I) -> Self {
48 self.id = Some(id.into());
49 self
50 }
51
52 pub fn params<V: Into<serde_json::Value>>(mut self, params: V) -> Self {
53 self.params = Some(params.into());
54 self
55 }
56
57 pub fn jsonrpc<S: Into<String>>(mut self, json_rpc: S) -> Self {
58 self.json_rpc = Some(json_rpc.into());
59 self
60 }
61
62 pub fn finish(self) -> Result<Request, IncompleteRequest> {
63 let jsonrpc = if let Some(jsonrpc) = self.json_rpc {
64 jsonrpc
65 } else {
66 "2.0".to_string()
67 };
68 if let (Some(id), Some(method)) = (self.id, self.method) {
69 if let Some(params) = self.params {
70 Ok(Request {
71 id,
72 method,
73 params,
74 jsonrpc,
75 })
76 } else {
77 Ok(Request {
78 id,
79 method,
80 params: serde_json::Value::Null,
81 jsonrpc,
82 })
83 }
84 } else {
85 Err(IncompleteRequest)
86 }
87 }
88}
89
90#[derive(Debug, Clone, PartialEq, Deserialize)]
92pub struct Response {
93 pub result: Option<serde_json::Value>,
94 pub error: Option<RpcError>,
95 pub id: serde_json::Value,
96 pub jsonrpc: Option<String>,
97}
98
99impl Response {
100 pub fn result<T: serde::de::DeserializeOwned>(&self) -> Option<Result<T, JsonError>> {
102 self.result.as_ref().map(T::deserialize)
103 }
104
105 pub fn into_result<T: serde::de::DeserializeOwned>(self) -> Option<Result<T, JsonError>> {
107 self.result.map(serde_json::from_value)
108 }
109
110 pub fn error(self) -> Option<RpcError> {
112 self.error
113 }
114
115 pub fn is_result(&self) -> bool {
117 self.result.is_some()
118 }
119
120 pub fn is_error(&self) -> bool {
122 self.error.is_some()
123 }
124}