Created
January 9, 2018 02:19
-
-
Save vinicius73/38831526a1367491695e322a93880e4c to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Boom = require('boom') | |
const getData = req => { | |
const data = req.body || req.query | |
return data || {} | |
} | |
const makeError = err => { | |
const { message, details } = err | |
const error = Boom.badRequest('Invalid request data schema', { message, details }) | |
error.output.payload.detail = message | |
error.output.payload.errors = details | |
return error | |
} | |
/** | |
* @method ensureJoiSchema | |
* @param {JoiSchema} schema | |
* @return {RestifyMiddleware} | |
*/ | |
const ensureJoiSchema = schema => (req, res, next) => { | |
const data = getData(req) | |
Joi.validate(data, schema, (err, value) => { | |
if (err) { | |
res.$error(makeError(err)) | |
next(false) | |
return | |
} | |
Object.defineProperty(req, '$requestData', { value, enumerable: true }) | |
next() | |
}) | |
} | |
module.exports = ensureJoiSchema |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment