Skip to content

Instantly share code, notes, and snippets.

@skwee357
Created August 27, 2016 10:11
Show Gist options
  • Save skwee357/7e4ca3b913f4b1202f51d72fcb1ac0db to your computer and use it in GitHub Desktop.
Save skwee357/7e4ca3b913f4b1202f51d72fcb1ac0db to your computer and use it in GitHub Desktop.
var Joi = require('joi'),
util = require('util'),
_ = require('lodash');
var BadRequestError = function (errors) {
Error.captureStackTrace(this, this.constructor);
this.name = 'BadRequestError';
this.message = 'Bad Request Error';
this.errors = errors;
};
util.inherits(BadRequestError, Error);
var validate = function (schema) {
return function (req, res, next) {
var body = _.extend({}, req.body);
delete body.access_token; //remove access token for api calls
Joi.validate(body, schema, {abortEarly: false}, function (err, schemaResult) {
if (err) {
var details = [];
err.details.forEach(function (d) {
details.push({message: d.message, path: d.path});
});
return next(new BadRequestError(details));
}
req.schema = schemaResult;
return next();
});
}
};
module.exports = {
validate: validate,
BadRequestError: BadRequestError
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment