Skip to content

Instantly share code, notes, and snippets.

@leodutra
Forked from nkt/restify-joi-validation.js
Created November 17, 2017 06:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leodutra/9549b81c1617d3e54465b7ae59de3e30 to your computer and use it in GitHub Desktop.
Save leodutra/9549b81c1617d3e54465b7ae59de3e30 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