개발일지

[NestJS] 댓글 작성 구현 본문

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

[NestJS] 댓글 작성 구현

lyjin 2022. 11. 9.

요구사항

  • 댓글
    • 댓글을 작성할 수 있습니다.
    • 댓글에 좋아요를 누를 수 있습니다.
    • 대댓글 작성

 

modeling

Users와 1:N, Votes와 1:N 관계를 가집니다.

 

model VoteComments {
    id         Int      @id @default(autoincrement())
    content    String
    writer     Users    @relation("VoteCommentWriter", fields: [writerId], references: [id])
    writerId   Int
    vote       Votes    @relation(fields: [voteId], references: [id])
    voteId     Int
    createdAt  DateTime @default(now())
    updatedAt  DateTime @updatedAt

    @@map("vote-comments")
}

model Votes {
    id         Int      @id @default(autoincrement())
    VoteComments VoteComments[]
    ...
}

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

 

 


댓글 작성

댓글 관련 라우터들만 관리하는 CommentsController 를 생성했습니다. 마찬가지로 CommentsService, CommentsRepository 클래스를 따로 생성했습니다.

 

// votes/votes.controller.ts

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

  @Post()
  async createVoteComment(
    @Param('voteId', ParseIntPipe) voteId: number,
    @Body('content') content: string,
  ) {
    const userId = 1; //임시

    const data: CreateVoteCommentDto = {
      voteId,
      userId,
      content,
    };

    return await this.commentsService.createVoteComment(data);
  }
}

 

export class CreateVoteCommentDto {
  voteId: number;
  userId: number;
  content: string;
}

 

 

votes/votes.service.ts

댓글 내용이 비었을 경우 에러를 반환합니다.

 

@Injectable()
export class CommentsService {
  constructor(private readonly commentsRepository: CommentsRepository) {}

  async createVoteComment(data: CreateVoteCommentDto) {
    if (data.content === '') {
      throw new CustomException(VotesException.EMPTY_COMMENT_CONTENT);
    }
    return await this.commentsRepository.createVoteComment(data);
  }
}

 

 

votes/votes.repository.ts

@Injectable()
export class CommentsRepository {
  private readonly prisma = new PrismaClient();

  async createVoteComment(data: CreateVoteCommentDto) {
    return await this.prisma.voteComments.create({
      data: {
        content: data.content,
        voteId: data.voteId,
        writerId: data.userId,
      },
    });
  }
}