我如何检查currentUser是否喜欢该帖子

时间:2019-10-27 18:39:14

标签: javascript sequelize.js

我有一个放置请求,该请求可以增加/减少,例如Count post。它获取帖子ID,然后执行以下操作

喜欢

enter image description here

不一样

enter image description here

我如何以这种方式重构代码,如果当前用户喜欢它,则喜欢根据。

我如何检查它是否被ByMe或当前用户喜欢?

post.controller.js

likePost: async (req: Request, res: Response) => {
    const id = req.params.id;

    const post = await models.Post.findByPk(id);

    if (post.liked === true) {
      post
        .update({
          liked: false,
          likeCounts: post.likeCounts === 0 ? 0 : --post.likeCounts
        })
        .then(unliked => {
          res.status(200).send({
            message: "You have unliked this post",
            post: unliked
          });
        });
    } else {
      post
        .update({
          liked: true,
          likeCounts: ++post.likeCounts
        })
        .then(liked => {
          res.status(200).send({
            message: "This post has been liked",
            post: liked
          });
        });
    }
  }

修改后的代码可以正常工作

 likePost: async (req: any, res: Response) => {
    const id = req.params.id;
    const userId = req.params.userId
    const post = await models.Post.findByPk(id);

    if (userId === post.authorId){
      if (post.liked === true) {
        post
          .update({
            liked: false,
            likeCounts: post.likeCounts === 0 ? 0 : --post.likeCounts
          })
          .then(unliked => {
            res.status(200).send({
              message: "You have unliked this post",
              post: unliked
            });
          });
      } else {
        post
          .update({
            liked: true,
            likeCounts: ++post.likeCounts
          })
          .then(liked => {
            res.status(200).send({
              message: "This post has been liked",
              post: liked
            });
          });
      }
     }
  }

0 个答案:

没有答案