plexus_client/params.rs
1//! The by-name params object a typed call sends.
2
3use serde::Serialize;
4use serde_json::{Map, Value};
5
6use crate::error::ClientError;
7
8/// Builds a call's params object from typed arguments — what a generated
9/// client method does with its parameters before it calls the transport.
10///
11/// Keys are the method's parameter names, which are what its schema
12/// declares. An `Option` parameter that is `None` is **omitted**, not sent
13/// as `null` ([`optional`](Self::optional)): the shape a server with
14/// `skip_serializing_if = "Option::is_none"` sends, and the one menger's
15/// REST tests assert.
16///
17/// The first argument that does not serialize is kept as
18/// [`ClientError::Encode`] and [`build`](Self::build) returns it — nothing is
19/// sent, and nothing panics (a panic in a wasm32 consumer is an
20/// unrecoverable trap).
21///
22/// ```
23/// use plexus_client::Params;
24///
25/// let params = Params::new()
26/// .param("id", "MNG-2")
27/// .optional("epic", None::<String>)
28/// .build()
29/// .unwrap();
30/// assert_eq!(params, serde_json::json!({"id": "MNG-2"}));
31/// ```
32#[derive(Debug, Default)]
33pub struct Params {
34 map: Map<String, Value>,
35 error: Option<ClientError>,
36}
37
38impl Params {
39 /// An empty params object — what a method with no parameters sends.
40 pub fn new() -> Self {
41 Self::default()
42 }
43
44 /// Add `name` with `value`, always.
45 pub fn param<V: Serialize>(mut self, name: &'static str, value: V) -> Self {
46 if self.error.is_none() {
47 match serde_json::to_value(value) {
48 Ok(json) => {
49 self.map.insert(name.to_string(), json);
50 }
51 Err(e) => {
52 self.error = Some(ClientError::Encode {
53 param: name,
54 message: e.to_string(),
55 })
56 }
57 }
58 }
59 self
60 }
61
62 /// Add `name` when `value` is `Some`; omit it when `None`.
63 pub fn optional<V: Serialize>(self, name: &'static str, value: Option<V>) -> Self {
64 match value {
65 Some(value) => self.param(name, value),
66 None => self,
67 }
68 }
69
70 /// The params object, or the first argument that would not encode.
71 pub fn build(self) -> Result<Value, ClientError> {
72 match self.error {
73 Some(e) => Err(e),
74 None => Ok(Value::Object(self.map)),
75 }
76 }
77}