Created
April 12, 2019 17:46
-
-
Save wesdeveloper/a836cc3bf0eea3a3d91d6e7e6630be2b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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