-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathengine.js
More file actions
82 lines (70 loc) · 2.17 KB
/
engine.js
File metadata and controls
82 lines (70 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
* Created by aditya on 15/09/17.
*/
const Engine = require('node-rules');
const _ = require('lodash');
function RuleRegistry(){
this.registry = [];
}
RuleRegistry.prototype.add = function(condition, consequence, options){
if(!options) options = {};
const rule = {'condition': function(R){
if(condition.length > 0){
condition.call(this, function(err, outcome){
if(err)
R.when(false);
else
R.when(outcome);
});
}else{
R.when(condition.call(this));
}
}, 'consequence': function(R){
consequence.call(this);
switch(options.handle){
case 'next':
R.next();
break;
case 'restart':
R.restart();
break;
case 'stop':
R.stop();
break;
default:
break;
}
}};
_.assign(rule, options);
this.registry.push(rule);
};
RuleRegistry.prototype.build = function(){
return this.registry;
};
RuleRegistry.prototype.length = function(){
return this.registry.length;
};
function RuleEngine(){
this.registry = new RuleRegistry();
this.engine = new Engine([], {ignoreFactChanges: true});
}
RuleEngine.prototype.add = function(condition, consequence, options){
this.registry.add(condition, consequence, options);
};
RuleEngine.prototype.enqueue = function(rules){
_.forEach(rules, function(rule, index){
const options = {'priority': 100 - this.registry.length(), 'handle': rules.length - 1 === index ? 'stop' : 'next'};
this.registry.add(rule.condition, rule.consequence, options);
}.bind(this));
};
RuleEngine.prototype.waterfall = function(rules){
_.forEach(rules, function(rule){
const options = {'priority': 100 - this.registry.length(), 'handle': 'stop'};
this.registry.add(rule.condition, rule.consequence, options);
}.bind(this));
};
RuleEngine.prototype.validate = function(fact, callback){
this.engine.register(this.registry.build());
this.engine.execute(fact, callback);
};
module.exports = RuleEngine;