UNPKG

7.56 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(events => { // run() returns events with truthy conditions
89 events.map(event => console.log(event.params.message))
90 })
91
92/*
93 * Output:
94 *
95 * Player has fouled out!
96 */
97```
98
99This is available in the [examples](./examples/02-nested-boolean-logic.js)
100
101## Advanced Example
102
103This example demonstates an engine for identifying employees who work for Microsoft and are taking Christmas day off.
104
105This demonstrates an engine which uses asynchronous fact data.
106Fact information is loaded via API call during runtime, and the results are cached and recycled for all 3 conditions.
107It also demonstates use of the condition _path_ feature to reference properties of objects returned by facts.
108
109```js
110import { Engine } from 'json-rules-engine'
111
112// example client for making asynchronous requests to an api, database, etc
113import apiClient from './account-api-client'
114
115/**
116 * Setup a new engine
117 */
118let engine = new Engine()
119
120/**
121 * Rule for identifying microsoft employees taking pto on christmas
122 *
123 * the account-information fact returns:
124 * { company: 'XYZ', status: 'ABC', ptoDaysTaken: ['YYYY-MM-DD', 'YYYY-MM-DD'] }
125 */
126let microsoftRule = {
127 conditions: {
128 all: [{
129 fact: 'account-information',
130 operator: 'equal',
131 value: 'microsoft',
132 path: '.company' // access the 'company' property of "account-information"
133 }, {
134 fact: 'account-information',
135 operator: 'in',
136 value: ['active', 'paid-leave'], // 'status' can be active or paid-leave
137 path: '.status' // access the 'status' property of "account-information"
138 }, {
139 fact: 'account-information',
140 operator: 'contains', // the 'ptoDaysTaken' property (an array) must contain '2016-12-25'
141 value: '2016-12-25',
142 path: '.ptoDaysTaken' // access the 'ptoDaysTaken' property of "account-information"
143 }]
144 },
145 event: {
146 type: 'microsoft-christmas-pto',
147 params: {
148 message: 'current microsoft employee taking christmas day off'
149 }
150 }
151}
152engine.addRule(microsoftRule)
153
154/**
155 * 'account-information' fact executes an api call and retrieves account data, feeding the results
156 * into the engine. The major advantage of this technique is that although there are THREE conditions
157 * requiring this data, only ONE api call is made. This results in much more efficient runtime performance
158 * and fewer network requests.
159 */
160engine.addFact('account-information', function (params, almanac) {
161 console.log('loading account information...')
162 return almanac.factValue('accountId')
163 .then((accountId) => {
164 return apiClient.getAccountInformation(accountId)
165 })
166})
167
168// define fact(s) known at runtime
169let facts = { accountId: 'lincoln' }
170engine
171 .run(facts)
172 .then(function (events) {
173 console.log(facts.accountId + ' is a ' + events.map(event => event.params.message))
174 })
175 .catch(err => console.log(err.stack))
176
177/*
178 * OUTPUT:
179 *
180 * loading account information... // <-- API call is made ONCE and results recycled for all 3 conditions
181 * lincoln is a current microsoft employee taking christmas day off
182 */
183```
184
185This is available in the [examples](./examples/03-dynamic-facts.js)
186
187## Docs
188
189The examples above provide a simple demonstrations of what `json-rules-engine` can do. To learn more about the advanced features and techniques,
190see the [docs](./docs) and read through the [examples](./examples). There is also a [walkthrough](./docs/walkthrough.md) available.
191
192## Persisting Rules
193
194Rules 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.
195
196```js
197// save somewhere...
198let jsonString = rule.toJSON()
199
200// ...later:
201let rule = new Rule(jsonString)
202```
203
204_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()``.
205
206## Debugging
207
208To see what the engine is doing under the hood, debug output can be turned on via:
209
210#### Node
211
212```bash
213DEBUG=json-rules-engine
214```
215
216#### Browser
217```js
218// set debug flag in local storage & refresh page to see console output
219localStorage.debug = 'json-rules-engine'
220```
221
222## License
223[ISC](./LICENSE)