개발일지

[NestJS] 댓글 좋아요 및 취소 본문

NestJS, Node.js/#01 Project - 투표 커뮤니티

[NestJS] 댓글 좋아요 및 취소

lyjin 2022. 11. 9.

앞서 했었던 투표 글 좋아요 및 취소 구현과 구현 방식이 같으므로 설명은 생략하겠습니다.

 

modeling

model VoteComments {
    id         Int      @id @default(autoincrement())
    likedUsers Users[]  @relation("LikedVoteUsers")
    ...
}

model Users {
    id                  Int            @id @default(autoincrement())
    likedVoteComments   VoteComments[] @relation("LikedVoteCommentUsers")
}

 

controller

  @Post(':commentId/like')
  async likeVoteComment(@Param('commentId', ParseIntPipe) commentId: number) {
    const userId = 1;

    const data: LikesVoteCommentDto = {
      commentId,
      userId,
    };

    await this.commentsService.likeVoteComment(data);
  }

  @Post(':commentId/cancle/likes')
  async cancleLikedVoteComment(
    @Param('voteId', ParseIntPipe) commentId: number,
  ) {
    const userId = 1;

    const data: LikesVoteCommentDto = {
      commentId,
      userId,
    };

    await this.commentsService.cancleLikedVoteComment(data);
  }

 

service

  async likeVoteComment(data: LikesVoteCommentDto) {
    await this.commentsRepository.createLikedUser(data);
  }

  async cancleLikedVoteComment(data: LikesVoteCommentDto) {
    await this.commentsRepository.deleteLikedUser(data);
  }

 

repository

  async createLikedUser(data: LikesVoteCommentDto) {
    return await this.prisma.voteComments.update({
      where: {
        id: data.commentId,
      },
      data: {
        likedUsers: {
          connect: {
            id: data.userId,
          },
        },
      },
    });
  }

  async deleteLikedUser(data: LikesVoteCommentDto) {
    return await this.prisma.voteComments.update({
      where: {
        id: data.commentId,
      },
      data: {
        likedUsers: {
          disconnect: {
            id: data.userId,
          },
        },
      },
    });
  }