Skip to main content

simple_jsonrpc_client/
macros.rs

1#[macro_export]
2macro_rules! jsonrpc {
3    (
4        $(#[$struct_attr:meta])*
5        pub struct $struct_name:ident {$(
6            $(#[$attr:meta])*
7            pub fn $method:ident(&$selff:ident $(, $arg_name:ident: $arg_ty:ty)*)
8                -> $return_ty:ty;
9        )*}
10    ) => (
11        $(#[$struct_attr])*
12        pub struct $struct_name {
13            pub client: reqwest::blocking::Client,
14            pub url: reqwest::Url,
15            pub id_generator: $crate::id_generator::IdGenerator,
16        }
17
18        impl $struct_name {
19            pub fn new(uri: &str, client: reqwest::blocking::Client) -> Self {
20                let url = reqwest::Url::parse(uri).expect("uri");
21                let id_generator = $crate::id_generator::IdGenerator::new();
22                $struct_name { url, id_generator, client, }
23            }
24
25            $(
26                $(#[$attr])*
27                pub fn $method(&$selff $(, $arg_name: $arg_ty)*) -> Result<$return_ty, $crate::error::Error> {
28                    let method = String::from(stringify!($method));
29                    let params = serialize_parameters!($($arg_name,)*);
30                    let id = $selff.id_generator.next();
31
32                    let mut req_json = serde_json::Map::new();
33                    req_json.insert("id".to_owned(), serde_json::json!(id));
34                    req_json.insert("jsonrpc".to_owned(), serde_json::json!("2.0"));
35                    req_json.insert("method".to_owned(), serde_json::json!(method));
36                    req_json.insert("params".to_owned(), params);
37
38                    let mut resp = $selff.client.post($selff.url.clone()).json(&req_json).send()?;
39                    let output = resp.json::<jsonrpc_core::response::Output>()?;
40                    match output {
41                        jsonrpc_core::response::Output::Success(success) => {
42                            serde_json::from_value(success.result).map_err(Into::into)
43                        },
44                        jsonrpc_core::response::Output::Failure(failure) => {
45                            Err(failure.error.into())
46                        }
47                    }
48                }
49            )*
50        }
51    )
52}
53
54#[doc(hidden)]
55#[macro_export]
56macro_rules! serialize_parameters {
57    () => ( serde_json::Value::Null );
58    ($($arg_name:ident,)+) => ( serde_json::to_value(($($arg_name,)+))?)
59}