S
S
stsin2020-03-03 14:48:18
Node.js
stsin, 2020-03-03 14:48:18

Like / Unlike on the same route?

There is a route in the node project that likes / removes likes.
What best practice will be in this case?
Should I make a separate route ('/unlike/:id') to remove a like?

router.put("/like/:id", auth, async (req, res) => {
  try {
    const comment= await Comment.findById(req.params.id);

    if (
      comment.likes.filter(like => like.user.toString() === req.user.id).length > 0
    ) {
      const removeIndex = comment.likes
        .map(like => like.user.toString())
        .indexOf(req.user.id);

      comment.likes.splice(removeIndex, 1);
    } else {
      comment.likes.unshift({ user: req.user.id });
    }

    await comment.save();

    res.json(comment.likes);
  } catch (err) {
    console.error(err.message);
    res.status(500).send("Server Error");
  }
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Cheremkhin, 2020-03-03
@Che603000

Should I make a separate route ('/unlike/:id') to remove a like?

Why not,
router.delete("/like/:id", auth, async (req, res) => { 
...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question