[TIL] Node.js 개인과제 (완) 23.06.16

이상훈·2023년 6월 18일
0

[내일배움캠프]

목록 보기
28/68

필수 요구사항

  • 전체 게시글 목록 조회 API
  • 게시글 작성 API
  • 게시글 상세 조회 API
  • 게시글 수정 API
  • 게시글 삭제 API
  • 댓글 목록 조회
  • 댓글 작성
  • 댓글 수정
  • 댓글 삭제
  • EC2 배포

1) 전체 게시글 목록 조회API

// 게시글 전체조회
router.get("/posts", async (req, res) => {
  const showPost = await Posts.find({}).sort({ createdAt: -1 });

  if (!showPost.length) {
    return res.status(404).json({ message: "게시글이 없습니다." });
  }

  const data = showPost.map((post) => {
    return {
      postId: post._id,
      user: post.user,
      title: post.title,
      createdAt: post.createdAt,
    };
  });

  res.json({
    showPost: data,
  });
});

생성날짜를 내림차순으로 sort해서 showPost에 담아준 후 출력

2) 게시글 작성 API

// 게시글 생성
router.post("/posts", async (req, res) => {
  const { user, password, title, content } = req.body;

  if (!user || !password || !title) {
    return res.status(400).json({ message: "데이터를 입력해주세요" });
  }

  const createPosts = await Posts.create({ user, password, title, content });

  res.status(201).json({ posts: createPosts, message: "게시글 생성완료" });
});

body로 값을 받고 user, password, title 중 하나라도 데이터가 없다면 오류메세지를 출력

3) 게시글 상세조회 API

// 게시글 상세 조회
router.get("/posts/:postId", checkObjectId, async (req, res) => {
  const { postId } = req.params;

  const result = await Posts.findById({ _id: new ObjectId(postId) });

  if (!result) {
    return res.status(404).json({ message: "해당 ID로 작성된 게시글이 없습니다." });
  }

  res.status(200).json({
    Detail: {
      postId: result._id,
      user: result.user,
      title: result.title,
      content: result.content,
      createdAt: result.createdAt,
    },
  });
});

params로 string값이 들어오므로 objectId로 만들어 준 후 DB 데이터와 비교.
찾은 데이터를 result에 담아준 후 출력

4) 게시글 수정 API

//게시글 수정
router.put("/posts/:postId", checkObjectId, async (req, res) => {
  const { postId } = req.params;
  const { user, password, title, content } = req.body;

  const modifyPost = await Posts.findById(new ObjectId(postId));
  if (!modifyPost) {
    return res.status(404).json({ message: "해당 ID로 작성된 게시글이 없습니다." });
  } else if (!user || !title || !content) {
    return res.status(400).json({ message: "데이터를 입력해주세요." });
  } else if (modifyPost.password !== password) {
    return res.status(400).json({ message: "잘못된 비밀번호입니다." });
  } else {
    await Posts.updateOne(
      { _id: new ObjectId(postId) },
      { $set: { user: user, title: title, content: content } }
    );
    res.status(201).json({
      message: "게시글 수정 완료",
      Detail: {
        postId: modifyPost._id,
        user: modifyPost.user,
        title: modifyPost.title,
        content: modifyPost.content,
        createdAt: modifyPost.createdAt,
        updatedAt: modifyPost.updatedAt,
      },
    });
  }
});

비밀번호가 동일할 때만 수정이 가능하며 수정할 게시글의 데이터가 입력되지 않은 상태라면 수정이 불가능함

5) 게시글 삭제 API

// 게시글 삭제
router.delete("/posts/:postId", checkObjectId, async (req, res) => {
  const { postId } = req.params;
  const { password } = req.body;

  const deletePost = await Posts.findById({ _id: new ObjectId(postId) });
  if (!deletePost) {
    return res.status(404).json({ message: "해당 ID로 작성된 게시글이 없습니다." });
  } else if (deletePost.password !== password) {
    return res.status(400).json({ message: "잘못된 비밀번호입니다." });
  } else {
    await Posts.deleteOne(new ObjectId(postId));
    await Comments.deleteMany({ postId: new ObjectId(postId) });
    res.status(200).json({ message: "게시글 삭제 완료" });
  }
});

