Skip to content

Instantly share code, notes, and snippets.

@myndzi
Created July 23, 2017 21:24
Show Gist options
  • Save myndzi/37b68efb0a7f00295b5f953564003611 to your computer and use it in GitHub Desktop.
Save myndzi/37b68efb0a7f00295b5f953564003611 to your computer and use it in GitHub Desktop.
function validate(schema) {
return function (req, res, next) {
// assuming joi callback style validation
schema.validate(req.params, schema, function (err, coercedParams) {
if (err) { next(err); return; } // if you want to handle errors with middleware
// if (err) { req.params = null; req.validationError = err; } // if you want to handle it in your route
else { req.params = coercedParams; } // replacing req.params with the validated/coerced version
next();
});
};
}
// testing it
var validateMiddleware = validate(someSampleSchema);
var req = { params: { foo: 'bar' } };
validateMiddleware(req, res, function (validatedReq) {
// assert that validatedReq is shaped as you expect
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment