Backend ๐Ÿ“š/Node.js

[Node]Instagram Clone - 7. ๋Œ“๊ธ€ ์ƒ์„ฑ API

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

1. ๋Œ“๊ธ€ ์Šคํ‚ค๋งˆ ์„ค๊ณ„

  • ๋Œ“๊ธ€(Comment)์„ ์ €์žฅํ•˜๊ธฐ ์œ„ํ•ด Mongoose๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋Œ“๊ธ€ ๋ชจ๋ธ์„ ์ •์˜.
  • ์ด ๋ชจ๋ธ์€ ๋Œ“๊ธ€์ด ์†ํ•œ ๊ฒŒ์‹œ๋ฌผ๊ณผ ์ž‘์„ฑ์ž ์ •๋ณด๋ฅผ ํฌํ•จํ•ด์•ผ ํ•จ!

1) ๋Œ“๊ธ€ ์Šคํ‚ค๋งˆ (comment.js)

(์ด์ „ ํฌ์ŠคํŠธ)

2. ๋Œ“๊ธ€ ์ƒ์„ฑ API ๊ตฌํ˜„

  • ์ด์ œ ๋Œ“๊ธ€์„ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ๋Š” API ์—”๋“œํฌ์ธํŠธ๋ฅผ ์„ค์ •.
  • ์‚ฌ์šฉ์ž๊ฐ€ ๋กœ๊ทธ์ธํ–ˆ์„ ๋•Œ๋งŒ ๋Œ“๊ธ€์„ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ๋„๋ก ์ธ์ฆ ๋ฏธ๋“ค์›จ์–ด๋ฅผ ์‚ฌ์šฉ.

1) ๋Œ“๊ธ€ ์ƒ์„ฑ ๋ผ์šฐํ„ฐ

//createComment.js

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.post("/:postId", auth, async (req, res) => {
  const { text } = req.body; // ์š”์ฒญ ๋ณธ๋ฌธ์—์„œ text๋งŒ ๊ฐ€์ ธ์˜ค๊ธฐ
  const postId = req.params.postId; // ๊ฒฝ๋กœ ๋งค๊ฐœ๋ณ€์ˆ˜์—์„œ postId ๊ฐ€์ ธ์˜ค๊ธฐ
  const userId = req.user._id; // ๋กœ๊ทธ์ธ๋œ ์‚ฌ์šฉ์ž ID

  try {
    // ํ•ด๋‹น ๊ฒŒ์‹œ๋ฌผ์ด ์กด์žฌํ•˜๋Š”์ง€ ํ™•์ธ
    const post = await Post.findById(postId);
    if (!post) {
      return res.status(404).json({ message: "๊ฒŒ์‹œ๋ฌผ์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค." });
    }

    // ๋Œ“๊ธ€ ์ƒ์„ฑ
    const newComment = new Comment({
      post: postId,
      user: userId,
      post: postId,
      text: text,
      createdAt: Date.now(),
    });

    await newComment.save(); // ๋Œ“๊ธ€ DB์— ์ €์žฅ

    // // ๊ฒŒ์‹œ๋ฌผ์— ๋Œ“๊ธ€ ์ถ”๊ฐ€
    // post.comments.push(newComment._id);
    // await post.save();

    // ๊ฒŒ์‹œ๋ฌผ์˜ comments ๋ฐฐ์—ด์— ๋Œ“๊ธ€ ID ์ถ”๊ฐ€
    await Post.findByIdAndUpdate(postId, {
      $push: { comments: newComment._id },
    });

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

module.exports = router;

 

3. ์‘๋‹ต ์˜ˆ์‹œ

  • ๋Œ“๊ธ€์ด ์„ฑ๊ณต์ ์œผ๋กœ ์ถ”๊ฐ€๋˜๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์€ JSON ํ˜•์‹์˜ ์‘๋‹ต์„ ๋ฐ›์Œ
json
์ฝ”๋“œ ๋ณต์‚ฌ
{
  "message": "๋Œ“๊ธ€์ด ์„ฑ๊ณต์ ์œผ๋กœ ์ถ”๊ฐ€๋˜์—ˆ์Šต๋‹ˆ๋‹ค.",
  "comment": {
    "_id": "comment_id",
    "post": "post_id",
    "user": "user_id",
    "text": "์ด ๊ฒŒ์‹œ๋ฌผ ์ •๋ง ์ข‹๋„ค์š”!",
    "createdAt": "2024-11-02T07:00:00.000Z"
  }
}

 

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

  • ์•„์ง ๋Œ“๊ธ€ ์‚ญ์ œ ๊ธฐ๋Šฅ ๊ตฌํ˜„์ด ์•ˆ๋˜์–ด ์žˆ์–ด์„œ comments ์ปฌ๋ ‰์…˜์—์„œ ๋Œ“๊ธ€์„ ์ง€์›Œ๋„ posts์—๋Š” ์ด์ „ ๋Œ“๊ธ€๋“ค์ด ๋‚จ์•„์žˆ์Œ
  • ๊ทธ๋ž˜์„œ ๋‹ค์Œ์—” ๋Œ“๊ธ€ ์‚ญ์ œ๋ฅผ ๊ตฌํ˜„ํ•ด๋ณผ๊ฑฐ์ž„~