UNPKG

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