forked from claytongulick/json-patch-rules
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
113 lines (91 loc) · 2.76 KB
/
index.js
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
const jsonPredicate = require('json-predicate');
const test = jsonPredicate.test;
class JSONPatchRules {
constructor(rules, options) {
this.options = Object.assign({
mode: 'whitelist'
},options);
this.rules = rules;
}
check(json_patch) {
if(!Array.isArray(json_patch))
throw new Error("json_patch parameter must be an array");
return json_patch.every((item) => this.checkOperation(item));
}
checkOperation(item) {
let rules = this.findRules(item);
if(this.options.mode == "blacklist") {
if(!rules)
return true;
if(rules.length == 0)
return true;
if(rules.length > 0)
return false;
}
if(this.options.mode == "whitelist") {
if(!rules)
return false;
if(rules.length == 0)
return false;
if(rules.length > 0)
return true;
}
}
findRules(item) {
return this.rules.filter(
(rule) => {
return this.ruleMatches(item, rule);
}
);
}
ruleMatches(item, rule) {
if(rule.path) {
let path = rule.path;
//if this is a regex
if(path.indexOf('^/') == 0) {
let regex = new RegExp(path);
let match = regex.test(item.path);
if(!match)
return false;
}
else if(path != item.path) {
return false;
}
}
if(rule.op) {
if(Array.isArray(rule.op)) {
let op_match = rule.op.includes(item.op)
if(!op_match)
return false;
}
else {
if(!rule.op === item.op)
return false;
}
}
if(rule.value) {
if (typeof rule.value == 'string') {
let regex = new RegExp(rule.value);
let test_match = regex.test(item.value);
if (!test_match)
return false;
}
else {
let test_match = (rule.value === item.value);
if(!test_match)
return false;
}
}
if(rule.test) {
let valid = jsonPredicate.validatePredicate(rule.test);
if(!valid)
throw new Error("Invalid JSON Predicate");
//if this is an array, it's a json predicate set
let test_match = test(item, rule.test);
if(!test_match)
return false;
}
return true;
}
}
module.exports = JSONPatchRules;