개발일지
[NestJS] 댓글 작성 구현 본문
요구사항
- 댓글
- 댓글을 작성할 수 있습니다.
- 댓글에 좋아요를 누를 수 있습니다.
대댓글 작성
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,
},
});
}
}
'NestJS, Node.js > #01 Project - 투표 커뮤니티' 카테고리의 다른 글
[NestJS] 댓글 조회, 수정, 삭제 구현 (0) | 2022.11.09 |
---|---|
[NestJS] 댓글 좋아요 및 취소 (0) | 2022.11.09 |
[NestJS] 투표 글 수정 및 삭제 구현 - Utility Types (0) | 2022.11.09 |
[NestJS] 투표 글 조회 구현 (0) | 2022.11.07 |
[NestJS] 투표 글 좋아요 및 취소 구현 (0) | 2022.11.07 |