-
Notifications
You must be signed in to change notification settings - Fork 152
/
joi-mongoose-helper.js
733 lines (633 loc) Β· 20.3 KB
/
joi-mongoose-helper.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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
'use strict'
let Joi = require('@hapi/joi')
Joi.objectId = require('joi-objectid')(Joi)
let _ = require('lodash')
let validationHelper = require('./validation-helper')
let queryHelper = require('./query-helper')
let config = require('../config')
let mongoose = require('mongoose')
// TODO: support "allowNull"
// TODO: add ".default()" to paths that have a default value
// TODO: support arrays and objects
// TODO: support "allowUndefined"
const internals = {}
/**
* Generates a Joi object that validates a query result for a specific model
* @param model: A mongoose model object.
* @param logger: A logging object.
* @returns {*}: A Joi object
*/
internals.generateJoiReadModel = function(model, logger) {
const Log = logger.bind()
validationHelper.validateModel(model, Log)
let readModelBase = {}
let fields = model.schema.tree
let associations = model.routeOptions.associations
? Object.keys(model.routeOptions.associations)
: []
for (let fieldName in fields) {
let field = fields[fieldName]
let isAssociation = associations.indexOf(fieldName)
if (field.readModel) {
readModelBase[fieldName] = field.readModel
} else if (
field.allowOnRead !== false &&
field.exclude !== true &&
isAssociation < 0 &&
internals.isValidField(fieldName, field, model)
) {
let attributeReadModel = internals.generateJoiFieldModel(
model,
field,
fieldName,
'read',
Log
)
if (field.requireOnRead === true) {
attributeReadModel = attributeReadModel.required()
}
readModelBase[fieldName] = attributeReadModel
}
}
if (model.routeOptions && model.routeOptions.associations) {
for (let associationName in model.routeOptions.associations) {
let association = model.routeOptions.associations[associationName]
let associationModel = Joi.object()
if (association.type === 'MANY_MANY') {
if (association.linkingModel) {
associationModel = internals.generateJoiReadModel(
association.include.through,
Log
)
}
let associationBase = {}
associationBase[association.model] = Joi.object()
associationBase._id = internals.joiObjectId()
// EXPL: remove the key for the current model
if (associationModel._inner.children) {
associationModel._inner.children = associationModel._inner.children.filter(
function(key) {
return key.key !== model.modelName
}
)
}
// EXPL: add the keys for the association model and the _id
associationModel = associationModel.keys(associationBase)
// EXPL: also accept MANY_MANY flattened embeddings
associationModel = Joi.alternatives().try(
associationModel,
Joi.object()
)
} else if (association.type === '_MANY') {
associationModel = Joi.alternatives().try(
internals.joiObjectId(),
Joi.object()
)
}
associationModel = associationModel.label(
model.modelName + '_' + associationName + 'Model'
)
if (
association.type === 'MANY_MANY' ||
association.type === 'ONE_MANY' ||
association.type === '_MANY'
) {
readModelBase[associationName] = Joi.array()
.items(associationModel)
.label(model.modelName + '_' + associationName + 'ArrayModel')
} else {
readModelBase[associationName] = associationModel
}
}
}
let readModel = Joi.object(readModelBase).label(model.modelName + 'ReadModel')
return readModel
}
/**
* Generates a Joi object that validates a query request payload for updating a document
* @param model: A mongoose model object.
* @param logger: A logging object.
* @returns {*}: A Joi object
*/
internals.generateJoiUpdateModel = function(model, logger) {
const Log = logger.bind()
validationHelper.validateModel(model, Log)
let updateModelBase = {}
let fields = model.schema.tree
let associations = model.routeOptions.associations
? model.routeOptions.associations
: {}
for (let fieldName in fields) {
let field = fields[fieldName]
let association = associations[fieldName] || null
let canUpdateAssociation = association
? association.type === 'ONE_ONE' ||
association.type === 'MANY_ONE' ||
association.type === '_MANY'
: false
if (internals.isValidField(fieldName, field, model)) {
if (field.updateModel) {
updateModelBase[fieldName] = field.updateModel
} else if (
field.allowOnUpdate !== false &&
(canUpdateAssociation || !association)
) {
let attributeUpdateModel = internals.generateJoiFieldModel(
model,
field,
fieldName,
'update',
Log
)
if (field.requireOnUpdate === true) {
attributeUpdateModel = attributeUpdateModel.required()
}
updateModelBase[fieldName] = attributeUpdateModel
}
}
}
let updateModel = Joi.object(updateModelBase).label(
model.modelName + 'UpdateModel'
)
return updateModel
}
/**
* Generates a Joi object that validates a request payload for creating a document
* @param model: A mongoose model object.
* @param logger: A logging object.
* @returns {*}: A Joi object
*/
internals.generateJoiCreateModel = function(model, logger) {
const Log = logger.bind()
validationHelper.validateModel(model, Log)
let createModelBase = {}
let fields = model.schema.tree
let associations = model.routeOptions.associations
? model.routeOptions.associations
: {}
for (let fieldName in fields) {
let field = fields[fieldName]
let association = associations[fieldName] || null
let canCreateAssociation = association
? association.type === 'ONE_ONE' ||
association.type === 'MANY_ONE' ||
association.type === '_MANY'
: false
if (internals.isValidField(fieldName, field, model)) {
// EXPL: use the field createModel if one is defined
if (field.createModel) {
createModelBase[fieldName] = field.createModel
} else if (
field.allowOnCreate !== false &&
(canCreateAssociation || !association)
) {
let attributeCreateModel = internals.generateJoiFieldModel(
model,
field,
fieldName,
'create',
Log
)
if (field.required === true) {
attributeCreateModel = attributeCreateModel.required()
}
createModelBase[fieldName] = attributeCreateModel
}
}
}
let createModel = Joi.object(createModelBase).label(
model.modelName + 'CreateModel'
)
return createModel
}
/**
* Generates a Joi object that validates a request query for the list function
* @param model: A mongoose model object.
* @param logger: A logging object.
* @returns {*}: A Joi object
*/
internals.generateJoiListQueryModel = function(model, logger) {
const Log = logger.bind()
let queryModel = {
$skip: Joi.number()
.integer()
.min(0)
.optional()
.description(
'The number of records to skip in the database. This is typically used in pagination.'
),
$page: Joi.number()
.integer()
.min(0)
.optional()
.description(
'The number of records to skip based on the $limit parameter. This is typically used in pagination.'
),
$limit: Joi.number()
.integer()
.min(0)
.optional()
.description(
'The maximum number of records to return. This is typically used in pagination.'
)
}
let queryableFields = queryHelper.getQueryableFields(model, Log)
let readableFields = queryHelper.getReadableFields(model, Log)
let sortableFields = queryHelper.getSortableFields(model, Log)
if (queryableFields && readableFields) {
queryModel.$select = Joi.alternatives().try(
Joi.array()
.items(Joi.string().valid(readableFields))
.description(
'A list of basic fields to be included in each resource. Valid values include: ' +
readableFields.toString().replace(/,/g, ', ')
),
Joi.string().valid(readableFields)
)
queryModel.$text = Joi.any().description(
'A full text search parameter. Takes advantage of indexes for efficient searching. Also implements stemming ' +
'with searches. Prefixing search terms with a "-" will exclude results that match that term.'
)
queryModel.$term = Joi.any().description(
"A regex search parameter. Slower than `$text` search but supports partial matches and doesn't require " +
'indexing. This can be refined using the `$searchFields` parameter.'
)
queryModel.$searchFields = Joi.alternatives().try(
Joi.array()
.items(Joi.string().valid(queryableFields))
.description(
'A set of fields to apply the `$term` search parameter to. If this parameter is not included, the `$term` ' +
'search parameter is applied to all searchable fields. Valid values include: ' +
queryableFields.toString().replace(/,/g, ', ')
),
Joi.string().valid(queryableFields)
)
queryModel.$sort = Joi.alternatives().try(
Joi.array()
.items(Joi.string().valid(sortableFields))
.description(
'A set of fields to sort by. Including field name indicates it should be sorted ascending, while prepending ' +
"'-' indicates descending. The default sort direction is 'ascending' (lowest value to highest value). Listing multiple" +
'fields prioritizes the sort starting with the first field listed. Valid values include: ' +
sortableFields.toString().replace(/,/g, ', ')
),
Joi.string().valid(sortableFields)
)
queryModel.$exclude = Joi.alternatives().try(
Joi.array()
.items(internals.joiObjectId())
.description('A list of objectIds to exclude in the result.'),
internals.joiObjectId()
)
queryModel.$count = Joi.boolean().description(
'If set to true, only a count of the query results will be returned.'
)
if (config.enableWhereQueries) {
queryModel.$where = Joi.any()
.optional()
.description('An optional field for raw mongoose queries.')
}
_.each(queryableFields, function(fieldName) {
const joiModel = internals.generateJoiModelFromFieldType(
model.schema.paths[fieldName].options,
Log
)
queryModel[fieldName] = Joi.alternatives().try(
Joi.array()
.items(joiModel)
.description('Match values for the ' + fieldName + ' property.'),
joiModel
)
})
}
let associations = model.routeOptions ? model.routeOptions.associations : null
if (associations) {
queryModel.$embed = Joi.alternatives().try(
Joi.array()
.items(Joi.string())
.description(
'A set of complex object properties to populate. Valid first level values include ' +
Object.keys(associations)
.toString()
.replace(/,/g, ', ')
),
Joi.string()
)
queryModel.$flatten = Joi.boolean().description(
'Set to true to flatten embedded arrays, i.e. remove linking-model data.'
)
}
queryModel = Joi.object(queryModel)
if (!config.enableQueryValidation) {
queryModel = queryModel.unknown()
}
return queryModel
}
/**
* Generates a Joi object that validates a request query for the find function
* @param model: A mongoose model object.
* @param logger: A logging object.
* @returns {*}: A Joi object
*/
internals.generateJoiFindQueryModel = function(model, logger) {
const Log = logger.bind()
let queryModel = {}
let readableFields = queryHelper.getReadableFields(model, Log)
if (readableFields) {
queryModel.$select = Joi.alternatives().try(
Joi.array()
.items(Joi.string().valid(readableFields))
.description(
'A list of basic fields to be included in each resource. Valid values include: ' +
readableFields.toString().replace(/,/g, ', ')
),
Joi.string().valid(readableFields)
)
}
let associations = model.routeOptions ? model.routeOptions.associations : null
if (associations) {
queryModel.$embed = Joi.alternatives().try(
Joi.array()
.items(Joi.string())
.description(
'A set of complex object properties to populate. Valid first level values include ' +
Object.keys(associations)
.toString()
.replace(/,/g, ', ')
),
Joi.string()
)
queryModel.$flatten = Joi.boolean().description(
'Set to true to flatten embedded arrays, i.e. remove linking-model data.'
)
}
queryModel = Joi.object(queryModel)
if (!config.enableQueryValidation) {
queryModel = queryModel.unknown()
}
return queryModel
}
/**
* Generates a Joi object for a model field
* @param model: A mongoose model object
* @param field: A model field
* @param fieldName: The name of the field
* @param modelType: The type of CRUD model being generated
* @param logger: A logging object
* @returns {*}: A Joi object
*/
internals.generateJoiFieldModel = function(
model,
field,
fieldName,
modelType,
logger
) {
const Log = logger.bind()
let fieldModel = {}
let joiModelFunction = {}
let nested = model.schema.nested
let instance = model.schema.paths[fieldName]
? model.schema.paths[fieldName].instance
: null
let isArray = false
if (instance === 'Array' || _.isArray(field.type)) {
isArray = true
// EXPL: if the array contains objects, then it has nested fields
if (_.isObject(field[0]) || field.type[0].name === 'Mixed') {
nested[fieldName] = true
}
}
if (instance === 'Mixed' && !nested[fieldName]) {
// EXPL: check for any valid nested fields
for (let key in field) {
if (internals.isValidField(key, field[key], model)) {
nested[fieldName] = true
}
}
}
// EXPL: if this field is nested, we treat it as a nested model and recursively call the appropriate model function
if (nested[fieldName]) {
switch (modelType) {
case 'read':
joiModelFunction = internals.generateJoiReadModel
break
case 'create':
joiModelFunction = internals.generateJoiCreateModel
break
case 'update':
joiModelFunction = internals.generateJoiUpdateModel
break
default:
throw new Error(
"modelType must be either 'read', 'create', or 'update'"
)
}
field = _.isObject(field[0]) ? field[0] : field
// EXPL: make a copy so field properties aren't deleted from the original model
field = _.extend({}, field)
// EXPL: remove all fields that aren't objects, since they can cause issues with the schema
for (let subField in field) {
if (!_.isObject(field[subField])) {
delete field[subField]
}
}
let nestedModel = {
modelName: model.modelName + '.' + fieldName,
fakeModel: true,
isArray: isArray,
routeOptions: {},
schema: new mongoose.Schema(field)
}
fieldModel = joiModelFunction(nestedModel, Log)
if (isArray) {
let label = fieldModel._flags.label
fieldModel = Joi.array()
.items(fieldModel)
.label(label + 'Array')
}
} else {
fieldModel = internals.generateJoiModelFromFieldType(field, Log)
}
return fieldModel
}
/**
* Returns a Joi object based on the mongoose field type.
* @param field: A field from a mongoose model.
* @param logger: A logging object.
* @returns {*}: A Joi object.
*/
internals.generateJoiModelFromFieldType = function(field, logger) {
let model
// assert(field.type, "incorrect field format");
let isArray = false
let fieldCopy = _.extend({}, field)
if (_.isArray(fieldCopy.type)) {
isArray = true
fieldCopy.type.schemaName = fieldCopy.type[0].name
}
if (!fieldCopy.type) {
fieldCopy.type = {
schemaName: 'None'
}
}
switch (fieldCopy.type.schemaName) {
case 'ObjectId':
model = internals.joiObjectId()
break
case 'Mixed':
model = Joi.object()
break
case 'Boolean':
model = Joi.bool()
break
case 'Number':
model = Joi.number()
break
case 'Date':
model = Joi.date()
break
case 'String':
if (fieldCopy.enum) {
model = Joi.any().only(fieldCopy.enum)
} else if (fieldCopy.regex) {
if (!(fieldCopy.regex instanceof RegExp)) {
if (fieldCopy.regex.options) {
model = Joi.string().regex(
fieldCopy.regex.pattern,
fieldCopy.regex.options
)
} else {
model = Joi.string().regex(fieldCopy.regex.pattern)
}
} else {
model = Joi.string().regex(fieldCopy.regex)
}
} else if (fieldCopy.stringType) {
switch (fieldCopy.stringType) {
case 'uri':
model = Joi.string().uri()
break
case 'email':
model = Joi.string().email()
break
case 'token':
model = Joi.string().token()
break
case 'hex':
model = Joi.string().hex()
break
case 'base64':
model = Joi.string().base64()
break
case 'hostname':
model = Joi.string().hostname()
break
case 'lowercase':
model = Joi.string().lowercase()
break
case 'uppercase':
model = Joi.string().uppercase()
break
case 'trim':
model = Joi.string().trim()
break
case 'creditCard':
model = Joi.string().creditCard()
break
default:
model = Joi.string().allow('')
}
} else {
model = Joi.string().allow('')
}
break
default:
model = Joi.any()
break
}
if (fieldCopy.allowNull) {
model = model.allow(null)
}
if (isArray) {
model = Joi.array().items(model)
}
if (fieldCopy.description) {
model = model.description(fieldCopy.description)
} else if (fieldCopy.stringType) {
model = model.description(fieldCopy.stringType)
}
return model
}
/**
* Provides easy access to the Joi ObjectId type.
* @returns {*|{type}}
*/
internals.joiObjectId = function() {
// EXPL: Rather than converting all objectIds to string for response, we allow raw mongoose.Types.ObjectId objects
let objectIdModel = Joi.object({
_bsontype: Joi.any().required(),
id: Joi.any().required()
})
let model = Joi.alternatives().try(
Joi.objectId().description('ObjectId'),
objectIdModel
)
return model
}
/**
* Returns true if arg is a true ObjectId or ObjectId string, false otherwise.
* @returns {boolean}
*/
internals.isObjectId = function(arg) {
let result = Joi.validate(arg, internals.joiObjectId())
if (result.error) {
return false
}
return true
}
/**
* Checks to see if a field is a valid model property
* @param fieldName: The name of the field
* @param field: The field being checked
* @param model: A mongoose model object
* @returns {boolean}
*/
internals.isValidField = function(fieldName, field, model) {
const invalidFieldNames = ['__t', '__v']
if (!_.isObject(field)) {
return false
}
// EXPL: avoid adding schema types
if (
fieldName === 'type' &&
(field.schemaName ||
(field[0] && field[0].schemaName) ||
field.name === 'Mixed')
) {
return false
}
// EXPL: ignore the '_id' field for fake models
if (model.fakeModel && !model.isArray) {
invalidFieldNames.push('_id')
}
// EXPL: ignore the 'id' field if it is a virtual field (i.e. not included in the user-defined schema)
if (_.get(model, 'schema.virtuals.id', null)) {
invalidFieldNames.push('id')
}
if (invalidFieldNames.indexOf(fieldName) > -1) {
return false
}
return true
}
module.exports = {
generateJoiReadModel: internals.generateJoiReadModel,
generateJoiUpdateModel: internals.generateJoiUpdateModel,
generateJoiCreateModel: internals.generateJoiCreateModel,
generateJoiListQueryModel: internals.generateJoiListQueryModel,
generateJoiFindQueryModel: internals.generateJoiFindQueryModel,
generateJoiFieldModel: internals.generateJoiFieldModel,
generateJoiModelFromFieldType: internals.generateJoiModelFromFieldType,
joiObjectId: internals.joiObjectId,
isObjectId: internals.isObjectId
}