有没有一种方法可以简化node.js + express中的代码?
// Backend handler to register a new participant
app.post('/api/participant', function (req, res, next) {
// I'm catching the registration form from the request
var data = req.body;
// I want to make sure the user is not uploading data other
// than the fields in the form
var participant = new Participant({
first: data.first,
last: data.last,
email: data.email,
category: data.category
});
participant.save(...);
});
我没有这样做:
var participant = new Participant(data);
因为任何人都可以score
在数据对象中包含(例如)一个属性,并利用竞争优势开始竞争。
所以我的问题是:我必须在每个后处理程序中执行此操作,还是有一种过滤属性的方法?
快速的Google搜索未找到任何预先存在的库,但是此功能可以很好地完成此工作:
function filterKeys(object, keys) {
Object.keys(object).forEach(function(key) {
if(keys.indexOf(key) == -1) {
delete object[key];
}
});
}
举个例子,
var foo = {"foo": 1, "bar": 2, "baz": 3};
console.log(foo); // {"foo": 1, "bar": 2, "baz": 3}
filterKeys(foo, ["foo", "baz"]);
console.log(foo); // {"foo": 1, "baz": 3}
所以就你而言
filterKeys(data, ["first", "last", "email", "category"]);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句