This repository has been archived by the owner on Aug 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathwhere.js
352 lines (284 loc) · 9.6 KB
/
where.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
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
/**
* Module dependencies
*/
var _ = require('lodash');
var X_ISO_DATE = require('../X_ISO_DATE.constant');
/**
* Apply a(nother) `where` filter to `data`
*
* @param { Object[] } data
* @param { Object } where
* @return { Object[] }
*/
module.exports = function (data, where, schema) {
if( !data ) return data;
schema = schema || {};
return _.filter(data, function(tuple) {
return matchSet(tuple, where, undefined, schema);
});
};
//////////////////////////
///
/// private methods ||
/// \/
///
//////////////////////////
// Match a model against each criterion in a criteria query
function matchSet(model, criteria, parentKey, schema) {
// Null or {} WHERE query always matches everything
if(!criteria || _.isEqual(criteria, {})) return true;
// By default, treat entries as AND
return _.all(criteria, function(criterion, key) {
return matchItem(model, key, criterion, parentKey, schema);
});
}
function matchOr(model, disjuncts, schema) {
var outcomes = [];
_.each(disjuncts, function(criteria) {
if(matchSet(model, criteria, undefined, schema)) outcomes.push(true);
});
var outcome = outcomes.length > 0 ? true : false;
return outcome;
}
function matchAnd(model, conjuncts, schema) {
var outcome = true;
_.each(conjuncts, function(criteria) {
if(!matchSet(model, criteria, undefined, schema)) outcome = false;
});
return outcome;
}
function matchLike(model, criteria, schema) {
for(var key in criteria) {
// Return false if no match is found
if (!checkLike(model[key], criteria[key], schema)) return false;
}
return true;
}
function matchNot(model, criteria, schema) {
return !matchSet(model, criteria, undefined, schema);
}
function matchItem(model, key, criterion, parentKey, schema) {
// Handle special attr query
if (parentKey) {
if (key === 'equals' || key === '=' || key === 'equal') {
return matchLiteral(model, parentKey, criterion, compare['='], schema);
}
else if (key === 'not' || key === '!') {
// Check for Not In
if(Array.isArray(criterion)) {
var match = false;
criterion.forEach(function(val) {
if(compare['='](model[parentKey], val)) {
match = true;
}
});
return match ? false : true;
}
return matchLiteral(model, parentKey, criterion, compare['!'], schema);
}
else if (key === 'greaterThan' || key === '>') {
return matchLiteral(model, parentKey, criterion, compare['>'], schema);
}
else if (key === 'greaterThanOrEqual' || key === '>=') {
return matchLiteral(model, parentKey, criterion, compare['>='], schema);
}
else if (key === 'lessThan' || key === '<') {
return matchLiteral(model, parentKey, criterion, compare['<'], schema);
}
else if (key === 'lessThanOrEqual' || key === '<=') {
return matchLiteral(model, parentKey, criterion, compare['<='], schema);
}
else if (key === 'startsWith') return matchLiteral(model, parentKey, criterion, checkStartsWith, schema);
else if (key === 'endsWith') return matchLiteral(model, parentKey, criterion, checkEndsWith, schema);
else if (key === 'contains') return matchLiteral(model, parentKey, criterion, checkContains, schema);
else if (key === 'like') return matchLiteral(model, parentKey, criterion, checkLike, schema);
else throw new Error ('Invalid query syntax!');
}
else if(key.toLowerCase() === 'or') {
return matchOr(model, criterion, schema);
} else if(key.toLowerCase() === 'not') {
return matchNot(model, criterion, schema);
} else if(key.toLowerCase() === 'and') {
return matchAnd(model, criterion, schema);
} else if(key.toLowerCase() === 'like') {
return matchLike(model, criterion, schema);
}
// IN query
else if(_.isArray(criterion)) {
return _.any(criterion, function(val) {
return compare['='](model[key], val);
});
}
// Special attr query
else if (_.isObject(criterion) && validSubAttrCriteria(criterion)) {
// Attribute is being checked in a specific way
return matchSet(model, criterion, key, schema);
}
// Otherwise, try a literal match
else return matchLiteral(model, key, criterion, compare['='], schema);
}
// Comparison fns
var compare = {
// Equalish
'=' : function (a,b) {
var x = normalizeComparison(a,b);
return x[0] == x[1];
},
// Not equalish
'!' : function (a,b) {
var x = normalizeComparison(a,b);
return x[0] != x[1];
},
'>' : function (a,b) {
var x = normalizeComparison(a,b);
return x[0] > x[1];
},
'>=': function (a,b) {
var x = normalizeComparison(a,b);
return x[0] >= x[1];
},
'<' : function (a,b) {
var x = normalizeComparison(a,b);
return x[0] < x[1];
},
'<=': function (a,b) {
var x = normalizeComparison(a,b);
return x[0] <= x[1];
}
};
// Prepare two values for comparison
function normalizeComparison(a,b) {
if(_.isUndefined(a) || a === null) a = '';
if(_.isUndefined(b) || b === null) b = '';
if (_.isString(a) && _.isString(b)) {
a = a.toLowerCase();
b = b.toLowerCase();
}
// If Comparing dates, keep them as dates
if(_.isDate(a) && _.isDate(b)) {
return [a.getTime(), b.getTime()];
}
// Otherwise convert them to ISO strings
if (_.isDate(a)) { a = a.toISOString(); }
if (_.isDate(b)) { b = b.toISOString(); }
// Stringify for comparisons- except for numbers, null, and undefined
if (!_.isNumber(a)) {
a = typeof a.toString !== 'undefined' ? a.toString() : '' + a;
}
if (!_.isNumber(b)) {
b = typeof b.toString !== 'undefined' ? b.toString() : '' + b;
}
// If comparing date-like things, treat them like dates
if (_.isString(a) && _.isString(b) && a.match(X_ISO_DATE) && b.match(X_ISO_DATE)) {
return ([new Date(a).getTime(), new Date(b).getTime()]);
}
return [a,b];
}
// Return whether this criteria is valid as an object inside of an attribute
function validSubAttrCriteria(c) {
if(!_.isObject(c)) return false;
var valid = false;
var validAttributes = [
'equals', 'not', 'greaterThan', 'lessThan', 'greaterThanOrEqual', 'lessThanOrEqual',
'<', '<=', '!', '>', '>=', 'startsWith', 'endsWith', 'contains', 'like'];
_.each(validAttributes, function(attr) {
if(hasOwnProperty(c, attr)) valid = true;
});
return valid;
}
// Returns whether this value can be successfully parsed as a finite number
function isNumbery (value) {
if(_.isDate(value)) return false;
return Math.pow(+value, 2) > 0;
}
// matchFn => the function that will be run to check for a match between the two literals
function matchLiteral(model, key, criterion, matchFn, schema) {
var val = _.cloneDeep(model[key]);
if(schema && schema[key] && schema[key].type) {
var schemaType = schema[key].type;
// If the value in the schema is a Date, parse it into an ISO Date sting
// so that it can be compared.
if(schemaType === 'date') {
val = new Date(val).toISOString();
criterion = new Date(criterion).toISOString();
}
}
// If the criterion are both parsable finite numbers, cast them
if(isNumbery(criterion) && isNumbery(val)) {
criterion = +criterion;
val = +val;
}
// ensure the key attr exists in model
if(!model.hasOwnProperty(key)) return false;
if(_.isUndefined(criterion)) return false;
// ensure the key attr matches model attr in model
if((!matchFn(val,criterion))) {
return false;
}
// Otherwise this is a match
return true;
}
function checkStartsWith (value, matchString) {
// console.log('CheCKING startsWith ', value, 'against matchString:', matchString, 'result:',sqlLikeMatch(value, matchString));
return sqlLikeMatch(value, matchString + '%');
}
function checkEndsWith (value, matchString) {
return sqlLikeMatch(value, '%' + matchString);
}
function checkContains (value, matchString) {
return sqlLikeMatch(value, '%' + matchString + '%');
}
function checkLike (value, matchString) {
// console.log('CheCKING ', value, 'against matchString:', matchString, 'result:',sqlLikeMatch(value, matchString));
return sqlLikeMatch(value, matchString);
}
function sqlLikeMatch (value,matchString) {
if(_.isRegExp(matchString)) {
// awesome
} else if(_.isString(matchString)) {
// Handle escaped percent (%) signs
matchString = matchString.replace(/%%%/g, '%');
// Escape regex
matchString = escapeRegExp(matchString);
// Replace SQL % match notation with something the ECMA regex parser can handle
matchString = matchString.replace(/([^%]*)%([^%]*)/g, '$1.*$2');
// Case insensitive by default
// TODO: make this overridable
var modifiers = 'i';
matchString = new RegExp('^' + matchString + '$', modifiers);
}
// Unexpected match string!
else {
console.error('matchString:');
console.error(matchString);
throw new Error('Unexpected match string: ' + matchString + ' Please use a regexp or string.');
}
// Deal with non-strings
if(_.isNumber(value)) value = '' + value;
else if(_.isBoolean(value)) value = value ? 'true' : 'false';
else if(!_.isString(value)) {
// Ignore objects, arrays, null, and undefined data for now
// (and maybe forever)
return false;
}
// Check that criterion attribute and is at least similar to the model's value for that attr
if(!value.match(matchString)) {
return false;
}
return true;
}
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
}
/**
* Safer helper for hasOwnProperty checks
*
* @param {Object} obj
* @param {String} prop
* @return {Boolean}
* @api public
*/
var hop = Object.prototype.hasOwnProperty;
function hasOwnProperty(obj, prop) {
return hop.call(obj, prop);
}