azure_functions/bindings/generic_trigger.rs
1use crate::{generic::Value, rpc::TypedData};
2use std::collections::HashMap;
3
4/// Represents a generic trigger binding.
5///
6/// The following binding attributes are supported:
7///
8/// | Name | Description |
9/// |-------------------------|----------------------------------------------------------------------------------------------------------------------------|
10/// | `type` | The binding type. |
11/// | `name` | The name of the parameter being bound. |
12/// | `*` | The additional binding attributes specific to the binding type. Supported value types are strings, booleans, and integers. |
13///
14/// # Examples
15///
16/// An example of using a `GenericTrigger` binding instead of a `CosmosDbTrigger` binding:
17///
18/// ```rust
19/// use azure_functions::{bindings::GenericTrigger, func, generic::Value};
20/// use log::info;
21///
22/// #[func]
23/// #[binding(
24/// type = "cosmosDBTrigger",
25/// name = "trigger",
26/// connectionStringSetting = "connection",
27/// databaseName = "exampledb",
28/// collectionName = "documents",
29/// createLeaseCollectionIfNotExists = true
30/// )]
31/// pub fn log_documents(trigger: GenericTrigger) {
32/// match trigger.data {
33/// Value::Json(v) => {
34/// info!("{}", v);
35/// }
36/// _ => panic!("expected JSON for Cosmos DB trigger data"),
37/// }
38/// }
39/// ```
40#[derive(Debug, Clone)]
41pub struct GenericTrigger {
42 /// The trigger binding data.
43 pub data: Value,
44 /// The trigger metadata.
45 pub metadata: HashMap<String, Value>,
46}
47
48impl GenericTrigger {
49 #[doc(hidden)]
50 pub fn new(data: TypedData, metadata: HashMap<String, TypedData>) -> Self {
51 let mut md = HashMap::with_capacity(metadata.len());
52 for (k, v) in metadata.into_iter() {
53 md.insert(k, v.into());
54 }
55 GenericTrigger {
56 data: data.into(),
57 metadata: md,
58 }
59 }
60}
61
62#[cfg(test)]
63mod tests {
64 use super::*;
65 use crate::rpc::typed_data::Data;
66 use serde_json::json;
67
68 #[test]
69 fn it_constructs() {
70 let data = TypedData {
71 data: Some(Data::Json(r#"{ "foo": "bar" }"#.to_string())),
72 };
73
74 let mut metadata = HashMap::new();
75 metadata.insert(
76 "foo".to_string(),
77 TypedData {
78 data: Some(Data::String("bar".to_string())),
79 },
80 );
81
82 let binding = GenericTrigger::new(data, metadata);
83
84 assert_eq!(binding.data, Value::Json(json!({ "foo": "bar" })));
85 assert_eq!(binding.metadata.len(), 1);
86 assert_eq!(
87 binding.metadata.get("foo"),
88 Some(&Value::String("bar".to_string()))
89 );
90 }
91}