UNPKG

2.83 kBJavaScriptView Raw
1'use strict'
2
3/*
4 * This is an advanced example demonstrating rules that passed based off the
5 * results of other rules
6 *
7 * Usage:
8 * node ./examples/07-rule-chaining.js
9 *
10 * For detailed output:
11 * DEBUG=json-rules-engine node ./examples/07-rule-chaining.js
12 */
13
14require('colors')
15let Engine = require('../dist').Engine
16
17/**
18 * Setup a new engine
19 */
20let engine = new Engine()
21
22/**
23 * Rule for identifying people who may like screwdrivers
24 */
25let drinkRule = {
26 conditions: {
27 all: [{
28 fact: 'drinksOrangeJuice',
29 operator: 'equal',
30 value: true
31 }, {
32 fact: 'enjoysVodka',
33 operator: 'equal',
34 value: true
35 }]
36 },
37 event: { type: 'drinks-screwdrivers' },
38 priority: 10, // IMPORTANT! Set a higher priority for the drinkRule, so it runs first
39 onSuccess: function (event, almanac) {
40 almanac.addRuntimeFact('screwdriverAficionado', true)
41 },
42 onFailure: function (event, almanac) {
43 almanac.addRuntimeFact('screwdriverAficionado', false)
44 }
45}
46engine.addRule(drinkRule)
47
48/**
49 * Rule for identifying people who should be invited to a screwdriver social
50 * - Only invite people who enjoy screw drivers
51 * - Only invite people who are sociable
52 */
53let inviteRule = {
54 conditions: {
55 all: [{
56 fact: 'screwdriverAficionado', // this fact value is set when the drinkRule is evaluated
57 operator: 'equal',
58 value: true
59 }, {
60 fact: 'isSociable',
61 operator: 'equal',
62 value: true
63 }]
64 },
65 event: { type: 'invite-to-screwdriver-social' },
66 priority: 5 // Set a lower priority for the drinkRule, so it runs later (default: 1)
67}
68engine.addRule(inviteRule)
69
70/**
71 * Register listeners with the engine for rule success and failure
72 */
73let facts
74engine
75 .on('success', (event, almanac) => {
76 console.log(facts.accountId + ' DID '.green + 'meet conditions for the ' + event.type.underline + ' rule.')
77 })
78 .on('failure', event => {
79 console.log(facts.accountId + ' did ' + 'NOT'.red + ' meet conditions for the ' + event.type.underline + ' rule.')
80 })
81
82// define fact(s) known at runtime
83facts = { accountId: 'washington', drinksOrangeJuice: true, enjoysVodka: true, isSociable: true }
84engine
85 .run(facts) // first run, using washington's facts
86 .then(() => {
87 facts = { accountId: 'jefferson', drinksOrangeJuice: true, enjoysVodka: false, isSociable: true }
88 return engine.run(facts) // second run, using jefferson's facts; facts & evaluation are independent of the first run
89 })
90 .catch(console.log)
91
92/*
93 * OUTPUT:
94 *
95 * washington DID meet conditions for the drinks-screwdrivers rule.
96 * washington DID meet conditions for the invite-to-screwdriver-social rule.
97 * jefferson did NOT meet conditions for the drinks-screwdrivers rule.
98 * jefferson did NOT meet conditions for the invite-to-screwdriver-social rule.
99 */