Last active
September 23, 2017 13:38
-
-
Save ortense/973e6e2b78bb268b198c699734256c6d to your computer and use it in GitHub Desktop.
A simple way to validate request schema in express with Joi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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