json-rules-engine engine 简单说明

engine包含了存储,执行规则,提交事件以及维护状态,比如添加以及一处fact,添加、删除、更新rule,同时还包含添加operator,添加以及维护conddition

执行

// run the engine
await engine.run()

// with constant facts
await engine.run({ userId: 1 })

const {
  results,         // rule results for successful rules
  failureResults,  // rule results for failed rules
  events,          // array of successful rule events
  failureEvents,   // array of failed rule events
  almanac          // Almanac instance representing the run
} = await engine.run({ userId: 1 })

添加rule

let Rule = require('json-rules-engine').Rule

// via rule properties:
engine.addRule({
  conditions: {},
  event: {},
  priority: 1,                             // optional, default: 1
  onSuccess: function (event, almanac) {}, // optional
  onFailure: function (event, almanac) {}, // optional
})

// or rule instance:
let rule = new Rule()
engine.addRule(rule)

添加operator

engine.addOperator('startsWithLetter', (factValue, jsonValue) => {
  if (!factValue.length) return false
  return factValue[0].toLowerCase() === jsonValue.toLowerCase()
})

// and to use the operator...
let rule = new Rule(
  conditions: {
    all: [
      {
        fact: 'username',
        operator: 'startsWithLetter', // reference the operator name in the rule
        value: 'a'
      }
    ]
  }
)

添加condition

engine.setCondition('validLogin', {
  all: [
    {
      operator: 'notEqual',
      fact: 'loginToken',
      value: null
    },
    {
      operator: 'greaterThan',
      fact: 'loginToken',
      path: '$.expirationTime',
      value: { fact: 'now' }
    }
  ]
});

engine.addRule({
  condtions: {
    all: [
      {
        condition: 'validLogin'
      },
      {
        operator: 'contains',
        fact: 'loginToken',
        path: '$.role',
        value: 'admin'
      }
    ]
  },
  event: {
    type: 'AdminAccessAllowed'
  }
})

回调事件

// 注意每次成功执行都会触发
engine.on("success",function(event,almanac,results){
  console.log("success",event,almanac,results)
})

engine.on("failure",function(event,almanac,results){
  console.log("failure",event,almanac,results)
})

说明

以上是一个简单说明,实际上engine 还支持不少参数allowUndefinedFacts、allowUndefinedConditions、replaceFactsInEventParams、pathResolver 同时对于run 的时候还可以自定义almanac

参考资料

https://github.com/CacheControl/json-rules-engine/blob/master/docs/engine.md

https://github.com/CacheControl/json-rules-engine/blob/master/docs/almanac.md

https://github.com/CacheControl/json-rules-engine/blob/master/docs/rules.md#condition-helpers-custom-path-resolver

posted on 2024-11-30 08:00  荣锋亮  阅读(20)  评论(0编辑  收藏  举报

导航