-
Notifications
You must be signed in to change notification settings - Fork 491
/
Copy path06-custom-operators.mts
113 lines (102 loc) · 2.58 KB
/
06-custom-operators.mts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/*
* This example demonstrates using custom operators.
*
* A custom operator is created for detecting whether the word starts with a particular letter,
* and a 'word' fact is defined for providing the test string
*
* In this example, Facts are passed to run() as constants known at runtime. For a more
* complex example demonstrating asynchronously computed facts, see the fact-dependency example.
*
* Usage:
* node ./examples/06-custom-operators.js
*
* For detailed output:
* DEBUG=json-rules-engine node ./examples/06-custom-operators.js
*/
import "colors";
import { Engine } from "json-rules-engine";
async function start() {
/**
* Setup a new engine
*/
const engine = new Engine();
/**
* Define a 'startsWith' custom operator, for use in later rules
*/
engine.addOperator("startsWith", (factValue: string, jsonValue: string) => {
if (!factValue.length) return false;
return factValue[0].toLowerCase() === jsonValue.toLowerCase();
});
/**
* Add rule for detecting words that start with 'a'
*/
const ruleA = {
conditions: {
all: [
{
fact: "word",
operator: "startsWith",
value: "a",
},
],
},
event: {
type: "start-with-a",
},
};
engine.addRule(ruleA);
/*
* Add rule for detecting words that start with 'b'
*/
const ruleB = {
conditions: {
all: [
{
fact: "word",
operator: "startsWith",
value: "b",
},
],
},
event: {
type: "start-with-b",
},
};
engine.addRule(ruleB);
// utility for printing output
const printEventType: Record<string, string> = {
"start-with-a": 'start with "a"',
"start-with-b": 'start with "b"',
};
/**
* Register listeners with the engine for rule success and failure
*/
let facts: Record<string, unknown>;
engine
.on("success", (event) => {
console.log(facts.word + " DID ".green + printEventType[event.type]);
})
.on("failure", (event) => {
console.log(
facts.word + " did " + "NOT".red + " " + printEventType[event.type],
);
});
/**
* Each run() of the engine executes on an independent set of facts. We'll run twice, once per word
*/
// first run, using 'bacon'
facts = { word: "bacon" };
await engine.run(facts);
// second run, using 'antelope'
facts = { word: "antelope" };
await engine.run(facts);
}
export default start();
/*
* OUTPUT:
*
* bacon did NOT start with "a"
* bacon DID start with "b"
* antelope DID start with "a"
* antelope did NOT start with "b"
*/