2016-06-28 97 views
1

我正在實施一個限制IP的post upvote系統。到目前爲止,對於upvoting單篇文章的路線包含4個總查詢,以完成這些步驟:在Sequelize中高效查詢

  1. 尋找有相同的帖子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'); 
         }); 
        }); 
    }); 
    
    +1

    只是一個承諾尖,你不必一切後,鍵入'.error'。你可以'返回'承諾,然後只有在最後''錯誤'處理,因爲你有相同的功能 –

    +0

    @MeghParikh你有這樣一個小例子嗎?我有點明白你的意思,但是如果我在路由之外聲明一個通用的錯誤響應,我怎麼能夠使用'res'? – Jordan

    +0

    請參閱http://stackoverflow.com/questions/38080111/expressjs-promises-and-error-handling-middleware和註冊路由,我只用'catch'一次 –

    回答