Backend ๐Ÿ“š/Node.js

[Node]Instagram Clone - 8. ๋Œ“๊ธ€ ์‚ญ์ œ API

leejaejae 2024. 11. 4. 14:00
  • ์‚ฌ์šฉ์ž๊ฐ€ ๊ฒŒ์‹œ๋ฌผ์—์„œ ๋ณธ์ธ์ด ์ž‘์„ฑํ•œ ๋Œ“๊ธ€์„ ์‚ญ์ œํ•  ์ˆ˜ ์žˆ๋Š” ๊ธฐ๋Šฅ์„ ๊ตฌํ˜„ํ•จ

1. ๋Œ“๊ธ€ ์‚ญ์ œ

1) ๋Œ“๊ธ€ ์‚ญ์ œ ๋ผ์šฐํ„ฐ

const express = require("express");
const router = express.Router();

const { Comment } = require("../../models/Comment"); // ๋Œ“๊ธ€ ๋ชจ๋ธ
const { Post } = require("../../models/Post"); // ๊ฒŒ์‹œ๋ฌผ ๋ชจ๋ธ
const { auth } = require("../auth");

const cookieParser = require("cookie-parser");
router.use(cookieParser());

router.delete("/:commentId", auth, async (req, res) => {
  const commentId = req.params.commentId; // ๊ฒฝ๋กœ ๋งค๊ฐœ๋ณ€์ˆ˜์—์„œ commentId ๊ฐ€์ ธ์˜ค๊ธฐ
  const userId = req.user._id; // ๋กœ๊ทธ์ธ๋œ ์‚ฌ์šฉ์ž ID

  try {
    // ๋Œ“๊ธ€์„ ์ฐพ์•„์„œ ์‚ญ์ œ
    const comment = await Comment.findById(commentId);
    if (!comment) {
      return res.status(404).json({ message: "๋Œ“๊ธ€์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค." });
    }

    // ๋Œ“๊ธ€ ์ž‘์„ฑ์ž๊ฐ€ ๋งž๋Š”์ง€ ํ™•์ธ
    if (comment.user.toString() !== userId.toString()) {
      return res
        .status(403)
        .json({ message: "๋Œ“๊ธ€์„ ์‚ญ์ œํ•  ๊ถŒํ•œ์ด ์—†์Šต๋‹ˆ๋‹ค." });
    }

    // ๋Œ“๊ธ€ ์‚ญ์ œ
    await Comment.findByIdAndDelete(commentId);

    // ๋Œ“๊ธ€์ด ๋‹ฌ๋ฆฐ ๊ฒŒ์‹œ๋ฌผ์—์„œ ๋Œ“๊ธ€ ID ์ œ๊ฑฐ
    await Post.findByIdAndUpdate(comment.post, {
      $pull: { comments: commentId },
    });

    return res.status(200).json({
      message: "๋Œ“๊ธ€์ด ์„ฑ๊ณต์ ์œผ๋กœ ์‚ญ์ œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.",
    });
  } catch (error) {
    return res.status(500).json({
      message: "๋Œ“๊ธ€ ์‚ญ์ œ ์ค‘ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค.",
      error: error.message,
    });
  }
});

module.exports = router;
  • ๋Œ“๊ธ€ ์•„์ด๋”” ์ž…๋ ฅํ•ด ์‚ญ์ œ ๊ตฌํ˜„
  • ๋กœ๊ทธ์ธํ–ˆ์„ ๋•Œ๋งŒ ์‚ญ์ œ ๊ฐ€๋Šฅ (auth ๋ฏธ๋“ค์›จ์–ด ์‚ฌ์šฉ)
  • ๋Œ“๊ธ€ ์ž‘์„ฑํ•œ ๋ณธ์ธ๋งŒ ์‚ญ์ œ ๊ฐ€๋Šฅ(user ์•„์ด๋”” ํ™•์ธํ•จ)

 

2. ๊ฒฐ๊ณผ ๐ŸŽ‰


1) ๋Œ“๊ธ€ ์‚ญ์ œ ์„ฑ๊ณต