Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
508 lines (442 loc) · 13.5 KB
/
Copy pathindex.js
File metadata and controls
508 lines (442 loc) · 13.5 KB
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
const types = {
array: require('./types/array'),
boolean: require('./types/boolean'),
datetime: require('./types/datetime'),
media: require('./types/media'),
mixed: require('./types/mixed'),
number: require('./types/number'),
object: require('./types/object'),
objectid: require('./types/objectid'),
reference: require('./types/reference'),
string: require('./types/string')
}
const ValidationError = require('./lib/validation-error')
const ACCESS_TYPES = [
'delete',
'deleteOwn',
'create',
'read',
'readOwn',
'update',
'updateOwn'
]
class Validator {
constructor({i18nFieldCharacter = ':', internalFieldPrefix = '_'} = {}) {
this.i18nFieldCharacter = i18nFieldCharacter
this.internalFieldPrefix = internalFieldPrefix
}
validateAccessMatrix(matrix, fieldName) {
const fieldPrefix = fieldName ? `${fieldName}.` : ''
const errors = []
if (typeof matrix === 'object') {
Object.keys(matrix).forEach(type => {
if (!ACCESS_TYPES.includes(type)) {
errors.push({
code: 'ERROR_INVALID_ACCESS_TYPE',
field: `${fieldPrefix}${type}`,
message: 'is not a valid access type'
})
}
switch (typeof matrix[type]) {
case 'boolean':
return
case 'object':
Object.keys(matrix[type]).forEach(key => {
if (['fields', 'filter'].includes(key)) {
if (typeof matrix[type][key] !== 'object') {
errors.push({
code: 'ERROR_INVALID_ACCESS_VALUE',
field: `${fieldPrefix}${type}.${key}`,
message:
'is not a valid value for the access type (expected Object)'
})
} else if (key === 'fields') {
const fieldsObj = matrix[type][key]
const fields = Object.keys(fieldsObj)
// A valid fields projection is an object where all fields are
// 0 or 1, never combining the two.
const invalidProjection = fields.some((field, index) => {
if (fieldsObj[field] !== 0 && fieldsObj[field] !== 1) {
return true
}
const nextField = fields[index + 1]
if (
nextField !== undefined &&
fieldsObj[field] !== fieldsObj[nextField]
) {
return true
}
return false
})
if (invalidProjection) {
errors.push({
code: 'ERROR_INVALID_ACCESS_VALUE',
field: `${fieldPrefix}${type}.fields`,
message:
'is not a valid field projection – accepted values for keys are either 0 or 1 and they cannot be combined in the same projection'
})
}
}
} else {
errors.push({
code: 'ERROR_INVALID_ACCESS_VALUE',
field: `${fieldPrefix}${type}.${key}`,
message: 'is not a valid key for an access value'
})
}
})
break
default:
errors.push({
code: 'ERROR_INVALID_ACCESS_VALUE',
field: `${fieldPrefix}${type}`,
message:
'is not a valid access value (expected Boolean or Object)'
})
}
})
} else {
errors.push({
code: 'ERROR_INVALID_ACCESS_MATRIX',
field: fieldName,
message: 'is not a valid access matrix object'
})
}
if (errors.length > 0) {
throw errors
}
}
validateDocument({document = {}, isUpdate = false, schema = {}}) {
const errors = []
let chain = Promise.resolve()
Object.keys(document).forEach(field => {
const value = document[field]
// Ignore internal fields.
if (field.indexOf(this.internalFieldPrefix) === 0) {
return
}
const canonicalName = field.split(this.i18nFieldCharacter)[0]
const fieldSchema = schema[canonicalName]
// If the value is `undefined` and the field is required, we'll deal with
// it when we iterate over the schema fields. We do this to avoid errors
// being added twice.
if (document[field] === undefined && fieldSchema.required) return
if (!fieldSchema) {
return errors.push({
code: 'ERROR_NOT_IN_SCHEMA',
field,
message: 'is not part of the schema'
})
}
chain = chain.then(() => {
return this.validateValue({
schema: fieldSchema,
value
}).catch(valueError => {
const valueErrors = Array.isArray(valueError)
? valueError
: [valueError]
valueErrors.forEach(error => {
const errorData = {
field: error.field || field,
message: error.message
}
if (typeof error.code === 'string') {
errorData.code = error.code
}
errors.push(errorData)
})
})
})
})
// Finding missing fields if we are validating a new document
// (i.e. not an update).
if (!isUpdate) {
Object.keys(schema).forEach(field => {
if (document[field] === undefined && schema[field].required) {
return errors.push({
code: 'ERROR_REQUIRED',
field,
message: 'must be specified'
})
}
})
}
return chain.then(() => {
if (errors.length > 0) {
return Promise.reject(errors)
}
return
})
}
validateDocuments({documents, schema}) {
documents = Array.isArray(documents) ? documents : [documents]
return documents.reduce((chain, document) => {
return chain.then(() => {
return this.validateDocument({
document,
schema
})
})
}, Promise.resolve())
}
validateSchemaField(name, schema) {
const errors = []
if (typeof schema.type === 'string') {
schema.type = schema.type.toLowerCase()
if (!types[schema.type]) {
const availableTypes = Object.keys(types).join(', ')
errors.push({
code: 'ERROR_INVALID_FIELD_TYPE',
field: `fields.${name}`,
message: `does not have a valid type (${schema.type}). Valid types: ${availableTypes}`
})
}
} else {
errors.push({
code: 'ERROR_MISSING_FIELD_TYPE',
field: `fields.${name}`,
message: 'must contain a `type` property'
})
}
return errors
}
validateSchemaFieldName(name) {
const regExp = /^[a-zA-Z0-9_-]+$/
if (typeof name !== 'string' || !regExp.test(name)) {
return [
{
code: 'ERROR_INVALID_FIELD_NAME',
field: `fields.${name}`,
message: `must be a non-empty string matching the expression '${regExp.toString()}'`
}
]
}
return []
}
validateSchemaFields(fields) {
if (
!fields ||
typeof fields !== 'object' ||
fields.toString() !== '[object Object]'
) {
return Promise.reject([
{
code: 'ERROR_INVALID_FIELDS',
field: 'fields',
message: 'must be an object'
}
])
}
if (Object.keys(fields).length === 0) {
return Promise.reject([
{
code: 'ERROR_EMPTY_FIELDS',
field: 'fields',
message: 'must contain at least one field'
}
])
}
const errors = Object.keys(fields).reduce((errors, fieldName) => {
const fieldErrors = this.validateSchemaField(
fieldName,
fields[fieldName]
).concat(this.validateSchemaFieldName(fieldName))
return errors.concat(fieldErrors)
}, [])
return errors.length > 0 ? Promise.reject(errors) : Promise.resolve()
}
validateSchemaSettings(settings) {
if (
!settings ||
typeof settings !== 'object' ||
settings.toString() !== '[object Object]'
) {
return Promise.reject([
{
code: 'ERROR_INVALID_SETTINGS',
field: 'settings',
message: 'must be an object'
}
])
}
const errors = []
const {
authenticate,
cache,
callback,
count,
defaultFilters,
displayName,
enableVersioning,
fieldLimiters,
index,
versioningCollection
} = settings
if (
authenticate !== null &&
authenticate !== undefined &&
typeof authenticate !== 'boolean'
) {
const isVerbArray =
Array.isArray(authenticate) &&
authenticate.every(item => {
return ['delete', 'get', 'post', 'put'].includes(
item.toString().toLowerCase()
)
})
if (!isVerbArray) {
errors.push({
code: 'ERROR_INVALID_SETTING',
field: 'settings.authenticate',
message:
'must be a Boolean or an array including one or more HTTP verbs (DELETE, GET, POST, PUT)'
})
}
}
if (cache !== null && cache !== undefined && typeof cache !== 'boolean') {
errors.push({
code: 'ERROR_INVALID_SETTING',
field: 'settings.cache',
message: 'must be a Boolean'
})
}
if (
count !== null &&
count !== undefined &&
(typeof count !== 'number' || !Number.isInteger(count) || count <= 0)
) {
errors.push({
code: 'ERROR_INVALID_SETTING',
field: 'settings.count',
message: 'must be a positive, integer number'
})
}
if (
callback &&
(typeof callback !== 'string' || callback.trim().length === 0)
) {
errors.push({
code: 'ERROR_INVALID_SETTING',
field: 'settings.callback',
message: 'must be a non-empty string'
})
}
if (
defaultFilters !== null &&
defaultFilters !== undefined &&
defaultFilters.toString() !== '[object Object]'
) {
errors.push({
code: 'ERROR_INVALID_SETTING',
field: 'settings.defaultFilters',
message: 'must be an object'
})
}
if (
displayName &&
(typeof displayName !== 'string' || displayName.trim().length === 0)
) {
errors.push({
code: 'ERROR_INVALID_SETTING',
field: 'settings.displayName',
message: 'must be a non-empty string'
})
}
if (
enableVersioning !== undefined &&
typeof enableVersioning !== 'boolean'
) {
errors.push({
code: 'ERROR_INVALID_SETTING',
field: 'settings.enableVersioning',
message: 'must be a Boolean'
})
}
if (fieldLimiters !== null && fieldLimiters !== undefined) {
if (fieldLimiters.toString() === '[object Object]') {
let expectedValue
const isFieldProjection = Object.keys(fieldLimiters).every(
(fieldName, index) => {
if (index === 0) {
expectedValue = fieldLimiters[fieldName]
} else if (fieldLimiters[fieldName] !== expectedValue) {
return false
}
return (
fieldLimiters[fieldName] === 1 || fieldLimiters[fieldName] === 0
)
}
)
if (!isFieldProjection) {
errors.push({
code: 'ERROR_INVALID_SETTING',
field: 'settings.fieldLimiters',
message:
'must be an object with a field projection (i.e. field names as keys and either all 1 or all 0 as values)'
})
}
} else {
errors.push({
code: 'ERROR_INVALID_SETTING',
field: 'settings.fieldLimiters',
message: 'must be an object'
})
}
}
if (index !== null && index !== undefined) {
const values = Array.isArray(index) ? index : [index]
const areValuesValid = values.every(
value => value.toString() === '[object Object]'
)
if (!areValuesValid) {
errors.push({
code: 'ERROR_INVALID_SETTING',
field: 'settings.index',
message: 'must be an object or array of objects'
})
}
}
if (
versioningCollection !== null &&
versioningCollection &&
(typeof versioningCollection !== 'string' ||
versioningCollection.trim().length === 0)
) {
errors.push({
code: 'ERROR_INVALID_SETTING',
field: 'settings.versioningCollection',
message: 'must be a non-empty string'
})
}
return errors.length > 0 ? Promise.reject(errors) : Promise.resolve()
}
validateValue({schema, value}) {
const type = schema.type && schema.type.toLowerCase()
const typeHandler = types[type]
if (typeof typeHandler !== 'function') {
return new ValidationError().reject()
}
// We treat null values as a special case. If the field is required,
// we reject with the `ERROR_REQUIRED` code, because technically the
// field is not set. If the field is not required, we accept the value.
if (value === null || value === undefined) {
if (schema.required) {
return new ValidationError().reject(
'must be specified',
'ERROR_REQUIRED'
)
}
return Promise.resolve()
}
return typeHandler({
schema,
value
}).then(() => {
if (typeof schema.validationCallback === 'function') {
return Promise.resolve(schema.validationCallback(value))
}
})
}
}
module.exports = Validator