【问题标题】:Firestore and express, .then chain not stopping when returned res.status(401).json()Firestore 和 express,.then 链在返回 res.status(401).json() 时不会停止
【发布时间】:2020-06-01 15:38:10
【问题描述】:

所以,我正在尝试在我的 API 中实现 .increment。我需要每秒更新一次以上的点赞数,这就是为什么我要尝试更新我的 API 来执行此操作。这是我正在尝试实现的确切代码:

const postRef = db
      .collection('posts')
      .doc(postId);
postRef.update({likeCount: admin.firestore.FieldValue.increment(1)});

当没有与用户句柄关联的当前类似文档时,上面的代码可以完美运行,但是当存在时,

return res.status(401).json({'Error': `${req.user.userHandle} already liked this post`});

被击中并完美返回错误消息。但是,.then 链的其余部分被击中,这是不应该的。

这是有效的旧代码:

exports.likepost = (req, res) => {

    const postId = req.body.postId;

    db
        .collection('posts')
        .doc(postId)
        .get()
        .then((doc) => {
            if(!doc.exists){
                return res.status(404).json({'Error': `post ID ${postId} not found`});
            }
            else{
                return db.collection('likes')
                    .where('postId', '==', postId)
                    .where('userHandle', '==', req.user.userHandle)
                    .get();
            }
        })
        .then((likeDoc) => {
            if(!likeDoc.empty){
                return res.status(404).json({'Error': `${req.user.userHandle} already liked this post`});
            }
            else{
                return db
                    .collection('posts')
                    .doc(postId)
                    .get()
            }
        })
        .then((doc) => {
            const oldLikeCount = doc.data().likeCount;
            const newLikeCount = oldLikeCount + 1;
            return db
                .collection('posts')
                .doc(postId)
                .update({
                    likeCount: newLikeCount
                });
        })
        .then(() => {
            const like = {
                userHandle: req.user.userHandle,
                postId: postId,
                likedAt: new Date().toISOString()
            };

            return db
                    .collection('likes')
                    .add(like);
        })
        .then(() => {
            return res.json({message: `Successfully liked ${postId}`});
        })
        .catch((err) => {
            return res.status(500).json({error: err});
        });
}

在这段代码中, res.status(404).json() 被命中,其余的 .then 链不执行,这是完美的。但是这段代码使用了太多的读写操作,并且每秒更新文档的次数不能超过 1 次。

这是有错误的新代码:

exports.likepost = (req, res) => {

    const postId = req.body.postId;

    db
        .collection('likes')
        .where('postId', '==', postId)
        .where('userHandle', '==', req.user.userHandle)
        .get()
        .then((likeDoc) => {
            if(!likeDoc.empty){
                return res.status(401).json({'Error': `${req.user.userHandle} already liked this post`});
            } // It should stop here but it is not.... the code returns the 401 status and the error message so it hits this code, but it doesn't stop the chain
            else{
                // Update count
                const postRef = db
                    .collection('posts')
                    .doc(postId);
                postRef.update({likeCount: admin.firestore.FieldValue.increment(1)});
            }
        })
        .then(() => {
            const like = {
                userHandle: req.user.userHandle,
                postId: postId,
                likedAt: new Date().toISOString()
            };
            return db
                    .collection('likes')
                    .add(like);
        })
        .then(() => {
            return res.json({message: `Successfully liked ${postId}`});
        })
        .catch((err) => {
            console.error(err);
            return res.status(500).json({error: err});
        });
}

非常感谢任何帮助!!!

【问题讨论】:

    标签: javascript node.js express google-cloud-firestore


    【解决方案1】:

    我不认为将 3 个或 4 个 then() 依次堆叠是一种最佳做法。如果您更改代码以在彼此之间包含then(),则可以减轻这种意外行为。如果您遵循这种方法(在您的新代码版本上),您的代码可能如下所示:

    exports.likepost = (req, res) => {
        const postId = req.body.postId;
        db.collection('likes')
          .where('postId', '==', postId)
          .where('userHandle', '==', req.user.userHandle)
          .get()
          .then((likeDoc) => {
              if(!likeDoc.empty){
                  return res.status(401).json({'Error': `${req.user.userHandle} already liked this post`});
              } 
              else{
                  const postRef = db.collection('posts').doc(postId);
                  postRef.update({likeCount: admin.firestore.FieldValue.increment(1)}).then({
                      const like = {
                          userHandle: req.user.userHandle,
                          postId: postId,
                          likedAt: new Date().toISOString()
                      };
                      db.collection('likes').add(like).then({
                          return res.json({message: `Successfully liked ${postId}`});
                      });
                  });
              }
          })
          .catch((err) => {
                console.error(err);
                return res.status(500).json({error: err});
          });
    }
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-28
      • 1970-01-01
      • 1970-01-01
      • 2015-06-11
      • 1970-01-01
      • 2018-11-14
      • 1970-01-01
      相关资源
      最近更新 更多