-
-
Save myndzi/37b68efb0a7f00295b5f953564003611 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
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