json-rules-engine
項目地址
安裝
[dependencies]
json-rules-engine = { version = "0.7.0", features = ["email"] }
tokio = { version = "0.3.3", features = ["macros"] }
serde_json = { version = "*" }
anyhow = { version = "*" }
特性
-
不少的類型安全的內置操做符如, string_equals
,int_in_range
...等 -
支持All, Any, AtLeast操做符 -
支持匹配成功後的多個對應事件如HTTP post到callback_url,發送郵件,適合報警 -
json序列化反序列化 -
內置moustache支持 -
自定義腳本 -
自定義函數
實例
use json_rules_engine::{Engine, Rule, Map, from_dynamic};
use serde_json::json;
use serde::{Serialize, Deserialize};
#[derive(Deserialize, Serialize)]
struct Facts {
name: String,
age: u8,
action: String
}
fn age_greater_than20_less_than_inclusive25(p: Map) -> bool {
let facts: Facts = from_dynamic(&p.into()).unwrap();
facts.age > 20 && facts.age <= 25
}
#[tokio::main]
async main() -> anyhow::Result<()> {
let sendgrid_api_key = "kjsldkjslkjlwkjkjew";
let rule_json = json!({
"conditions": {
"and": [
{
"field": "name",
"operator": "string_equals",
"value": "Cheng JIANG"
},
{
"field": "age",
"operator": "int_in_range",
"value": [20, 25]
},
{
"script": "facts.age > 20 && facts.age <= 25",
},
{
"script": "my_function(facts)",
},
{
"field": "action",
"operator": "string_equals",
"value": "coding in rust"
}
]
},
"events": [
{
"type": "post_to_callback_url",
"params": {
"callback_url": "http://example.com/people/conding_in_rust",
"type": "info",
"title": "Another person is coding in rust",
"message": "Name: {{ name }}, Age: {{ age }}, Action: {{ action }},"
}
},
{
"type": "email_notification",
"params": {
"from": "alex_cj96@foxmail.com",
"to": ["abc.def@gmail.com"],
"type": "info",
"title": "Another person is coding in rust",
"message": "Name: {{ name }}, Age: {{ age }}, Action: {{ action }},"
}
}
]
});
let rule: Rule = serde_json::from_str::<Rule>(&serde_json::to_string(&rule_json).unwrap()).unwrap();
let mut engine = Engine::new(sendgrid_api_key);
engine.add_rule(rule);
engine.add_function("my_function", age_greater_than20_less_than_inclusive25);
let facts = json!({
"name": "Cheng JIANG",
"age": 24,
"action": "coding in rust",
});
let rule_results = engine.run(&facts).await?;
println!("{:?}", rule_results);
}
本文分享自微信公衆號 - Rust語言中文社區(rust-china)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。node