Created
May 17, 2015 15:16
-
-
Save nkt/c93fc4c42069c2699e0e to your computer and use it in GitHub Desktop.
Restify middleware for validation using Joi package
This file contains hidden or 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 {BadRequestError} = require('restify/lib/errors'); | |
const Joi = require('joi'); | |
module.exports = function validationPlugin() { | |
const fields = ['params', 'query', 'body']; | |
return function validationMiddleware(req, res, next) { | |
if (!req.route || !req.route.validate) { | |
return next(); | |
} | |
let schema = {}; | |
let data = {}; | |
fields.forEach((field) => { | |
if (req.route.validate[field]) { | |
schema[field] = req.route.validate[field]; | |
data[field] = req[field]; | |
} | |
}); | |
Joi.validate(data, schema, { | |
abortEarly: false, | |
convert: true, | |
allowUnknown: true, | |
stripUnknown: true | |
}, (err, value) => { | |
if (err) { | |
const errors = err.details.map((e) => { | |
return { | |
code: e.type, | |
detail: e.message, | |
paths: e.path.split('.') | |
}; | |
}); | |
let error = new BadRequestError(); | |
error.body = errors; | |
return next(error); | |
} | |
Object.assign(req, value); | |
next(); | |
}); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment