我正在实施一个限制IP的post upvote系统。到目前为止,对于upvoting单篇文章的路线包含4个总查询,以完成这些步骤:在Sequelize中高效查询
- 寻找有相同的帖子ID和IP,如果存在一个
失败已经存在给予好评 - otherwise-
- 创建给予好评
- 查找后与给予好评关联和它们相关联。
- 最后重新获取帖子以包含刚关联的upvote。
我觉得最后两个步骤可以合并,但是如果我在联合upvote之后返回帖子,则不包含它,因为发现它没有upvote关联。这是我现在拥有的,我觉得这对于一个单独的upvote是非常低效的。
router.get('/posts/:id/upvote', function(req, res) {
var id = req.params.id;
var query_options = {
where: {
id: id
},
include: common_includes
};
// Look for already existing upvote with same PostId and IP.
Upvote.findOne({ where: { ip: req.ip, PostId: id }}).then(function(upvote) {
if (upvote !== null) return res.fail('Already upvoted');
// No upvote exists, create one
Upvote.create({
ip: req.ip
}).then(function(upvote) {
// Find post to associate upvote with
Post.findOne({ where: { id: id }}).then(function(post) {
// Associate upvote to post
upvote.setPost(post).then(function() {
// Query again to get updated post to be returned
Post.findOne(query_options).then(function(post) {
return res.pass(formatPost(post));
}).error(function(err) {
console.log(err);
return res.fail('Server error');
});
}).error(function(err) {
console.log(err);
return res.fail('Server error');
});
}).error(function(err) {
console.log(err);
return res.fail('Server error');
});
}).error(function(err) {
console.log(err);
return res.fail('Server error');
});
});
});
只是一个承诺尖,你不必一切后,键入'.error'。你可以'返回'承诺,然后只有在最后''错误'处理,因为你有相同的功能 –
@MeghParikh你有这样一个小例子吗?我有点明白你的意思,但是如果我在路由之外声明一个通用的错误响应,我怎么能够使用'res'? – Jordan
请参阅http://stackoverflow.com/questions/38080111/expressjs-promises-and-error-handling-middleware和注册路由,我只用'catch'一次 –