-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwhere-filter.ts
302 lines (258 loc) · 7.46 KB
/
where-filter.ts
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
// TODO: lots of "as any" and ": any" in this code for a quick and dirty conversion
// to typescript; should be cleaned up to use real types
// Where-like filter to support syntax expressions like:
// {a: 1}
// {and: [{a: 1}, {b: "2"}]}
// {or: [{a: 1}, {b: "2"}]}
function getValue(obj: any, path: string) {
/* eslint-disable-next-line eqeqeq */
if (obj == null) {
return undefined;
}
if (path.indexOf('.') < 0) return obj[path];
const keys = path.split('.');
let val = obj;
for (let i = 0, n = keys.length; i < n; i++) {
val = val[keys[i] as any];
/* eslint-disable-next-line eqeqeq */
if (val == null) {
return val;
}
}
return val;
}
/**
* Compare two values
* @param {*} val1 The 1st value
* @param {*} val2 The 2nd value
* @return {number} 0: =, positive: >, negative <
* @private
*/
function compare(val1: any, val2: any) {
/* eslint-disable-next-line eqeqeq */
if (val1 == null || val2 == null) {
// Either val1 or val2 is null or undefined
/* eslint-disable-next-line eqeqeq */
return val1 == val2 ? 0 : NaN;
}
if (typeof val1 === 'number') {
return val1 - val2;
}
if (typeof val1 === 'string') {
if (val1 > val2) {
return 1;
} else {
if (val1 < val2) {
return -1;
} else {
/* eslint-disable-next-line eqeqeq */
if (val1 == val2) {
return 0;
}
}
}
return NaN;
}
if (typeof val1 === 'boolean') {
return (val1 as any) - val2;
}
if (val1 instanceof Date) {
const result = (val1 as any) - val2;
return result;
}
// Return NaN if we don't know how to compare
/* eslint-disable-next-line eqeqeq */
return val1 == val2 ? 0 : NaN;
}
function testInEquality(example: any, val: any) {
if ('gt' in example) {
return compare(val, example.gt) > 0;
}
if ('gte' in example) {
return compare(val, example.gte) >= 0;
}
if ('lt' in example) {
return compare(val, example.lt) < 0;
}
if ('lte' in example) {
return compare(val, example.lte) <= 0;
}
return false;
}
function toRegExp(pattern: RegExp | string) {
if (pattern instanceof RegExp) {
return pattern;
}
let regex = '';
// Escaping user input to be treated as a literal string within a regular expression
// https://developer.mozilla.org/en-US/docs/Web/
// JavaScript/Guide/Regular_Expressions#Writing_a_Regular_Expression_Pattern
// pattern = pattern.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1');
for (let i = 0, n = pattern.length; i < n; i++) {
const char = pattern.charAt(i);
if (char === '\\') {
i++; // Skip to next char
// match backslash-escaped chars verbatim, escape them in the regex too
// but a trailing backslash only matches itself
regex += i < n ? '\\' + pattern.charAt(i) : '\\\\';
} else if (char === '%') {
// sql substring wildcard
regex += '.*';
} else if (char === '_') {
// sql single-char wildcard
regex += '.';
} else {
// all other chars, including metachars, included in the regex as-is
regex += char;
}
}
return regex;
}
function test(example: any, value: any) {
if (typeof value === 'string' && example instanceof RegExp) {
return value.match(example);
}
if (example === undefined) {
return undefined;
}
if (typeof example === 'object' && example !== null) {
if (example.regexp) {
return value ? value.match(example.regexp) : false;
}
if (example.inq) {
for (let i = 0; i < example.inq.length; i++) {
/* eslint-disable-next-line eqeqeq */
if (example.inq[i] == value) {
return true;
}
}
return false;
}
if (example.nin) {
for (let i = 0; i < example.nin.length; i++) {
/* eslint-disable-next-line eqeqeq */
if (example.nin[i] == value) {
return false;
}
}
return true;
}
if ('neq' in example) {
return compare(example.neq, value) !== 0;
}
if ('eq' in example) {
return compare(example.eq, value) === 0;
}
if ('between' in example) {
return (
testInEquality({ gte: example.between[0] }, value) &&
testInEquality({ lte: example.between[1] }, value)
);
}
if (example.like || example.nlike || example.ilike || example.nilike) {
let like = example.like || example.nlike || example.ilike || example.nilike;
if (typeof like === 'string') {
like = toRegExp(like);
}
if (example.like) {
return !!new RegExp(like).test(value);
}
if (example.nlike) {
return !new RegExp(like).test(value);
}
if (example.ilike) {
return !!new RegExp(like, 'i').test(value);
}
if (example.nilike) {
return !new RegExp(like, 'i').test(value);
}
}
if (testInEquality(example, value)) {
return true;
}
// unlike mongo, test() does not match objects {a: 1} == {a: 1} and {a: 1} != {b: 1}
// The fall-through default is to match as strings, often "[object Object]"
}
// not strict equality
// CAUTION: objects are converted and compared as strings, ie "[object Object]"
return (
// eslint-disable-next-line eqeqeq
(example !== null ? example.toString() : example) == (value != null ? value.toString() : value)
);
}
export type FilterFunction<T> = (obj: T) => boolean;
// TODO: real types
// @ts-ignore
export type Where<T> = any;
export default function whereFilter<T>(filter: Where<T> | FilterFunction<T>): FilterFunction<T> {
if (typeof filter === 'function') {
return filter;
}
const where = filter as any;
const keys = Object.keys(where);
return function (obj: any) {
return keys.every(function (key) {
// the expected value can identity-match only if value is string/number/boolean/null
if (where[key] === obj[key]) return true;
if (key === 'and' || key === 'or') {
if (Array.isArray(where[key])) {
if (key === 'and') {
return where[key].every(function (cond) {
return whereFilter(cond)(obj);
});
}
if (key === 'or') {
return where[key].some(function (cond) {
return whereFilter(cond)(obj);
});
}
}
}
const value = getValue(obj, key);
if (Array.isArray(value)) {
const matcher = where[key];
if (matcher.some) {
return value.some(function (v) {
return whereFilter(matcher.some)(v);
});
}
if (matcher.all) {
return value.every(function (v) {
return whereFilter(matcher.all)(v);
});
}
// below is code for doing `arrayOfScalars: singleContainedValue`
// or an `neq` variant of that
// The following condition is for the case where we are querying with
// a neq filter, and when the value is an empty array ([]).
// the empty array [] matches all neq values
// CAUTION: when an array of and-conditions is applied to an array, the test
// will pass if each condition is matched by _any_ element in the array.
if (matcher.neq !== undefined && value.length <= 0) {
return true;
}
return value.some(function (_v, i) {
return whereFilter({ [i]: matcher })(value);
});
}
if (test(where[key], value)) {
return true;
}
// If we have a composed key a.b and b would resolve to a property of an object inside an array
// then, we attempt to emulate mongo db matching. Helps for embedded relations
const dotIndex = key.indexOf('.');
if (dotIndex !== -1) {
const subValue = obj[key.substring(0, dotIndex)];
const subWhere: Record<string, unknown> = {};
const subKey = key.substring(dotIndex + 1);
subWhere[subKey] = where[key];
if (Array.isArray(subValue)) {
return subValue.some(whereFilter(subWhere));
} else if (typeof subValue === 'object' && subValue !== null) {
return whereFilter(subWhere)(subValue);
}
}
return false;
});
};
}