sauceCtrl_manageLike

PHOTO EMBED

Wed Sep 08 2021 16:24:25 GMT+0000 (UTC)

Saved by @devdave

exports.manageLike = (req, res, next) => {
  // grabs user id
  let userId = req.body.userId;
  // grabs sauce id
  let sauceId = req.params.id;
  // grabs 'like' in request body
  let like = req.body.like;

  if (like === 1) {
    // if user smashes the like button
    // => updates the sauce given its id
    Sauce.updateOne(
      { _id: sauceId },
      {
        // [ mongoDB push operator ]
        // pushes userId to usersLiked: [array]
        $push: { usersLiked: userId },
        // [ mongoDB increment operator ]
        // increments likes [array]
        $inc: { likes: +1 },
      }
    )
      .then(() =>
        res.status(200).json({ message: "Like ajouté par l'utilisateur !" })
      )
      .catch((error) => res.status(400).json({ error }));
  }

  if (like === -1) {
    // if user smashes the dislike button
    // => updates the sauce given its id
    Sauce.updateOne(
      { _id: sauceId },
      {
        // [ mongoDB push operator ]
        // pushes userId to usersDisliked: [array]
        $push: { usersDisliked: userId },
        // [ mongoDB increment operator ]
        // increments dislikes [array]
        $inc: { dislikes: +1 },
      }
    )
      .then(() =>
        res.status(200).json({ message: "Dislike ajouté par l'utilisateur !" })
      )
      .catch((error) => res.status(400).json({ error }));
  }

  // Remove like / dislike
  if (like === 0) {
    Sauce.findOne({
      _id: sauceId,
    })
      .then((sauce) => {
        // remove like
        // if user has already liked
        if (sauce.usersLiked.includes(userId)) {
          Sauce.updateOne(
            { _id: sauceId },
            { $pull: { usersLiked: userId }, $inc: { likes: -1 } }
          )
            .then(() =>
              res
                .status(200)
                .json({ message: "Like retiré par l'utilisateur !" })
            )
            .catch((error) => res.status(400).json({ error }));
        }
        // remove dislike
        // if user has already disliked
        if (sauce.usersDisliked.includes(userId)) {
          Sauce.updateOne(
            { _id: sauceId },
            { $pull: { usersDisliked: userId }, $inc: { dislikes: -1 } }
          )
            .then(() =>
              res
                .status(200)
                .json({ message: "Dislike retiré par l'utilisateur !" })
            )
            .catch((error) => res.status(400).json({ error }));
        }
      })
      .catch((error) => res.status(400).json({ error }));
  }
};
content_copyCOPY