33-module-nesting
1. 섹션 소개 및 작업 인스트럭션
1nest g resource2? comments3? REST API4? No
comments 폴더가 생기면, 이 폴더 통째로 posts 폴더 안으로 이동시켜 하위 모듈로 만든다.
comments 컨트롤러를 다음과 같이 수정한다.
1/** 1) Entity 생성2* author -> 작성자3* post -> 귀속되는 포스트4* comment -> 실제 댓글 내용5* likeCount -> 좋아요 갯수6*7* id -> PrimaryGeneratedColumn8* createdAt -> 생성일자9* updatedAt -> 업데이트일자10*11* 2) GET() pagination12* 3) GET(':commentId') 특정 comment만 하나 가져오는 기능13* 4) POST() 코멘트 생성하는 기능14* 5) PATCH(':commentId') 특정 comment 업데이트 하는 기능15* 6) DELETE(':commentId') 특정 comment 삭제하는 기능16*/17@Controller('posts/:postId/comments')18export class CommentsController {19constructor(20private readonly commentsService: CommentsService, //21) {}22}
2. Comments Entity 생성
posts/comments/entity/comments.entity.ts 파일을 만든다.
1import { IsNumber, IsString } from 'class-validator'23import { BaseModel } from 'src/common/entity/base.entity'4import { PostsModel } from 'src/posts/entity/posts.entity'5import { UsersModel } from 'src/users/entity/users.entity'6import { Column, Entity, ManyToOne } from 'typeorm'78@Entity()9export class CommentsModel extends BaseModel {10@ManyToOne(() => UsersModel, user => user.postComments)11author: UsersModel1213@ManyToOne(() => PostsModel, post => post.comments)14post: PostsModel1516@Column()17@IsString()18comment: string1920@Column({21default: 0,22})23@IsNumber()24likeCount: number25}
users 모델에 postComments 컬럼을 추가한다.
1// users.entity.ts 생략2@OneToMany(() => CommentsModel, comment => comment.author)3postComments: CommentsModel[]
post 모델에 comments 컬럼을 추가한다.
1// posts.entity.ts 생략2@OneToMany(() => CommentsModel, comment => comment.post)3comments: CommentsModel[]
app 모듈에서 CommentsModel를 추가한다.
1@Module({2imports: [3// 생략4TypeOrmModule.forRoot({5// 생략6entities: [7PostsModel, //8UsersModel,9ImageModel,10ChatsModel,11MessagesModel,12CommentsModel, // 추가13],14synchronize: true,15}),16// 생략17],18// 생략19})
그리고 comments 모듈에서도 사용할 수 있게 추가해준다.
1@Module({2imports: [3TypeOrmModule.forFeature([CommentsModel]), //4],5controllers: [CommentsController],6providers: [CommentsService],7})
3. Paginate Comments API
posts/comments/dto/paginate-comments.dto.ts 파일을 만든다.
1import { BasePaginationDto } from 'src/common/dto/base-pagination.dto'23export class PaginateCommentsDto extends BasePaginationDto {}
comments.controller.ts에 댓글 페이지네이션 엔드포인트를 추가한다.
1// **** (1) 댓글 페이지네이션2@Get()3@IsPublic()4getComments(5@Param('postId', ParseIntPipe) postId: number, //6@Query() query: PaginateCommentsDto,7) {8return this.commentsService.paginteComments(query, postId)9}
comments 모듈에서 CommonModule을 사용할 수 있게 추가해준다.
1@Module({2imports: [3TypeOrmModule.forFeature([CommentsModel]), //4CommonModule,5],6controllers: [CommentsController],7providers: [CommentsService],8})
comments 서비스에 페이지네이션 기능을 추가한다.
1@Injectable()2export class CommentsService {3constructor(4@InjectRepository(CommentsModel)5private readonly commentsRepository: Repository<CommentsModel>,6private readonly commonService: CommonService,7) {}89paginteComments(dto: PaginateCommentsDto, postId: number) {10return this.commonService.paginate(11dto,12this.commentsRepository,13{ where: { post: { id: postId } } },14`posts/${postId}/comments`,15)16}17}
4. ID 기반으로 하나의 Comments 가져오는 API 작성
ID를 기반으로 특정 댓글 1개만 가져오기 위해 comments 컨트롤러에 엔드포인트를 추가한다.
1// **** (2) 특정 댓글 1개만 가져오기2@Get(':commentId')3@IsPublic()4getComment(@Param('commentId', ParseIntPipe) commentId: number) {5return this.commentsService.getCommentById(commentId)6}
comments 서비스에 기능을 추가한다.
1// **** (2) 특정 댓글 1개만 가져오기2async getCommentById(id: number) {3const comment = await this.commentsRepository.findOne({4...DEFAULT_COMMENT_FIND_OPTIONS,5where: { id },6})78if (!comment) {9throw new BadRequestException(`id: ${id} Comment는 존재하지 않습니다.`)10}1112return comment13}
5. Comment 생성 API
댓글 생성 DTO를 위해 comments/dto/create-comments.dto.ts 파일을 만든다.
1import { PickType } from '@nestjs/mapped-types'2import { CommentsModel } from '../entity/comments.entity'34export class CreateCommentsDto extends PickType(CommentsModel, ['comment']) {}
댓글 생성하기 위해 comments 컨트롤러에 엔드포인트를 추가한다.
1// **** (3) 댓글 생성2@Post()3@UseInterceptors(TransactionInterceptor)4async postComment(5@Param('postId', ParseIntPipe) postId: number,6@Body() body: CreateCommentsDto,7@User() user: UsersModel,8@QueryRunner() qr: QR,9) {10const resp = await this.commentsService.createComment(body, postId, user, qr)1112await this.postsService.incrementCommentCount(postId, qr)1314return resp15}
comments 모듈에서 AuthModule, UsersModule을 사용할 수 있게 추가해준다.
1@Module({2imports: [3TypeOrmModule.forFeature([CommentsModel]), //4CommonModule,5AuthModule,6UsersModule,7],8controllers: [CommentsController],9providers: [CommentsService],10})
comments 서비스에 기능을 추가한다.
1// **** (3) 댓글 생성2async createComment(3dto: CreateCommentsDto, //4postId: number,5author: UsersModel,6qr?: QueryRunner,7) {8const repository = this.getRepository(qr)910return repository.save({11...dto,12post: { id: postId },13author,14})15}
comments/const/default-comment-find-options.const.ts 파일을 만든다.
1import { FindManyOptions } from 'typeorm'2import { CommentsModel } from '../entity/comments.entity'34export const DEFAULT_COMMENT_FIND_OPTIONS: FindManyOptions<CommentsModel> = {5relations: {6author: true,7},8select: {9author: {10id: true,11nickname: true,12},13},14}
6. Patch Comment API
댓글 생성 DTO를 위해 comments/dto/update-comments.dto.ts 파일을 만든다.
1import { PartialType } from '@nestjs/mapped-types'2import { CreateCommentsDto } from './create-comments.dto'34export class UpdateCommentsDto extends PartialType(CreateCommentsDto) {}
댓글 수정하기 위해 comments 컨트롤러에 엔드포인트를 추가한다.
1// **** (4) 댓글 수정2@Patch(':commentId')3@UseGuards(IsCommentMineOrAdminGuard)4async patchComment(5@Param('commentId', ParseIntPipe) commentId: number, //6@Body() body: UpdateCommentsDto,7) {8return this.commentsService.updateComment(body, commentId)9}
comments 서비스에 기능을 추가한다.
1// **** (4) 댓글 수정2async updateComment(dto: UpdateCommentsDto, commentId: number) {3const comment = await this.commentsRepository.findOne({4where: {5id: commentId,6},7})89if (!comment) {10throw new BadRequestException('존재하지 않는 댓글입니다.')11}1213const prevComment = await this.commentsRepository.preload({14id: commentId,15...dto,16})1718const newComment = await this.commentsRepository.save(prevComment)1920return newComment21}
7. Delete Comment API
댓글 삭제를 위해 comments 컨트롤러에 엔드포인트를 추가한다.
1// **** (5) 댓글 삭제2@Delete(':commentId')3@UseGuards(IsCommentMineOrAdminGuard)4@UseInterceptors(TransactionInterceptor)5async deleteComment(6@Param('commentId', ParseIntPipe) commentId: number, //7@Param('postId', ParseIntPipe) postId: number,8@QueryRunner() qr: QR,9) {10const resp = await this.commentsService.deleteComment(commentId, qr)1112await this.postsService.decrementCommentCount(postId, qr)1314return resp15}
comments 서비스에 기능을 추가한다.
1// **** (5) 댓글 삭제2async deleteComment(id: number, qr?: QueryRunner) {3const repository = this.getRepository(qr)45const comment = await repository.findOne({6where: { id },7})89if (!comment) {10throw new BadRequestException('존재하지 않는 댓글입니다.')11}1213await repository.delete(id)1415return id16}
8. Path Parameter 검증하는 Middleware 생성
comment 컨트롤러 안에 있는 :postId패스 파라미터가 유효한지 확인하는 미들웨어를 만든다.
posts.service에 id를 갖고있는 post가 존재하는지 확인하는 기능을 추가한다.
1// **** 이 id를 가진 post가 존재하는지 확인2async checkPostExistsById(id: number) {3return this.postsRepository.exist({4where: { id },5})6}
comments/middleware/post-exists.middleware.ts 파일을 만든다.
1import { BadRequestException, Injectable, NestMiddleware } from '@nestjs/common'2import { NextFunction, Request, Response } from 'express'3import { PostsService } from 'src/posts/posts.service'45@Injectable()6export class PostExistsMiddelware implements NestMiddleware {7constructor(private readonly postService: PostsService) {}89async use(req: Request, res: Response, next: NextFunction) {10const postId = req.params.postId1112if (!postId) {13throw new BadRequestException('Post ID 파라미터는 필수입니다.')14}1516const exists = await this.postService.checkPostExistsById(parseInt(postId))1718if (!exists) {19throw new BadRequestException('Post가 존재하지 않습니다.')20}2122next() // 다음 로직을 실행23}24}
9. PostExists Middleware CommentsController에 적용
등록하려는 모듈(comments)에 PostExists Middleware를 적용시킬 것이다.
1@Module({2imports: [3TypeOrmModule.forFeature([CommentsModel]), //4CommonModule,5AuthModule,6UsersModule,7PostsModule,8],9controllers: [CommentsController],10providers: [CommentsService],11})12export class CommentsModule implements NestModule {13configure(consumer: MiddlewareConsumer) {14consumer.apply(PostExistsMiddelware).forRoutes(CommentsController)15}16}
그리고 posts 모듈을 export한다.
1@Module({2// 생략3exports: [PostsService],4})5export class PostsModule {}