1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
use super::{Id, Method, Version};
use crate::{prelude::*, Error};
use core::fmt::Debug;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
pub trait Request: Debug + DeserializeOwned + Serialize + Sized + Send {
type Response: super::response::Response;
fn method(&self) -> Method;
fn into_json(self) -> String {
Wrapper::new(self).into_json()
}
fn from_string(s: impl AsRef<[u8]>) -> Result<Self, Error> {
let wrapper: Wrapper<Self> = serde_json::from_slice(s.as_ref()).map_err(Error::serde)?;
Ok(wrapper.params)
}
}
pub trait SimpleRequest: Request {}
#[derive(Debug, Deserialize, Serialize)]
pub struct Wrapper<R> {
jsonrpc: Version,
id: Id,
method: Method,
params: R,
}
impl<R> Wrapper<R>
where
R: Request,
{
pub fn new(request: R) -> Self {
Self::new_with_id(Id::uuid_v4(), request)
}
pub(crate) fn new_with_id(id: Id, request: R) -> Self {
Self {
jsonrpc: Version::current(),
id,
method: request.method(),
params: request,
}
}
pub fn id(&self) -> &Id {
&self.id
}
pub fn params(&self) -> &R {
&self.params
}
pub fn into_json(self) -> String {
serde_json::to_string_pretty(&self).unwrap()
}
}