MCPcopy
hub / github.com/CacheControl/json-rules-engine / start

Function start

examples/03-dynamic-facts.js:19–76  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

17const apiClient = require('./support/account-api-client')
18
19async function start () {
20 /**
21 * Setup a new engine
22 */
23 const engine = new Engine()
24
25 /**
26 * Rule for identifying microsoft employees taking pto on christmas
27 *
28 * the account-information fact returns:
29 * { company: 'XYZ', status: 'ABC', ptoDaysTaken: ['YYYY-MM-DD', 'YYYY-MM-DD'] }
30 */
31 const microsoftRule = {
32 conditions: {
33 all: [{
34 fact: 'account-information',
35 operator: 'equal',
36 value: 'microsoft',
37 path: '$.company' // access the 'company' property of "account-information"
38 }, {
39 fact: 'account-information',
40 operator: 'in',
41 value: ['active', 'paid-leave'], // 'status'' can be active or paid-leave
42 path: '$.status' // access the 'status' property of "account-information"
43 }, {
44 fact: 'account-information',
45 operator: 'contains',
46 value: '2016-12-25',
47 path: '$.ptoDaysTaken' // access the 'ptoDaysTaken' property of "account-information"
48 }]
49 },
50 event: {
51 type: 'microsoft-christmas-pto',
52 params: {
53 message: 'current microsoft employee taking christmas day off'
54 }
55 }
56 }
57 engine.addRule(microsoftRule)
58
59 /**
60 * 'account-information' fact executes an api call and retrieves account data, feeding the results
61 * into the engine. The major advantage of this technique is that although there are THREE conditions
62 * requiring this data, only ONE api call is made. This results in much more efficient runtime performance.
63 */
64 engine.addFact('account-information', function (params, almanac) {
65 return almanac.factValue('accountId')
66 .then(accountId => {
67 return apiClient.getAccountInformation(accountId)
68 })
69 })
70
71 // define fact(s) known at runtime
72 const facts = { accountId: 'lincoln' }
73 const { events } = await engine.run(facts)
74
75 console.log(facts.accountId + ' is a ' + events.map(event => event.params.message))
76}

Callers 1

Calls 4

addRuleMethod · 0.95
addFactMethod · 0.95
runMethod · 0.95
factValueMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…