Security News
Oracle Drags Its Feet in the JavaScript Trademark Dispute
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
json-rules-engine
Advanced tools
The json-rules-engine npm package is a powerful tool for creating and executing business rules in JavaScript. It allows you to define rules in JSON format and evaluate them against a set of facts. This can be useful for a variety of applications, including decision-making systems, workflow automation, and more.
Defining Rules
You can define rules using JSON format. Each rule consists of conditions and an event. The conditions specify the criteria that need to be met, and the event specifies what happens when the conditions are met.
{"rules":[{"conditions":{"all":[{"fact":"temperature","operator":"greaterThanInclusive","value":100}]},"event":{"type":"highTemperature","params":{"message":"Temperature is too high!"}}}]}
Evaluating Rules
You can evaluate rules against a set of facts. If the facts meet the conditions specified in the rules, the corresponding event will be triggered.
{"facts":{"temperature":101},"engine":{"addRule":"rule","run":"facts"}}
Combining Multiple Conditions
You can combine multiple conditions using logical operators like 'all' and 'any'. This allows you to create complex rules that evaluate multiple criteria.
{"rules":[{"conditions":{"all":[{"fact":"temperature","operator":"greaterThanInclusive","value":100},{"fact":"humidity","operator":"lessThan","value":30}]},"event":{"type":"alert","params":{"message":"High temperature and low humidity!"}}}]}
nools is a rules engine for JavaScript that uses a domain-specific language (DSL) for defining rules. It is more powerful and flexible than json-rules-engine but has a steeper learning curve. It is suitable for complex rule-based systems.
A rules engine expressed in JSON
json-rules-engine
is a powerful, lightweight rules engine. Rules are composed of simple json structures, making them human readable and easy to persist.
ALL
and ANY
boolean operators, including recursive nesting$ npm install json-rules-engine
This example demonstrates an engine for detecting whether a basketball player has fouled out (a player who commits five personal fouls over the course of a 40-minute game, or six in a 48-minute game, fouls out).
import { Engine } from '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
}]
}]
},
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(results => {
// 'results' is an object containing successful events, and an Almanac instance containing facts
results.events.map(event => console.log(event.params.message))
})
/*
* Output:
*
* Player has fouled out!
*/
This is available in the examples
This example demonstates an engine for identifying employees who work for Microsoft and are taking Christmas day off.
This demonstrates an engine which uses asynchronous fact data. Fact information is loaded via API call during runtime, and the results are cached and recycled for all 3 conditions. It also demonstates use of the condition path feature to reference properties of objects returned by facts.
import { Engine } from 'json-rules-engine'
// example client for making asynchronous requests to an api, database, etc
import apiClient from './account-api-client'
/**
* Setup a new engine
*/
let engine = new Engine()
/**
* Rule for identifying microsoft employees taking pto on christmas
*
* the account-information fact returns:
* { company: 'XYZ', status: 'ABC', ptoDaysTaken: ['YYYY-MM-DD', 'YYYY-MM-DD'] }
*/
let microsoftRule = {
conditions: {
all: [{
fact: 'account-information',
operator: 'equal',
value: 'microsoft',
path: '.company' // access the 'company' property of "account-information"
}, {
fact: 'account-information',
operator: 'in',
value: ['active', 'paid-leave'], // 'status' can be active or paid-leave
path: '.status' // access the 'status' property of "account-information"
}, {
fact: 'account-information',
operator: 'contains', // the 'ptoDaysTaken' property (an array) must contain '2016-12-25'
value: '2016-12-25',
path: '.ptoDaysTaken' // access the 'ptoDaysTaken' property of "account-information"
}]
},
event: {
type: 'microsoft-christmas-pto',
params: {
message: 'current microsoft employee taking christmas day off'
}
}
}
engine.addRule(microsoftRule)
/**
* 'account-information' fact executes an api call and retrieves account data, feeding the results
* into the engine. The major advantage of this technique is that although there are THREE conditions
* requiring this data, only ONE api call is made. This results in much more efficient runtime performance
* and fewer network requests.
*/
engine.addFact('account-information', function (params, almanac) {
console.log('loading account information...')
return almanac.factValue('accountId')
.then((accountId) => {
return apiClient.getAccountInformation(accountId)
})
})
// define fact(s) known at runtime
let facts = { accountId: 'lincoln' }
engine
.run(facts)
.then((results) => {
console.log(facts.accountId + ' is a ' + results.events.map(event => event.params.message))
})
.catch(err => console.log(err.stack))
/*
* OUTPUT:
*
* loading account information... // <-- API call is made ONCE and results recycled for all 3 conditions
* lincoln is a current microsoft employee taking christmas day off
*/
This is available in the examples
The examples above provide a simple demonstrations of what json-rules-engine
can do. To learn more about the advanced features and techniques,
see the docs and read through the examples. There is also a walkthrough available.
Rules may be easily converted to JSON and persisted to a database, file system, or elsewhere. To convert a rule to JSON, simply call the rule.toJSON()
method. Later, a rule may be restored by feeding the json into the Rule constructor.
// save somewhere...
let jsonString = rule.toJSON()
// ...later:
let rule = new Rule(jsonString)
Why aren't "fact" methods persistable? This is by design, for several reasons. Firstly, facts are by definition business logic bespoke to your application, and therefore lie outside the scope of this library. Secondly, many times this request indicates a design smell; try thinking of other ways to compose the rules and facts to accomplish the same objective. Finally, persisting fact methods would involve serializing javascript code, and restoring it later via eval()
. If you have a strong desire for this feature, the node-rules project supports this (though be aware the capability is enabled via eval()
.
To see what the engine is doing under the hood, debug output can be turned on via:
DEBUG=json-rules-engine
// set debug flag in local storage & refresh page to see console output
localStorage.debug = 'json-rules-engine'
5.0.4 / 2020-09-26
FAQs
Rules Engine expressed in simple json
The npm package json-rules-engine receives a total of 0 weekly downloads. As such, json-rules-engine popularity was classified as not popular.
We found that json-rules-engine demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
Security News
The Linux Foundation is warning open source developers that compliance with global sanctions is mandatory, highlighting legal risks and restrictions on contributions.
Security News
Maven Central now validates Sigstore signatures, making it easier for developers to verify the provenance of Java packages.