1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
use crate::{
    rpc::{typed_data::Data, TypedData},
    FromVec,
};
use serde_derive::{Deserialize, Serialize};
use serde_json::{to_string, to_value, Value};

/// Represents the SignalR message output binding.
///
/// The following binding attributes are supported:
///
/// | Name         | Description                                                                                                                  |
/// |--------------|------------------------------------------------------------------------------------------------------------------------------|
/// | `name`       | The name of the parameter being bound.                                                                                       |
/// | `hub_name`   | The name of the SignalR hub that will receive the message.                                                                   |
/// | `connection` | The name of the app setting that contains the SignalR Service connection string. Defaults to `AzureSignalRConnectionString`. |
///
/// # Examples
///
/// This example implements an HTTP-triggered Azure Function that returns a SignalRMessage binding:
///
/// ```rust
/// use azure_functions::{
///     bindings::{HttpRequest, SignalRMessage},
///     func,
/// };
/// use serde_json::{to_value, Value};
///
/// #[func]
/// #[binding(name = "req", auth_level = "anonymous", methods = "post")]
/// #[binding(name = "$return", hub_name = "chat", connection = "myconnection")]
/// pub fn send_message(req: HttpRequest) -> SignalRMessage {
///     SignalRMessage {
///         user_id: req.query_params().get("user").map(|v| v.to_owned()),
///         group_name: req.query_params().get("group").map(|v| v.to_owned()),
///         target: "newMessage".to_owned(),
///         arguments: vec![req.query_params().get("message").map_or(Value::Null, |v| to_value(v).unwrap())],
///     }
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SignalRMessage {
    /// The optional user id to send the message to.
    pub user_id: Option<String>,
    /// The optional group name to send the message to.
    pub group_name: Option<String>,
    /// The target method name to invoke on each SignalR client.
    pub target: String,
    /// The arguments to pass to the target method.
    pub arguments: Vec<Value>,
}

#[doc(hidden)]
impl Into<TypedData> for SignalRMessage {
    fn into(self) -> TypedData {
        TypedData {
            data: Some(Data::Json(
                to_string(&self).expect("failed to convert SignalR message to JSON string"),
            )),
        }
    }
}

#[doc(hidden)]
impl FromVec<SignalRMessage> for TypedData {
    fn from_vec(vec: Vec<SignalRMessage>) -> Self {
        TypedData {
            data: Some(Data::Json(
                Value::Array(vec.into_iter().map(|m| to_value(m).unwrap()).collect()).to_string(),
            )),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::to_value;

    #[test]
    fn it_serializes_to_json() {
        let json = to_string(&SignalRMessage {
            user_id: Some("foo".to_owned()),
            group_name: Some("bar".to_owned()),
            target: "baz".to_owned(),
            arguments: vec![
                to_value(1).unwrap(),
                to_value("foo").unwrap(),
                to_value(false).unwrap(),
            ],
        })
        .unwrap();

        assert_eq!(
            json,
            r#"{"userId":"foo","groupName":"bar","target":"baz","arguments":[1,"foo",false]}"#
        );
    }

    #[test]
    fn it_converts_to_typed_data() {
        let message = SignalRMessage {
            user_id: Some("foo".to_owned()),
            group_name: Some("bar".to_owned()),
            target: "baz".to_owned(),
            arguments: vec![
                to_value(1).unwrap(),
                to_value("foo").unwrap(),
                to_value(false).unwrap(),
            ],
        };

        let data: TypedData = message.into();
        assert_eq!(
            data.data,
            Some(Data::Json(
                r#"{"userId":"foo","groupName":"bar","target":"baz","arguments":[1,"foo",false]}"#
                    .to_string()
            ))
        );
    }
}