json-rules-engine 简单试用

以下是对于json-rules-engine 的一个简单试用

rule 简单说明

json-rules-engine rule 基于json 进行描述配置,支持一些内置的operator,当然也可以自定义,rule 支持常见的any,and操作,同时支持嵌套,每个rule 可以包含自己的回调(成功以及失败),对于facts 的数据处理支持基于json path 的提起,同时可以进行动态facts 数据的处理(almanac 以及facts),同时rule 可以方便的转换为json 存储在db 或者其他存储中,方便业务修改试用

代码

  • app.js
const { Engine } = require('json-rules-engine')

/**
 * Setup a new engine
 */
let engine = new Engine()

// define a rule for detecting the player has exceeded foul limits.  Foul out any player who:
// (has committed 5 fouls AND game is 40 minutes) OR (has committed 6 fouls AND game is 48 minutes)
engine.addRule({
  conditions: {
    any: [{
      all: [{
        fact: 'gameDuration',
        operator: 'equal',
        value: 40
      }, {
        fact: 'personalFoulCount',
        operator: 'greaterThanInclusive',
        value: 5
      }]
    }, {
      all: [{
        fact: 'gameDuration',
        operator: 'equal',
        value: 48
      }, {
        fact: 'personalFoulCount',
        operator: 'greaterThanInclusive',
        value: 6
      }]
    }]
  },
  name:"dalongdemo",
  event: {  // define the event to fire when the conditions evaluate truthy
    type: 'fouledOut',
    params: {
      message: 'Player has fouled out!'
    }
  }
})

/**
 * Define facts the engine will use to evaluate the conditions above.
 * Facts may also be loaded asynchronously at runtime; see the advanced example below
 */
let facts = {
  personalFoulCount: 6,
  gameDuration: 40
}

// Run the engine to evaluate
engine
  .run(facts)
  .then(({ events, almanac, results}) => {
    console.log(events,almanac,results)
    events.map(event => console.log(event.params.message))
  })

/*
 * Output:
 *
 * Player has fouled out!
 */
  • 效果

说明

以上只是一个简单试用,以及关于rule 的介绍,后边会介绍下其他几个关键class的使用

参考资料

https://github.com/CacheControl/json-rules-engine

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

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

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

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

导航