개발일지

[NestJS] 댓글 조회, 수정, 삭제 구현 본문

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

[NestJS] 댓글 조회, 수정, 삭제 구현

lyjin 2022. 11. 9.

댓글 목록 조회

투표 글을 클릭하면 그 투표글에 대한 댓글 목록을 불러올 수 있어야합니다. @Param()으로 해당 투표 글의 id를 받아옵니다.

 

// votes/votes.controller.ts

@Controller('votes/:voteId/comments')
export class CommentsController {
  constructor(
    private readonly commentsRepository: CommentsRepository,
  ) {}

  @Get()
  async getVoteComments(@Param('voteId', ParseIntPipe) voteId: number) {
    return await this.commentsRepository.getAllVoteComments(voteId);
  }
}

 

repository

_count 를 사용해 좋아요 수를 포함하여 보여줍니다.

 

  async getAllVoteComments(voteId: number): Promise<VoteComments[]> {
    return await this.prisma.voteComments.findMany({
      where: {
        voteId,
      },
      include: {
        _count: {
          select: {
            likedUsers: true,
          },
        },
      },
    });
  }

 


댓글 수정

투표 글 수정할 때와 마찬가지로 유틸리티 타입으로 dto를 정의하고 서비스를 정의해줍니다.

 

// votes/votes.controller.ts

@Patch(':commentId')
async updateVoteComment(
    @Param('commentId', ParseIntPipe) commentId: number,
    @Body() body: Omit<UpdateVoteCommentDto, 'commentId'>,
  ) {
  const data: UpdateVoteCommentDto = {
    ...body,
    commentId,
  };

  return { comments: await this.commentsService.updateVoteComment(data) };
}

 

export class UpdateVoteCommentDto extends PartialType(
  OmitType(CreateVoteCommentDto, ['userId', 'voteId']),
) {
  commentId: number;
}

 

댓글 편집 여부 표시하기

수정된 댓글일 경우 (편집됨) 과 같이 편집 여부를 함께 나타내고싶었습니다. VoteComments에 boolean 타입의 isUpdated 필드를 추가해줬습니다.

 

model VoteComments {
    id         Int      @id @default(autoincrement())
    isUpdated  Boolean  @default(false)
    ...
}

 

 

댓글이 수정될 때 수정될 content와 함께 isUpdated를 true로 변경해줍니다. 클라이언트에서는 isUpdated == true 인 경우에만 해당 글귀를 보여줍니다.

 

async updateVoteComment(dto: UpdateVoteCommentDto) {
  const { commentId, content } = dto;

  return await this.prisma.voteComments.update({
    where: {
      id: commentId,
    },
    data: {
      content,
      isUpdated: true,
    },
  });
}

 


댓글 삭제

// votes/votes.controller.ts

@Delete(':commentId')
async deleteVoteComment(@Param('commentId', ParseIntPipe) commentId: number) {
  return await this.commentsRepository.deleteVoteComment(commentId);
}

 

// votes/votes.repository.ts

async deleteVoteComment(commentId: number) {
  return await this.prisma.voteComments.delete({
    where: {
      id: commentId,
    },
  });
}