Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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