18 个版本 (8 个重大更改)
0.9.4 | 2021 年 8 月 7 日 |
---|---|
0.9.3 | 2021 年 2 月 11 日 |
0.9.1 | 2020 年 12 月 17 日 |
0.7.3 | 2020 年 11 月 16 日 |
#1691 in 网页编程
每月下载量:40
62KB
1.5K SLoC
json-rules-engine
安装
将此包添加到您的项目 Cargo.toml
文件中。(检查 https://crates.io/crates/json-rules-engine 以获取正确版本)
[dependencies]
json-rules-engine = { version = "0.9", features = ["email", "eval"] }
tokio = { version = "0.3.3", features = ["macros"] }
serde_json = { version = "*" }
anyhow = { version = "*" }
功能
- 内置运算符
- 全面支持
ALL
,OR
,Not
,AtLeast
布尔运算符,包括递归嵌套 - 类型安全
- 从 json 加载规则
- 内置 Moustache 渲染
- 安全脚本
- 自定义函数
- 自定义事件
- 合并组
- 现有事件
- 将 HTTP POST 发送到回调 URL
- 基于
SendGrid
的电子邮件通知
入门
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 fn 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]
},
{
"and": [
{
"expr": "facts.age > 20 && facts.age <= 25",
},
{
"expr": "my_function(facts)",
},
]
},
{
"field": "action",
"operator": "string_equals",
"value": "coding in rust"
}
]
},
"events": [
{
"type": "post_to_callback_url",
"params": {
"callback_url": "http://example.com/peoples/conding_in_rust",
"type": "info",
"title": "Another person is coding in rust",
"message": "Name: {{ name }}, Age: {{ age }}, Action: {{ action }}"
}
},
{
"type": "email_notification",
"params": {
"from": "[email protected]",
"to": ["[email protected]"],
"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();
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);
}
特别感谢
依赖关系
~2–15MB
~199K SLoC