-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathQueryParser.js
643 lines (547 loc) · 16.8 KB
/
QueryParser.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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
/* eslint-disable max-lines */
/*
* Copyright 2023 Mia s.r.l.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict'
const { ObjectId } = require('mongodb')
const {
ARRAY_MERGE_ELEMENT_OPERATOR,
ARRAY_REPLACE_ELEMENT_OPERATOR,
RAWOBJECTTYPE,
ARRAY,
JSON_SCHEMA_ARRAY_TYPE,
TEXT_INDEX,
NORMAL_INDEX,
JSON_SCHEMA_OBJECT_TYPE,
DATE,
OBJECTID,
GEOPOINT,
} = require('../lib/consts')
const { getFieldDefinition, getFieldDefinitionNameFromQuery } = require('./QueryParser.utils')
const ALLOWED_COMPLEX_TYPES = [ARRAY, RAWOBJECTTYPE, JSON_SCHEMA_OBJECT_TYPE, JSON_SCHEMA_ARRAY_TYPE]
class QueryParser {
constructor(collectionDefinition, pathsForRawSchema) {
this._fieldDefinition = getFieldDefinition(collectionDefinition)
this._nullableFields = getNullableFields(collectionDefinition)
this._rawObjectAccesses = getRawObjectFields(collectionDefinition)
this._pathsForRawSchema = pathsForRawSchema
this._textIndexFields = getTextIndexes(collectionDefinition, TEXT_INDEX)
this._normalIndexes = getTextIndexes(collectionDefinition, NORMAL_INDEX)
this.traverseBinded = value => {
traverse(this._fieldDefinition, this.traverseBinded, value)
}
this.traverseBody = value => {
traverseBody(this._fieldDefinition, this._nullableFields, value)
}
this.traverseCommands = (commands, editableFields) => {
traverseCommands(
this._fieldDefinition,
this._nullableFields,
this._rawObjectAccesses,
commands,
editableFields,
this._pathsForRawSchema
)
}
this.traverseTextSearchQuery = (query) => {
startTraverseTextSearchQuery(query, this._normalIndexes, this._fieldDefinition, this.traverseBinded)
}
this.isTextSearchQuery = (query) => checkIfTextSearchQuery(query)
this.parseAndCastBody = this.parseAndCastBody.bind(this)
}
parseAndCast(query) {
this.traverseBinded(query)
}
parseAndCastBody(doc) {
this.traverseBody(doc)
}
parseAndCastCommands(commands, editableFields) {
this.traverseCommands(commands, editableFields)
}
parseAndCastTextSearchQuery(query) {
this.traverseTextSearchQuery(query)
}
// TODO: understand why this!
isTextSearchQuery(query) {
return this.isTextSearchQuery(query)
}
}
function castDate(value) {
if (value === null) {
return null
}
const type = typeof value
if (type === 'number' || type === 'string') {
const date = new Date(value)
if (!isNaN(date.getTime())) {
return date
}
}
throw new Error('Invalid Date')
}
function castToGeoPoint(value) {
return { type: 'Point', coordinates: value }
}
function castArray(value) {
return value
}
function castToObjectId(value) {
if (value === null) {
return value
}
// Number are accepted by mongodb as timestamp
// for generating the ObjectId in that time
if (ObjectId.isValid(value) && typeof value !== 'number') {
return new ObjectId(value)
}
throw new Error('Invalid objectId')
}
function callCastFunctionOnValue(value, castFunction) {
return castFunction(value)
}
callCastFunctionOnValue.supportedTypes = {
string: true,
boolean: true,
number: true,
integer: true,
Date: true,
ObjectId: true,
Array: false,
GeoPoint: true,
}
function callEq(value, castFunction) {
return castFunction(value)
}
callEq.supportedTypes = {
string: true,
boolean: true,
number: true,
integer: true,
Date: true,
ObjectId: true,
Array: true,
GeoPoint: true,
}
function callCastFunctionOnArray(array, castFunction) {
return array.map(castFunction)
}
callCastFunctionOnArray.supportedTypes = {
string: true,
boolean: true,
number: true,
integer: true,
Date: true,
ObjectId: true,
Array: true,
GeoPoint: true,
}
function castNearSphere(value, castFunction) {
const nearShpere = { $geometry: castFunction(value.from) }
if (value.minDistance) {
nearShpere.$minDistance = value.minDistance
}
if (value.maxDistance) {
nearShpere.$maxDistance = value.maxDistance
}
return nearShpere
}
castNearSphere.supportedTypes = {
string: false,
boolean: false,
number: false,
integer: false,
Date: false,
ObjectId: false,
Array: false,
GeoPoint: true,
}
function callExists(value) {
return value
}
callExists.supportedTypes = {
string: true,
boolean: true,
number: true,
integer: true,
Date: true,
ObjectId: true,
Array: true,
GeoPoint: true,
[RAWOBJECTTYPE]: true,
[JSON_SCHEMA_OBJECT_TYPE]: true,
}
function callElemMatch(value) {
return value
}
callElemMatch.supportedTypes = {
string: false,
boolean: false,
number: false,
integer: false,
Date: false,
ObjectId: false,
Array: true,
GeoPoint: false,
}
function callSize(value) {
// https://www.mongodb.com/docs/manual/reference/operator/query/size/
return value
}
callSize.supportedTypes = {
string: false,
boolean: false,
number: false,
integer: false,
Date: false,
ObjectId: false,
Array: true,
GeoPoint: false,
}
const castValueFunctions = {
[DATE]: castDate,
[OBJECTID]: castToObjectId,
[GEOPOINT]: castToGeoPoint,
[ARRAY]: castArray,
}
const traverseOperatorFunctions = {
$gt: callCastFunctionOnValue,
$lt: callCastFunctionOnValue,
$gte: callCastFunctionOnValue,
$lte: callCastFunctionOnValue,
$eq: callEq,
$ne: callCastFunctionOnValue,
$in: callCastFunctionOnArray,
$nin: callCastFunctionOnArray,
$all: callCastFunctionOnArray,
$exists: callExists,
$nearSphere: castNearSphere,
$regex: callCastFunctionOnValue,
$elemMatch: callElemMatch,
// for $regex
$options: callCastFunctionOnValue,
$size: callSize,
}
function identity(value) {
return value
}
// eslint-disable-next-line max-statements
function traverse(fieldDefinition, traverseBinded, query) {
for (const key of Object.keys(query)) {
if (key.startsWith('$')) {
if (key === '$and' || key === '$or') {
query[key].forEach(traverseBinded)
continue
}
if (key === '$text') {
continue
}
throw new Error(`Unknown operator: ${key}`)
}
const definition = getFieldDefinitionNameFromQuery(key)
if (!fieldDefinition[definition.split('.')[0]]) {
throw new Error(`Unknown field: ${key}`)
}
const type = fieldDefinition[definition]
const castValueFunction = castValueFunctions[type] || identity
const value = query[key]
if (value === undefined) {
continue
}
if (value === null || (value && value.constructor !== Object)) {
query[key] = castValueFunction(value, fieldDefinition[key])
continue
}
const queryKey = Object.keys(value)
for (const operator of queryKey) {
if (
!operator.startsWith('$') && ALLOWED_COMPLEX_TYPES.includes(type)) {
continue
}
const traverseOperatorFunction = traverseOperatorFunctions[operator]
if (!traverseOperatorFunction) {
throw new Error(`Unsupported operator: ${operator}`)
}
if (Boolean(type) && !traverseOperatorFunction.supportedTypes[type]) {
throw new Error(`Unsupported operator: ${operator} for ${type} field`)
}
const operatorValue = value[operator]
query[key][operator] = traverseOperatorFunction(operatorValue, castValueFunction)
}
}
}
function traverseBody(fieldDefinition, nullableFields, doc) {
const keys = Object.keys(doc)
for (const key of keys) {
if (!fieldDefinition[key]) {
throw new Error(`Unknown field: ${key}`)
}
const type = fieldDefinition[key]
const castValueFunction = castValueFunctions[type]
if (!castValueFunction) {
continue
}
const value = doc[key]
if (value === null && nullableFields[key]) {
continue
}
// NOTE: this implementation is constrained and does not support nested objects
if (type === ARRAY && fieldDefinition[`${key}.__items`]) {
const itemCastFunction = castValueFunctions[fieldDefinition[`${key}.__items`]] ?? ((elem) => elem)
doc[key] = value.map(itemCastFunction)
} else {
doc[key] = castValueFunction(value)
}
}
}
function getNullableFieldsCompatibility(collectionDefinition) {
return collectionDefinition
.fields
.reduce((acc, field) => {
if (field.nullable === true) {
acc[field.name] = true
}
return acc
}, {})
}
function getNullableFields(collectionDefinition) {
if (!collectionDefinition.schema) {
return getNullableFieldsCompatibility(collectionDefinition)
}
return Object
.entries(collectionDefinition.schema.properties)
.reduce((acc, [propertyName, jsonSchema]) => {
acc[propertyName] = jsonSchema.nullable
return acc
}, {})
}
function getRawObjectFieldsCompatibility(collectionDefinition) {
return collectionDefinition
.fields
.reduce((acc, field) => {
if (field.type !== RAWOBJECTTYPE) {
return acc
}
acc.push(new RegExp(`^${field.name}\\.`))
return acc
}, [])
}
function getRawObjectFields(collectionDefinition) {
if (!collectionDefinition.schema) {
return getRawObjectFieldsCompatibility(collectionDefinition)
}
return Object
.entries(collectionDefinition.schema.properties)
.reduce((acc, [propertyName, jsonSchema]) => {
if (jsonSchema.type !== JSON_SCHEMA_OBJECT_TYPE) {
return acc
}
acc.push(new RegExp(`^${propertyName}\\.`))
return acc
}, [])
}
function getTextIndexes(collectionDefinition, type) {
if (!collectionDefinition.indexes) {
return []
}
return collectionDefinition
.indexes
.filter(index => index.type === type)
.reduce((acc, index) => [...acc, ...index.fields.map(el => el.name)], [])
}
function transformArrayMergeCommands(arrayName, arrayElementFields, fieldName, changesForCommand) {
Object.keys(arrayElementFields).forEach((key) => {
changesForCommand[`${arrayName}.$.${key}`] = arrayElementFields[key]
})
delete changesForCommand[fieldName]
}
function transformReplaceCommands(arrayName, fieldName, changesForCommand) {
changesForCommand[`${arrayName}.$`] = changesForCommand[fieldName]
delete changesForCommand[fieldName]
}
function transformArrayCommands(arrayData, changesForCommand) {
const { arrayName, arrayElementFields, fieldName, arrayOperation } = arrayData
if (!arrayElementFields) {
throw new Error('Invalid value for array operation')
}
const isAMerge = (arrayOperation === `.${ARRAY_MERGE_ELEMENT_OPERATOR}`)
const isAReplace = (arrayOperation === `.${ARRAY_REPLACE_ELEMENT_OPERATOR}`)
if (isAMerge) {
transformArrayMergeCommands(arrayName, arrayElementFields, fieldName, changesForCommand)
}
if (isAReplace) {
transformReplaceCommands(arrayName, fieldName, changesForCommand)
}
}
// eslint-disable-next-line max-statements
function traverseCommands(
fieldDefinition,
nullableFields,
rawObjectAccesses,
commands,
editableFields,
pathsForRawSchema
) {
for (const key of Object.keys(commands)) {
if (key === '$unset' || key === '$currentDate') {
continue
}
const changesForCommand = commands[key]
const fieldKeys = Object.keys(changesForCommand)
for (const fieldName of fieldKeys) {
const splitFieldName = fieldName.split('.$')
if (isFieldAnArray(splitFieldName, fieldDefinition, pathsForRawSchema)) {
const arrayType = fieldDefinition[`${fieldName}.__items`]
const castValueFunction = castValueFunctions[arrayType]
if (castValueFunction) {
changesForCommand[fieldName] = castValueFunction(changesForCommand[fieldName])
}
const arrayData = {
arrayName: splitFieldName[0],
arrayElementFields: changesForCommand[fieldName],
fieldName,
arrayOperation: splitFieldName[1],
}
transformArrayCommands(arrayData, changesForCommand)
continue
}
if (Boolean(
getRawSchemaFieldPath(fieldName, pathsForRawSchema))
|| rawObjectAccesses.some(objKey => objKey.test(fieldName))
) {
// Allow anything
continue
}
const fieldType = fieldDefinition[fieldName]
if (!fieldType) {
throw new Error('Unknown fields')
}
if (!editableFields.includes(fieldName)) {
throw new Error(`You cannot edit "${fieldName}" field`)
}
const castValueFunction = castValueFunctions[fieldType] || identity
const value = changesForCommand[fieldName]
if (value === null && nullableFields[fieldName]) {
continue
}
changesForCommand[fieldName] = castValueFunction(value)
}
}
}
function isFieldAnArray(splitFieldName, fieldDefinition, pathsForRawSchema) {
const isArrayType = (fieldDefinition[splitFieldName[0]] === ARRAY)
return isArrayType || getRawSchemaFieldPath(splitFieldName[0], pathsForRawSchema)?.type === JSON_SCHEMA_ARRAY_TYPE
}
function getRawSchemaFieldPath(fieldPath, rawSchemas = {}) {
const { paths } = rawSchemas
if (paths[fieldPath]) {
return paths[fieldPath]
}
// we do this sort to match the strictest regex
// in some cases we could have a shorter regex matching the pattern
// and returning the element.
const patternProperties = Object
.keys(rawSchemas.patternProperties ?? {})
.sort((firstRegex, secondRegex) => secondRegex.length - firstRegex.length)
const fromPatternProperties = patternProperties.find(pattern => new RegExp(pattern).test(fieldPath))
if (fromPatternProperties) {
return rawSchemas.patternProperties[fromPatternProperties]
}
return null
}
// eslint-disable-next-line max-statements
function traverseTextSearchQuery(query, normalIndexes) {
const keys = Object.keys(query)
for (const key of keys) {
if (key === '$text') {
if (countTextOccurrences(query[key]) > 1) {
throw new Error(`Query ${query} has more than one $text expression`)
}
const textQueryKeys = Object.keys(query[key])
if (!textQueryKeys.includes('$search')) {
throw new Error(`$text search query ${query[key]} must include $search field`)
}
for (const textOptionKey of textQueryKeys) {
if (!['$search', '$language', '$caseSensitive', '$diacriticSensitive'].includes(textOptionKey)) {
throw new Error(`Unknown option for $text search query: ${textOptionKey}`)
}
}
continue
}
if (key === '$nor') {
query.$nor.forEach(clause => {
if (checkIfTextSearchQuery(clause)) {
throw new Error('$text can not appear in a $nor expression')
}
})
continue
}
if (key === '$elemMatch') {
query.$elemMatch.split(',').forEach(clause => {
if (checkIfTextSearchQuery(clause)) {
throw new Error('$text query can not appear in a $elemMatch query expression')
}
})
continue
}
if (key === '$or') {
query[key].forEach(clause => {
Object.keys(clause).forEach(orKey => {
if (orKey[0] !== '$' && !normalIndexes.includes(orKey)) {
throw new Error('To use a $text query in an $or expression, all clauses in the $or array must be indexed')
}
traverseTextSearchQuery(clause, normalIndexes)
})
})
continue
}
if (key[0] === '$') {
const clauses = query[key]
if (Array.isArray(clauses)) {
clauses.forEach(clause => traverseTextSearchQuery(clause, normalIndexes))
continue
}
if ((typeof clauses) === 'object') {
// eslint-disable-next-line id-length
Object.keys(clauses).forEach(k => traverseTextSearchQuery(clauses[k], normalIndexes))
continue
}
}
}
}
function startTraverseTextSearchQuery(query, normalIndexes, fieldDefinition, traverseBinded) {
// $text query should conform both to standard query rules and to $text query rules
traverse(fieldDefinition, traverseBinded, query)
traverseTextSearchQuery(query, normalIndexes)
}
const recursiveSearch = (query, searchKey, results = []) => {
Object.keys(query).forEach(key => {
const value = query[key]
if (key === searchKey) {
results.push(value)
} else if (value && typeof value === 'object') {
recursiveSearch(value, searchKey, results)
}
})
return results
}
function checkIfTextSearchQuery(query) {
const occurrences = recursiveSearch(query, '$text', [])
return Array.isArray(occurrences) && occurrences.length > 0
}
function countTextOccurrences(query) {
const occurrences = recursiveSearch(query, '$text', [])
return occurrences.length
}
module.exports = QueryParser