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<T: serde::Serialize>(self, p: T) -> Result<Builder<M>, Error> {
35        let value = serde_json::to_value(p).map_err(Error::from)?;
36        let params = Params::try_from(value)?;
37        Ok(Builder {
38            method: self.method,
39            params: Some(params),
40        })
41    }
42
43    pub fn params_str(self, p: &str) -> Result<Builder<M>, Error> {
44        let params = Params::try_from(p)?;
45        Ok(Builder {
46            method: self.method,
47            params: Some(params),
48        })
49    }
50}
51
52impl Builder<MethodNone> {
53    pub fn method(self, m: &str) -> Builder<Method> {
54        Builder {
55            method: Method(m.to_string()),
56            params: self.params,
57        }
58    }
59}
60
61impl Builder<Method> {
62    pub fn build(self) -> Notification {
63        Notification {
64            jsonrpc: "2.0".to_string(),
65            method: self.method.0,
66            params: self.params,
67        }
68    }
69}