var RuleEngine = require("node-rules");
var RuleConverter = require("query-builder-to-string");
var ruleInput = {
"condition": "AND",
"rules": [{
"id": "price",
"field": "price",
"type": "double",
"input": "number",
"operator": "less",
"value": 10.25
},
{
"condition": "OR",
"rules": [{
"id": "category",
"field": "category",
"type": "integer",
"input": "select",
"operator": "equal",
"value": 2
},
{
"id": "category",
"field": "category",
"type": "integer",
"input": "select",
"operator": "equal",
"value": 1
},
{
"condition": "AND",
"rules": [{
"id": "in_stock",
"field": "in_stock",
"type": "integer",
"input": "radio",
"operator": "equal",
"value": 1
}]
}
]
}
],
"valid": true
};
var output = RuleConverter(ruleInput);
/* Creating Rule Engine instance */
var R = new RuleEngine();
/* Add a rule */
var rule = {
"condition": function (R) {
R.when(eval(output));
},
"consequence": function (R) {
this.result = false;
this.reason = "The transaction was blocked as it was less than 10";
R.stop();
}
};
/* Register Rule */
R.register(rule);
/* Add a Fact with less than 10 as transaction, and this should be blocked */
var fact = {
"price": "5",
"category": 2
};
/* Check if the engine blocks it! */
R.execute(fact, function (data) {
if (data.result) {
console.log("Valid transaction");
} else {
console.log("Blocked Reason:" + data.reason);
}
});