Skip to content

Instantly share code, notes, and snippets.

@wesdeveloper
Created April 12, 2019 17:46
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 wesdeveloper/a836cc3bf0eea3a3d91d6e7e6630be2b to your computer and use it in GitHub Desktop.
Save wesdeveloper/a836cc3bf0eea3a3d91d6e7e6630be2b to your computer and use it in GitHub Desktop.
const Joi = require('joi');
const validateParam = (schema, name) => (req, res, next) => {
const result = Joi.validate({ param: req.params[name] }, schema);
if (result.error) {
return res.status(400).json(result.error);
}
if (!req.payload) {
req.payload = {};
}
if (!req.payload.params) {
req.payload.params = {};
}
req.payload.params[name] = req.params[name];
return next();
};
const validateBody = schema => (req, res, next) => {
const result = Joi.validate(req.body, schema, { abortEarly: false });
if (result.error) {
const errors = result.error.details.reduce(
(acc, curr) =>
acc.concat({ path: curr.path.join('.'), message: curr.message }),
[],
);
return res.status(400).send({ status: 400, errors });
}
if (!req.payload) {
req.payload = {};
}
if (!req.payload.body) {
req.payload.body = {};
}
req.payload.body = result.value;
return next();
};
const validateObject = (object, schema) => {
const result = Joi.validate(object, schema, { abortEarly: false });
if (result.error) {
return result.error.details;
}
return true;
};
module.exports = {
validateBody,
validateParam,
validateObject,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment