signalrs_client_custom_auth/hub/
arguments.rs

1use super::invocation::{ArgumentsLeft, ExtractionError, FromInvocation, HubInvocation};
2use futures::Stream;
3use serde::de::DeserializeOwned;
4
5/// Stream of data from server to client
6///
7/// Can only appear as an argument to a hub method.
8/// It will be extracted from HubInvocation and automagically streamed.
9struct StreamArg<T>(Box<dyn Stream<Item = T>>);
10
11/// Represets a [`Hub`](crate::hub::Hub) method's argument.
12///
13/// Meant for all user defined types, as implementation for primitives should be provided out of the box.
14/// Should be derived alongside [`Deserialize`](serde::Deserialize) using [`HubArgument`](signalrs_derive::HubArgument) derive macro.
15///
16/// # Example
17/// ```rust,no_run
18/// use serde::Deserialize;
19/// use signalrs_derive::HubArgument;
20/// # use signalrs_client::hub::Hub;
21/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
22/// #     let hub = Hub::default().method("Send", print);    
23/// #     Ok(())
24/// # }
25/// # async fn print(_message: Data) {
26/// #    // do nothing
27/// # }
28///
29/// #[derive(Deserialize, HubArgument)]
30/// struct Data {
31///     f1: i32,
32///     f2: String
33/// }
34/// ```
35pub trait HubArgument {}
36
37impl<T> FromInvocation for T
38where
39    T: HubArgument + DeserializeOwned,
40{
41    fn try_from_invocation(request: &mut HubInvocation) -> Result<Self, ExtractionError> {
42        match &mut request.state.arguments {
43            ArgumentsLeft::Text(args) => {
44                let next = args.next().ok_or_else(|| ExtractionError::MissingArgs)?;
45                serde_json::from_value(next).map_err(|e| e.into())
46            }
47        }
48    }
49}
50
51impl<T> FromInvocation for StreamArg<T> {
52    fn try_from_invocation(_request: &mut HubInvocation) -> Result<Self, ExtractionError> {
53        // no body yet, here to ensure that Rust will not detect conflicting implementation in some cases
54        unimplemented!("not yet implemented")
55    }
56}
57
58macro_rules! impl_hub_argument {
59    ($($ty:ident),+) => {
60        $(
61            impl HubArgument for $ty {}
62        )+
63    };
64}
65
66impl_hub_argument!(usize, isize);
67impl_hub_argument!(f32, f64);
68impl_hub_argument!(i8, i16, i32, i64, i128);
69impl_hub_argument!(u8, u16, u32, u64, u128);
70impl_hub_argument!(String);