Skip to main content

jrpc_types/notification/
builder.rs

1//! This module implements a Builder class for the Request object.
2
3use crate::{error::Error, notification::Notification, params::Params};
4
5// =======================
6// Type State Structs
7// =======================
8pub struct MethodNone;
9pub struct Method(String);
10// =======================
11
12/// The Builder class for a Request object.
13pub struct Builder<M> {
14    method: M,
15    params: Option<Params>,
16}
17
18impl Default for Builder<MethodNone> {
19    fn default() -> Self {
20        Self::new()
21    }
22}
23
24impl Builder<MethodNone> {
25    pub fn new() -> Self {
26        Builder {
27            method: MethodNone,
28            params: None,
29        }
30    }
31}
32
33impl<M> Builder<M> {
34    pub fn params(self, p: serde_json::Value) -> Result<Builder<M>, Error> {
35        Ok(Builder {
36            method: self.method,
37            params: Some(Params::try_from(p)?),
38        })
39    }
40
41    pub fn params_serialize<T: serde::Serialize>(self, p: T) -> Result<Builder<M>, Error> {
42        let value = serde_json::to_value(p).map_err(Error::from)?;
43        let params = Params::try_from(value)?;
44        Ok(Builder {
45            method: self.method,
46            params: Some(params),
47        })
48    }
49
50    pub fn params_str(self, p: &str) -> Result<Builder<M>, Error> {
51        let params = Params::try_from(p)?;
52        Ok(Builder {
53            method: self.method,
54            params: Some(params),
55        })
56    }
57}
58
59impl Builder<MethodNone> {
60    pub fn method(self, m: &str) -> Builder<Method> {
61        Builder {
62            method: Method(m.to_string()),
63            params: self.params,
64        }
65    }
66}
67
68impl Builder<Method> {
69    pub fn build(self) -> Notification {
70        Notification {
71            jsonrpc: "2.0".to_string(),
72            method: self.method.0,
73            params: self.params,
74        }
75    }
76}