[TIL] 210707

오늘은 어제 만든 댓글 삭제기능에서 어떻게 표시되게 하는것과 수정삭제 API를 만들었다.

-------🖥️ Frontend-------

📂 수정칸 열고닫기

프론트쪽에서 관건은 수정버튼을 눌렀을때 어떻게 새로운 공간을 만들어주고 기존에 있던 댓글 내용을 그대로 보여주는가였다. 찾아보다가 버튼을 클릭하면 display를 none에서 block으로 만들어주면서 숨겨저있던 공간을 보여주는 코드를 발견해서 한번 접목해보았다.
새로운 공간을 보여주면서 기존에 있던 공간도 같이 없애줘야해서 누르는 동시에 "기존공간", "새로운공간", "수정 확인버튼" 이 세개를 변화하도록 만들었다.
처음엔 어떤내용인지만 불러오는 API이기 때문에 type을 "GET"으로 했다가 어떤 댓글의 내용을 가지고 올지 몰라서 order 데이터를 넘겨주면서 "POST"로 했다.
지금 생각해보니 url로 order 데이터를 넘겨주면서 "GET" 해도 되긴했다.

function openEdit(order) {
  $.ajax({
    type: 'POST',
    url: `comments/read/edit/${postId}`,
    data: { order: order },
    success: function (response) {
      const comment = response['comment'];
      const preDiv = document.getElementById(`pastCommentContext${order}`);
      const div = document.getElementById(`commentOrder${order}`);
      const button = document.getElementById(`editOrder${order}`);

      if (div.style.display === 'none') {
        preDiv.style.display = 'none';
        div.style.display = 'block';
        button.style.display = 'block';
        $(`#commentOrder${order}`).val(`${comment['comment']}`);
      } else {
        preDiv.style.display = 'block';
        div.style.display = 'none';
        button.style.display = 'none';
      }
    },
  });
}

📂 수정 & 삭제 API

여기까지만 완성하면 수정API와 삭제API는 기존에 했던 CRUD 활용하면 됐다.

function editComment(order) {
  let newComment = $(`#commentOrder${order}`).val();

  $.ajax({
    type: 'PUT',
    url: `comments/edit/${postId}`,
    data: {
      comment: newComment,
      order: order,
    },
    success: function (response) {
      alert('수정되었습니다.');
      window.location.reload();
    },
  });
}

function deleteComment(order) {
  const answer = confirm('정말로 삭제하시겠습니까?');
  if (!answer) {
    return;
  } else {
    $.ajax({
      type: 'DELETE',
      url: `comments/delete/${postId}`,
      data: {
        order: order,
      },
      success: function (response) {
        alert('삭제되었습니다.');
        window.location.reload();
      },
    });
  }
}

-------⚙️ Backend-------

📂 수정 & 삭제 API

router.post('/read/edit/:postId', async (req, res) => {
  const { postId } = req.params;
  const { order } = req.body;
  const comments = await Comment.findOne({ $and: [{ postId }, { order }] });

  res.send({ comment: comments });
});

router.put('/edit/:postId', async (req, res) => {
  const { postId } = req.params;
  const { order, comment } = req.body;

  if (comment === '') {
    res.status(400).send({
      errorMessage: '댓글을 작성해주세요.',
    });
    return;
  }

  await Comment.updateOne(
    {
      $and: [{ postId }, { order }],
    },
    { $set: { comment } }
  );

  res.send();
});

router.delete('/delete/:postId', async (req, res) => {
  const { postId } = req.params;
  const { order } = req.body;

  await Comment.deleteOne({
    $and: [{ postId }, { order }],
  });

  res.send();
});

좋은 웹페이지 즐겨찾기