So, when a user is requesting resources from my server I of course wish to validate that the request itself is 'secure' and valid. Currently in my code I use this homebrew solution which looks something like:
if(assertThat(validator.isAlphanumeric,data.currentQuestion,next)){return;}
where assertThat() is
var assertThat = function(func,value,next){
if(!func(value)){
var err = new Error("[...]");
err.status = 422;
next(err);
return true;
}
}
This works fine, but that if statement there to prevent further execution has irritated me quite a bit (as properly indenting it uses too much space, yet writing it on one line looks ugly). Is there a way within the Express framework to design a function that will work without that if statement somehow? I might be asking for the impossible, but as my experience with node.js is limited and I am trying to design this application as beautifully as possible I am checking none the less.
Really the only way you could bypass the if is if you insert a custom middleware function before whatever route handler or middleware you were previously using assertThat() in. The middleware could for example take in a list of validators that you want to apply to the request. Example:
function validate(validators) {
return function(req, res, next) {
var data = req.body;
for (var i = 0, validators.length, v; i < len; ++i) {
v = validators[i];
if (!v.fn(data[v.name])) {
var err = new Error('[...]');
err.status = 422;
return next(err);
}
}
next();
};
}
Then you could use it like this:
app.get('/foo',
validate([
{ fn: validator.isAlphanumeric, name: 'currentQuestion' }
]),
function(req, res) {
res.send('Passed validation!');
});