UNPKG

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