Skip to content

Instantly share code, notes, and snippets.

@nkt
Created May 17, 2015 15:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nkt/c93fc4c42069c2699e0e to your computer and use it in GitHub Desktop.
Save nkt/c93fc4c42069c2699e0e to your computer and use it in GitHub Desktop.
Restify middleware for validation using Joi package
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