Skip to content

Instantly share code, notes, and snippets.

@ortense
Last active September 23, 2017 13:38
Show Gist options
  • Save ortense/973e6e2b78bb268b198c699734256c6d to your computer and use it in GitHub Desktop.
Save ortense/973e6e2b78bb268b198c699734256c6d to your computer and use it in GitHub Desktop.
A simple way to validate request schema in express with Joi
const Joi = require('joi')
class ValidationError extends Error {
constructor(joiError) {
super('Request validation error')
this.details = joiError.details
this.type = this.name = this.constructor.name
Object.defineProperties(this, {
type: { enumerable: true, writable: false },
name: { enumerable: false, writable: false },
message: { enumerable: true, writable: false },
})
}
}
module.exports = (schemas = {}) => (request, response, next) => {
const requestSchema = Joi.object(schemas)
const { error, value } = requestSchema.validate(request, { abortEarly: false })
if (error) return next(new ValidationError(error))
Object.keys(schemas).forEach(k => request[k] = value[k])
return next()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment