2019-10-07 08:13:41 -04:00
|
|
|
const { Joi: CelebrateJoi, celebrate, errors } = require('celebrate')
|
2020-05-20 10:18:08 -04:00
|
|
|
const { ObjectId } = require('./mongojs')
|
2019-10-07 08:13:41 -04:00
|
|
|
|
2020-05-20 10:18:08 -04:00
|
|
|
const objectIdValidator = {
|
|
|
|
name: 'objectId',
|
|
|
|
language: {
|
|
|
|
invalid: 'needs to be a valid ObjectId'
|
|
|
|
},
|
|
|
|
pre(value, state, options) {
|
|
|
|
if (!ObjectId.isValid(value)) {
|
|
|
|
return this.createError('objectId.invalid', { value }, state, options)
|
|
|
|
}
|
|
|
|
|
|
|
|
if (options.convert) {
|
|
|
|
return new ObjectId(value)
|
|
|
|
}
|
|
|
|
|
|
|
|
return value
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const Joi = CelebrateJoi.extend(objectIdValidator)
|
2019-10-07 08:13:41 -04:00
|
|
|
const errorMiddleware = errors()
|
|
|
|
|
|
|
|
module.exports = { Joi, validate, errorMiddleware }
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Validation middleware
|
|
|
|
*/
|
|
|
|
function validate(schema) {
|
|
|
|
return celebrate(schema, { allowUnknown: true })
|
|
|
|
}
|