2023. 1. 6. 06:29ㆍ프로젝트/7주차 클론 코딩
댓글 CRUD(Create, Update, Update, Delete) + 대댓글 / 좋아요 중에서
대댓글에 관한 내용만 포스팅 하기로 했다. 다른 내용이나 자세한 코드는 깃허브를 참조하면 될 것 같습니다.
1. 구현 방법
이래저래 찾아봤었던 결과, 1. 참조를 이용하는 방식 / 2. 참조를 이용하지 않는 방식 이 있었다.
1번의 방법으로 구현하고 싶었으나, 한정된 시간이라는 이유로 2번의 방식으로 구현하게 되었다.
1. req.body에서 comment, parentCommentId를 받아온다.
parentCommentId는 참조하는 CommentId 번호를 받아오는 형태로 구현하였다.(DB 상으로 참조하는 것은 아니다.)
2. parentCommentId를 받아오는 값에 따라
2.1 null일 경우 ( 대댓글 X ) -> parentCommentId는 생성되는 자기자신이 된다.
2.2 null이 아닐 경우 ( 대댓글 ) -> parentCommentId는 참조하게 되는 CommentId를 가리킨다.
.../src/services/comments.service.js
// ...
createComment = async(userId, pinId, comment, parentCommentId, like) => {
// 2.1
if(parentCommentId === null) {
const commentNum = await this.commentRepository.findCommentNum();
parentCommentId = commentNum + 1;
}
await this.commentRepository.createComment(
userId, pinId, comment, parentCommentId, like
);
}
2.1 의 경우 Comment의 DB의 제일 마지막 Number를 구해서 +1 을 하고 생성을 진행한다.
.../src/repositories/comments.repository.js
findCommentNum = async() => {
const findAllComment = await Comments.max('commentId');
console.log(findAllComment);
return findAllComment
}
sequelize의 method max는 가장 큰 commentId를 반환하는데, 이것은 가장 최근에 생성된 comment의 ID이다. 최대값에 +1을 하여 생성될 commentId를 지정한다.
2. Thunder Client로 본 예시

댓글 테스트1 은 commentId가 25이고, 이것은 parentCommentId와 같으므로 자기 자신을 가리킨다.
댓글 테스트 1-1과 1-2는 parentCommentId가 25이므로, 댓글 테스트1의 대댓글임을 보여준다.
'프로젝트 > 7주차 클론 코딩' 카테고리의 다른 글
| 2. 핀 검색하기 기능 구현 (0) | 2023.01.06 |
|---|---|
| 1. 카카오 Oauth 구현(백엔드) (0) | 2023.01.06 |
| 목차) 소개 (0) | 2023.01.06 |
| 7주차 클론 코딩 핀터레스트 (0) | 2023.01.06 |