Rules contain a set of conditions and a single event. When the engine is run, each rule condition is evaluated. If the results are truthy, the rule's event is triggered.
Returns a new rule instance
let rule = new Rule(options)Assigns the rule conditions to the provided argument. The root condition must be a boolean operator (all or any)
rule.setConditions({
all: [
{
fact: 'revenue',
operator: 'greaterThanInclusive'
value: 1000000
}
]
})
// if fact returns an object or array, providing a "path" key can be used for property traversal
rule.setConditions({
all: [
{
fact: 'userData', // 'userData' fact returns { profile: { addresses: [{ city: 'new york' }]}}
operator: 'equal'
value: 'new york',
path: '.profile.addresses[0].city' // "path" navigates the data structure, down to the "city" property
}
]
})See the fact dependency example
Sets the event the engine should emit when the rule conditions pass. All events must have a type property, which denotes the event name to emit when the rule passes.
Optionally, a params property may be provided as well. params will be passed to the event as an argument.
rule.setEvent({
type: 'string', //required
params: { object } //optional
})Sets the rule priority. Priority must be a positive, non-zero integer. The higher the priority, the sooner the rule will run. If no priority is assigned to a Rule, it will receive a default priority of 1.
rule.setPriority(100)Serializes the rule into a JSON string. Usually used when persisting rules.
let jsonString = rule.toJSON() // string: '{"conditions":{"all":[]},"priority":50 ...
let rule = new Rule(jsonString) // restored rule; same conditions, priority, event
// without stringifying
let jsonObject = rule.toJSON(false) // object: {conditions:{ all: [] }, priority: 50 ...Listen for 'success' and 'failure' events emitted when rule is evaluated.
// whenever rule is evaluated and the conditions pass, 'success' will trigger
rule.on('success', function(event, almanac) {
console.log(event) // { type: 'my-event', params: { id: 1 }
})Companion to 'success', except fires when the rule fails.
engine.on('failure', function(event, almanac) {
console.log(event) // { type: 'my-event', params: { id: 1 }
})Each rule condition must begin with a boolean operator(all or any) at its root.
The operator compares the value returned by the fact to what is stored in the value property. If the result is truthy, the condition passes.
equal - fact must equal value
notEqual - fact must not equal value
these operators use strict equality (===) and inequality (!==)
lessThan - fact must be less than value
lessThanInclusive- fact must be less than or equal to value
greaterThan - fact must be greater than value
greaterThanInclusive- fact must be greater than or equal to value
in - fact must be included in value (an array)
notIn - fact must not be included in value (an array)
contains - fact (an array) must include value
doesNotContain - fact (an array) must not include value