비밀번호가 동일할 때만 삭제가 가능하며 params로 받은 id값이 DB에 없다면 오류메세지 출력
게시글이 삭제되면 게시글에 달린 댓글들도 전부 같이 삭제

6) 댓글 목록 조회

// 댓글 목록 조회
router.get("/comments/:postId", checkObjectId, async (req, res) => {
  const { postId } = req.params;
  const showReview = await Comments.find({ postId: new ObjectId(postId) }).sort({ createdAt: -1 });

  if (!showReview.length) {
    return res.status(404).json({ message: "데이터가 없습니다." });
  }

  const data = showReview.map((comment) => {
    return {
      commentId: comment._id,
      user: comment.user,
      content: comment.content,
      createdAt: comment.createdAt,
    };
  });

  res.json({
    showReview: data,
  });
});

게시글 목록 조회와 같음, showReview에 값이 없다면 오류메세지 출력

7) 댓글 작성

// 댓글 생성
router.post("/comments/:postId", checkObjectId, async (req, res) => {
  const { postId } = req.params;
  const { user, password, content } = req.body;

  const savedPost = await Posts.findById({ _id: new ObjectId(postId) });

  if (!content) {
    return res.status(400).json({ message: "댓글 내용을 입력해주세요." });
  } else if (!savedPost) {
    return res.status(404).json({ message: "해당 게시글을 찾을 수 없습니다." });
  }
  const createComments = await Comments.create({
    postId: new ObjectId(postId),
    user,
    password,
    content,
  });
  res.status(201).json({ comments: createComments, message: "댓글 생성완료" });
});

body로 받은 값에 content 내용이 없다면 오류메세지 출력

8) 댓글 수정

// 댓글 수정
router.put("/comments/:commentId", async (req, res) => {
  const { commentId } = req.params;
  const { password, content } = req.body;

  try {
    new ObjectId(commentId);
  } catch (error) {
    return res.status(400).json({ message: "데이터 형식이 올바르지 않습니다" });
  }

  const modifyReview = await Comments.findById(new ObjectId(commentId));
  if (!modifyReview) {
    return res.status(404).json({ message: "해당 아이디로 작성된 댓글이 없습니다." });
  } else if (modifyReview.password !== password) {
    return res.status(400).json({ message: "잘못된 비밀번호입니다." });
  } else if (!content) {
    return res.status(400).json({ message: "댓글 내용을 입력해주세요." });
  } else {
    await Comments.updateOne({ _id: new ObjectId(commentId) }, { $set: { content: content } });
    res.status(201).json({
      message: "댓글 수정 완료",
      Detail: {
        content: modifyReview.content,
        createdAt: modifyReview.createdAt,
        updatedAt: modifyReview.updatedAt,
      },
    });
  }
});

params로 받은 id값의 댓글 데이터가 없다면 오류메세지 출력, 비밀번호가 동일할 때만 수정가능하며 content내용이 빈값이라면 오류메세지 출력

9) 댓글 삭제

// 댓글 삭제
router.delete("/comments/:commentId", async (req, res) => {
  const { commentId } = req.params;
  const { password } = req.body;

  try {
    new ObjectId(commentId);
  } catch (error) {
    return res.status(400).json({ message: "데이터 형식이 올바르지 않습니다." });
  }

  const deleteReview = await Comments.findById({ _id: new ObjectId(commentId) });
  if (!deleteReview) {
    return res.status(400).json({ message: "해당 아이디로 작성된 댓글이 없습니다." });
  } else if (deleteReview.password !== password) {
    return res.status(400).json({ message: "잘못된 비밀번호입니다." });
  } else {
    await Comments.deleteOne(new ObjectId(commentId));
    res.status(200).json({ message: "댓글 삭제 완료" });
  }
});

비밀번호가 동일 할 때만 삭제 가능하며 params로 받은 commentId값이 없다면 오류메세지 출력

profile
코린이

0개의 댓글