如何在json-rules-engine中查找失败的规则

时间:2019-03-13 09:18:18

标签: javascript node.js drools rule-engine node-rules

我是规则引擎的新手,我正在尝试使用JavaScript创建规则引擎。

我有以下规则,并且将一个参数作为错误的输入传递,如何查找不匹配的参数(事实)。

该事件引发的消息没有失败的规则,我想知道如何获取失败的参数。

请让我知道在这种情况下该怎么办。

npm  json-rules-engine

规则:

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
            }]
        }]
    },
    event: { // define the event to fire when the conditions evaluate truthy
        type: 'fouledOut',
        params: {
            message: 'Player has fouled out!'
        }
    }
})


**input:**

`let facts = {
    personalFoulCount: 6,
    gameDuration: 102
}`

**output:**

Player has fouled out!

**expected output:**

Player has fouled out due to a mismatch in gameDuration

2 个答案:

答案 0 :(得分:0)

I recently used this npm module: json-rules-engine
got into the same situation, and came out with solution

this may be exact solution or not, but serves the purpose

解决方案: 定义多个规则对象,然后传递给引擎并导出失败的规则。

Details:
1. From the above example, in the conditions.any array, there are 2 objects
2. create 2 Rule Objects with a ruleName as below
    const createRule = (conditions, ruleName) => ({
        conditions,
        event: {type: ruleName},
    });
3. create Engine object by passing the rules array
    const engine = new Engine(ruleList);
4. once facts ran against the rules with the engine, failed rules can be derived as below:
    i.e engine.run(facts).then(results => {
               // results.events will have passed rules
               // to get failed rules: maintain a list of rule names and filter the passed rules 
        });

答案 1 :(得分:0)

我们可以使用on方法来获取规则的failure/success事件。 下面的示例返回成功和失败规则的计数。

let facts = [{
        personalFoulCount: 6,
        gameDuration: 102
    },
    {
        personalFoulCount: 6,
        gameDuration: 40
    }]

engine.addRule({
    conditions: {
            all: [{
            fact: 'gameDuration',
            operator: 'equal',
            value: 40
        }]
    },
    event: { type: 'procedure_result'}
})

let result = {success_count : 0 , failed_count : 0}

engine.on('success', () => result.success_count++)
    .on('failure', () => result.failed_count++)

const getResults = function(){
    return new Promise((resolve, reject) => {
        facts.forEach(fact => {
            return engine.run(fact)
            .then(() => resolve())
        })
    })
}

getResults().then(() => console.log(result));

输出: { success_count: 1, failed_count: 1 }