UNPKG

7.7 kBMarkdownView Raw
1![json-rules-engine](http://i.imgur.com/MAzq7l2.png)
2[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)
3[![Build Status](https://github.com/cachecontrol/json-rules-engine/workflows/Node.js%20CI/badge.svg?branch=master)](https://github.com/cachecontrol/json-rules-engine/workflows/Node.js%20CI/badge.svg?branch=master)
4
5[![npm version](https://badge.fury.io/js/json-rules-engine.svg)](https://badge.fury.io/js/json-rules-engine)
6[![install size](https://packagephobia.now.sh/badge?p=json-rules-engine)](https://packagephobia.now.sh/result?p=json-rules-engine)
7[![npm downloads](https://img.shields.io/npm/dm/json-rules-engine.svg)](https://www.npmjs.com/package/json-rules-engine)
8
9A rules engine expressed in JSON
10
11## Synopsis
12
13```json-rules-engine``` is a powerful, lightweight rules engine. Rules are composed of simple json structures, making them human readable and easy to persist.
14
15## Features
16
17* Rules expressed in simple, easy to read JSON
18* Full support for ```ALL``` and ```ANY``` boolean operators, including recursive nesting
19* Fast by default, faster with configuration; priority levels and cache settings for fine tuning performance
20* Secure; no use of eval()
21* Isomorphic; runs in node and browser
22* Lightweight & extendable; 12kb gzipped w/few dependencies
23
24## Installation
25
26```bash
27$ npm install json-rules-engine
28```
29
30## Basic Example
31
32This 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).
33
34```js
35const { Engine } = require('json-rules-engine')
36
37
38/**
39 * Setup a new engine
40 */
41let engine = new Engine()
42
43// define a rule for detecting the player has exceeded foul limits. Foul out any player who:
44// (has committed 5 fouls AND game is 40 minutes) OR (has committed 6 fouls AND game is 48 minutes)
45engine.addRule({
46 conditions: {
47 any: [{
48 all: [{
49 fact: 'gameDuration',
50 operator: 'equal',
51 value: 40
52 }, {
53 fact: 'personalFoulCount',
54 operator: 'greaterThanInclusive',
55 value: 5
56 }]
57 }, {
58 all: [{
59 fact: 'gameDuration',
60 operator: 'equal',
61 value: 48
62 }, {
63 fact: 'personalFoulCount',
64 operator: 'greaterThanInclusive',
65 value: 6
66 }]
67 }]
68 },
69 event: { // define the event to fire when the conditions evaluate truthy
70 type: 'fouledOut',
71 params: {
72 message: 'Player has fouled out!'
73 }
74 }
75})
76
77/**
78 * Define facts the engine will use to evaluate the conditions above.
79 * Facts may also be loaded asynchronously at runtime; see the advanced example below
80 */
81let facts = {
82 personalFoulCount: 6,
83 gameDuration: 40
84}
85
86// Run the engine to evaluate
87engine
88 .run(facts)
89 .then(results => {
90 // 'results' is an object containing successful events, and an Almanac instance containing facts
91 results.events.map(event => console.log(event.params.message))
92 })
93
94/*
95 * Output:
96 *
97 * Player has fouled out!
98 */
99```
100
101This is available in the [examples](./examples/02-nested-boolean-logic.js)
102
103## Advanced Example
104
105This example demonstates an engine for identifying employees who work for Microsoft and are taking Christmas day off.
106
107This demonstrates an engine which uses asynchronous fact data.
108Fact information is loaded via API call during runtime, and the results are cached and recycled for all 3 conditions.
109It also demonstates use of the condition _path_ feature to reference properties of objects returned by facts.
110
111```js
112const { Engine } = require('json-rules-engine')
113
114// example client for making asynchronous requests to an api, database, etc
115import apiClient from './account-api-client'
116
117/**
118 * Setup a new engine
119 */
120let engine = new Engine()
121
122/**
123 * Rule for identifying microsoft employees taking pto on christmas
124 *
125 * the account-information fact returns:
126 * { company: 'XYZ', status: 'ABC', ptoDaysTaken: ['YYYY-MM-DD', 'YYYY-MM-DD'] }
127 */
128let microsoftRule = {
129 conditions: {
130 all: [{
131 fact: 'account-information',
132 operator: 'equal',
133 value: 'microsoft',
134 path: '.company' // access the 'company' property of "account-information"
135 }, {
136 fact: 'account-information',
137 operator: 'in',
138 value: ['active', 'paid-leave'], // 'status' can be active or paid-leave
139 path: '.status' // access the 'status' property of "account-information"
140 }, {
141 fact: 'account-information',
142 operator: 'contains', // the 'ptoDaysTaken' property (an array) must contain '2016-12-25'
143 value: '2016-12-25',
144 path: '.ptoDaysTaken' // access the 'ptoDaysTaken' property of "account-information"
145 }]
146 },
147 event: {
148 type: 'microsoft-christmas-pto',
149 params: {
150 message: 'current microsoft employee taking christmas day off'
151 }
152 }
153}
154engine.addRule(microsoftRule)
155
156/**
157 * 'account-information' fact executes an api call and retrieves account data, feeding the results
158 * into the engine. The major advantage of this technique is that although there are THREE conditions
159 * requiring this data, only ONE api call is made. This results in much more efficient runtime performance
160 * and fewer network requests.
161 */
162engine.addFact('account-information', function (params, almanac) {
163 console.log('loading account information...')
164 return almanac.factValue('accountId')
165 .then((accountId) => {
166 return apiClient.getAccountInformation(accountId)
167 })
168})
169
170// define fact(s) known at runtime
171let facts = { accountId: 'lincoln' }
172engine
173 .run(facts)
174 .then((results) => {
175 console.log(facts.accountId + ' is a ' + results.events.map(event => event.params.message))
176 })
177 .catch(err => console.log(err.stack))
178
179/*
180 * OUTPUT:
181 *
182 * loading account information... // <-- API call is made ONCE and results recycled for all 3 conditions
183 * lincoln is a current microsoft employee taking christmas day off
184 */
185```
186
187This is available in the [examples](./examples/03-dynamic-facts.js)
188
189## Docs
190
191The examples above provide a simple demonstrations of what `json-rules-engine` can do. To learn more about the advanced features and techniques,
192see the [docs](./docs) and read through the [examples](./examples). There is also a [walkthrough](./docs/walkthrough.md) available.
193
194## Persisting Rules
195
196Rules 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.
197
198```js
199// save somewhere...
200let jsonString = rule.toJSON()
201
202// ...later:
203let rule = new Rule(jsonString)
204```
205
206_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](https://github.com/mithunsatheesh/node-rules) project supports this (though be aware the capability is enabled via ``eval()``.
207
208## Debugging
209
210To see what the engine is doing under the hood, debug output can be turned on via:
211
212#### Node
213
214```bash
215DEBUG=json-rules-engine
216```
217
218#### Browser
219```js
220// set debug flag in local storage & refresh page to see console output
221localStorage.debug = 'json-rules-engine'
222```
223
224## License
225[ISC](./LICENSE)