requestValidator.jslib/ | |
---|---|
var _ = require("underscore");
var parse = {
string:function(val) {
return val.toString();
},
int:function(val) {
var num = parseInt(val);
if(isNaN(num))
return 0;
else
return num
},
float:function(val) {
var num = parseFloat(val);
if(isNaN(num))
return 0;
else
return num
}
};
exports.makeValidator = function(reqMap) {
return function(req,res,next) {
var proceed = false
, reqKeys = _.keys(req.body); | |
figuring out if the request passes | if(reqMap.canOnly) {
if(reqMap.canOnly.length === reqKeys.length) { |
this test dictates that the request must have the keys in canOnly and none other | proceed = _.chain(reqKeys)
.intersection(reqMap.canOnly)
.value().length === reqMap.canOnly.length;
}
} else if(reqMap.must) { |
this test dictates that the request must have the keys in reqMap.must | proceed = _.chain(reqMap.must)
.map(function(key) {
return _.contains(reqKeys,key);
})
.every()
.value();
} else {
proceed = true;
}
if(proceed) {
if(reqMap.omit) {
req.body = _.omit(req.body,reqMap.omit);
}
if(reqMap.types) {
_.each(reqMap.types,function(type,key) {
if(_.has(req.body,key)) {
req.body[key] = parse[type](req.body[key]);
}
});
}
next();
} else {
res.send(400);
}
}
};
|