rpc_router/params/
into_params.rs

1use crate::{Error, Result};
2use serde::de::DeserializeOwned;
3use serde_json::Value;
4
5/// `IntoParams` allows for converting an `Option<Value>` into
6/// the necessary type for RPC handler parameters.
7/// The default implementation below will result in failure if the value is `None`.
8/// For customized behavior, users can implement their own `into_params`
9/// method.
10pub trait IntoParams: DeserializeOwned + Send {
11	fn into_params(value: Option<Value>) -> Result<Self> {
12		match value {
13			Some(value) => Ok(serde_json::from_value(value).map_err(Error::ParamsParsing)?),
14			None => Err(Error::ParamsMissingButRequested),
15		}
16	}
17}
18
19/// Marker trait with a blanket implementation that return T::default
20/// if the `params: Option<Value>` is none.
21pub trait IntoDefaultRpcParams: DeserializeOwned + Send + Default {}
22
23impl<P> IntoParams for P
24where
25	P: IntoDefaultRpcParams,
26{
27	fn into_params(value: Option<Value>) -> Result<Self> {
28		match value {
29			Some(value) => Ok(serde_json::from_value(value).map_err(Error::ParamsParsing)?),
30			None => Ok(Self::default()),
31		}
32	}
33}
34
35// region:    --- Blanket implementation
36
37// IMPORTANT: Probably need to be put below a feature, like `with-blanket-option-params`
38
39/// Implements `IntoRpcParams` for any type that also implements `IntoRpcParams`.
40///
41/// Note: Application code might prefer to avoid this blanket implementation.
42impl<D> IntoParams for Option<D>
43where
44	D: DeserializeOwned + Send,
45	D: IntoParams,
46{
47	fn into_params(value: Option<Value>) -> Result<Self> {
48		let value = value
49			.map(|v| serde_json::from_value(v))
50			.transpose()
51			.map_err(Error::ParamsParsing)?;
52		Ok(value)
53	}
54}
55
56// IMPORTANT: Probably need to be put below a feature, like `with-blanket-value-params`
57
58/// This is the IntoRpcParams implementation for serde_json Value.
59///
60/// Note: As above, this might not be a capability app code might want to
61///       allow for rpc_handlers, prefering to have everything strongly type.
62impl IntoParams for Value {}
63
64// endregion: --- Blanket implementation