Skip to Content
BackendNestJs33-module-nesting

1. 섹션 소개 및 작업 인스트럭션

shellscript
1
nest g resource
2
? comments
3
? REST API
4
? No

comments 폴더가 생기면, 이 폴더 통째로 posts 폴더 안으로 이동시켜 하위 모듈로 만든다.

comments 컨트롤러를 다음과 같이 수정한다.

comments.controller.ts
1
/** 1) Entity 생성
2
* author -> 작성자
3
* post -> 귀속되는 포스트
4
* comment -> 실제 댓글 내용
5
* likeCount -> 좋아요 갯수
6
*
7
* id -> PrimaryGeneratedColumn
8
* createdAt -> 생성일자
9
* updatedAt -> 업데이트일자
10
*
11
* 2) GET() pagination
12
* 3) GET(':commentId') 특정 comment만 하나 가져오는 기능
13
* 4) POST() 코멘트 생성하는 기능
14
* 5) PATCH(':commentId') 특정 comment 업데이트 하는 기능
15
* 6) DELETE(':commentId') 특정 comment 삭제하는 기능
16
*/
17
@Controller('posts/:postId/comments')
18
export class CommentsController {
19
constructor(
20
private readonly commentsService: CommentsService, //
21
) {}
22
}

2. Comments Entity 생성

posts/comments/entity/comments.entity.ts 파일을 만든다.

comments.entity.ts
1
import { IsNumber, IsString } from 'class-validator'
2
3
import { BaseModel } from 'src/common/entity/base.entity'
4
import { PostsModel } from 'src/posts/entity/posts.entity'
5
import { UsersModel } from 'src/users/entity/users.entity'
6
import { Column, Entity, ManyToOne } from 'typeorm'
7
8
@Entity()
9
export class CommentsModel extends BaseModel {
10
@ManyToOne(() => UsersModel, user => user.postComments)
11
author: UsersModel
12
13
@ManyToOne(() => PostsModel, post => post.comments)
14
post: PostsModel
15
16
@Column()
17
@IsString()
18
comment: string
19
20
@Column({
21
default: 0,
22
})
23
@IsNumber()
24
likeCount: number
25
}

users 모델에 postComments 컬럼을 추가한다.

users.entity.ts
1
// users.entity.ts 생략
2
@OneToMany(() => CommentsModel, comment => comment.author)
3
postComments: CommentsModel[]

post 모델에 comments 컬럼을 추가한다.

posts.entity.ts
1
// posts.entity.ts 생략
2
@OneToMany(() => CommentsModel, comment => comment.post)
3
comments: CommentsModel[]

app 모듈에서 CommentsModel를 추가한다.

app.module.ts
1
@Module({
2
imports: [
3
// 생략
4
TypeOrmModule.forRoot({
5
// 생략
6
entities: [
7
PostsModel, //
8
UsersModel,
9
ImageModel,
10
ChatsModel,
11
MessagesModel,
12
CommentsModel, // 추가
13
],
14
synchronize: true,
15
}),
16
// 생략
17
],
18
// 생략
19
})

그리고 comments 모듈에서도 사용할 수 있게 추가해준다.

comments.module.ts
1
@Module({
2
imports: [
3
TypeOrmModule.forFeature([CommentsModel]), //
4
],
5
controllers: [CommentsController],
6
providers: [CommentsService],
7
})

3. Paginate Comments API

posts/comments/dto/paginate-comments.dto.ts 파일을 만든다.

posts/comments/dto/paginate-comments.dto.ts
1
import { BasePaginationDto } from 'src/common/dto/base-pagination.dto'
2
3
export class PaginateCommentsDto extends BasePaginationDto {}

comments.controller.ts에 댓글 페이지네이션 엔드포인트를 추가한다.

comments.controller.ts
1
// **** (1) 댓글 페이지네이션
2
@Get()
3
@IsPublic()
4
getComments(
5
@Param('postId', ParseIntPipe) postId: number, //
6
@Query() query: PaginateCommentsDto,
7
) {
8
return this.commentsService.paginteComments(query, postId)
9
}

comments 모듈에서 CommonModule을 사용할 수 있게 추가해준다.

comments.module.ts
1
@Module({
2
imports: [
3
TypeOrmModule.forFeature([CommentsModel]), //
4
CommonModule,
5
],
6
controllers: [CommentsController],
7
providers: [CommentsService],
8
})

comments 서비스에 페이지네이션 기능을 추가한다.

comments.service.ts
1
@Injectable()
2
export class CommentsService {
3
constructor(
4
@InjectRepository(CommentsModel)
5
private readonly commentsRepository: Repository<CommentsModel>,
6
private readonly commonService: CommonService,
7
) {}
8
9
paginteComments(dto: PaginateCommentsDto, postId: number) {
10
return this.commonService.paginate(
11
dto,
12
this.commentsRepository,
13
{ where: { post: { id: postId } } },
14
`posts/${postId}/comments`,
15
)
16
}
17
}

4. ID 기반으로 하나의 Comments 가져오는 API 작성

ID를 기반으로 특정 댓글 1개만 가져오기 위해 comments 컨트롤러에 엔드포인트를 추가한다.

comments.controller.ts
1
// **** (2) 특정 댓글 1개만 가져오기
2
@Get(':commentId')
3
@IsPublic()
4
getComment(@Param('commentId', ParseIntPipe) commentId: number) {
5
return this.commentsService.getCommentById(commentId)
6
}

comments 서비스에 기능을 추가한다.

comments.service.ts
1
// **** (2) 특정 댓글 1개만 가져오기
2
async getCommentById(id: number) {
3
const comment = await this.commentsRepository.findOne({
4
...DEFAULT_COMMENT_FIND_OPTIONS,
5
where: { id },
6
})
7
8
if (!comment) {
9
throw new BadRequestException(`id: ${id} Comment는 존재하지 않습니다.`)
10
}
11
12
return comment
13
}

5. Comment 생성 API

댓글 생성 DTO를 위해 comments/dto/create-comments.dto.ts 파일을 만든다.

create-comments.dto.ts
1
import { PickType } from '@nestjs/mapped-types'
2
import { CommentsModel } from '../entity/comments.entity'
3
4
export class CreateCommentsDto extends PickType(CommentsModel, ['comment']) {}

댓글 생성하기 위해 comments 컨트롤러에 엔드포인트를 추가한다.

comments.controller.ts
1
// **** (3) 댓글 생성
2
@Post()
3
@UseInterceptors(TransactionInterceptor)
4
async postComment(
5
@Param('postId', ParseIntPipe) postId: number,
6
@Body() body: CreateCommentsDto,
7
@User() user: UsersModel,
8
@QueryRunner() qr: QR,
9
) {
10
const resp = await this.commentsService.createComment(body, postId, user, qr)
11
12
await this.postsService.incrementCommentCount(postId, qr)
13
14
return resp
15
}

comments 모듈에서 AuthModule, UsersModule을 사용할 수 있게 추가해준다.

comments.module.ts
1
@Module({
2
imports: [
3
TypeOrmModule.forFeature([CommentsModel]), //
4
CommonModule,
5
AuthModule,
6
UsersModule,
7
],
8
controllers: [CommentsController],
9
providers: [CommentsService],
10
})

comments 서비스에 기능을 추가한다.

comments.service.ts
1
// **** (3) 댓글 생성
2
async createComment(
3
dto: CreateCommentsDto, //
4
postId: number,
5
author: UsersModel,
6
qr?: QueryRunner,
7
) {
8
const repository = this.getRepository(qr)
9
10
return repository.save({
11
...dto,
12
post: { id: postId },
13
author,
14
})
15
}

comments/const/default-comment-find-options.const.ts 파일을 만든다.

comments/const/default-comment-find-options.const.ts
1
import { FindManyOptions } from 'typeorm'
2
import { CommentsModel } from '../entity/comments.entity'
3
4
export const DEFAULT_COMMENT_FIND_OPTIONS: FindManyOptions<CommentsModel> = {
5
relations: {
6
author: true,
7
},
8
select: {
9
author: {
10
id: true,
11
nickname: true,
12
},
13
},
14
}

6. Patch Comment API

댓글 생성 DTO를 위해 comments/dto/update-comments.dto.ts 파일을 만든다.

update-comments.dto.ts
1
import { PartialType } from '@nestjs/mapped-types'
2
import { CreateCommentsDto } from './create-comments.dto'
3
4
export class UpdateCommentsDto extends PartialType(CreateCommentsDto) {}

댓글 수정하기 위해 comments 컨트롤러에 엔드포인트를 추가한다.

comments.controller.ts
1
// **** (4) 댓글 수정
2
@Patch(':commentId')
3
@UseGuards(IsCommentMineOrAdminGuard)
4
async patchComment(
5
@Param('commentId', ParseIntPipe) commentId: number, //
6
@Body() body: UpdateCommentsDto,
7
) {
8
return this.commentsService.updateComment(body, commentId)
9
}

comments 서비스에 기능을 추가한다.

comments.service.ts
1
// **** (4) 댓글 수정
2
async updateComment(dto: UpdateCommentsDto, commentId: number) {
3
const comment = await this.commentsRepository.findOne({
4
where: {
5
id: commentId,
6
},
7
})
8
9
if (!comment) {
10
throw new BadRequestException('존재하지 않는 댓글입니다.')
11
}
12
13
const prevComment = await this.commentsRepository.preload({
14
id: commentId,
15
...dto,
16
})
17
18
const newComment = await this.commentsRepository.save(prevComment)
19
20
return newComment
21
}

7. Delete Comment API

댓글 삭제를 위해 comments 컨트롤러에 엔드포인트를 추가한다.

comments.controller.ts
1
// **** (5) 댓글 삭제
2
@Delete(':commentId')
3
@UseGuards(IsCommentMineOrAdminGuard)
4
@UseInterceptors(TransactionInterceptor)
5
async deleteComment(
6
@Param('commentId', ParseIntPipe) commentId: number, //
7
@Param('postId', ParseIntPipe) postId: number,
8
@QueryRunner() qr: QR,
9
) {
10
const resp = await this.commentsService.deleteComment(commentId, qr)
11
12
await this.postsService.decrementCommentCount(postId, qr)
13
14
return resp
15
}

comments 서비스에 기능을 추가한다.

comments.service.ts
1
// **** (5) 댓글 삭제
2
async deleteComment(id: number, qr?: QueryRunner) {
3
const repository = this.getRepository(qr)
4
5
const comment = await repository.findOne({
6
where: { id },
7
})
8
9
if (!comment) {
10
throw new BadRequestException('존재하지 않는 댓글입니다.')
11
}
12
13
await repository.delete(id)
14
15
return id
16
}

8. Path Parameter 검증하는 Middleware 생성

comment 컨트롤러 안에 있는 :postId패스 파라미터가 유효한지 확인하는 미들웨어를 만든다.

posts.service에 id를 갖고있는 post가 존재하는지 확인하는 기능을 추가한다.

posts.service.ts
1
// **** 이 id를 가진 post가 존재하는지 확인
2
async checkPostExistsById(id: number) {
3
return this.postsRepository.exist({
4
where: { id },
5
})
6
}

comments/middleware/post-exists.middleware.ts 파일을 만든다.

comments/middleware/post-exists.middleware.ts
1
import { BadRequestException, Injectable, NestMiddleware } from '@nestjs/common'
2
import { NextFunction, Request, Response } from 'express'
3
import { PostsService } from 'src/posts/posts.service'
4
5
@Injectable()
6
export class PostExistsMiddelware implements NestMiddleware {
7
constructor(private readonly postService: PostsService) {}
8
9
async use(req: Request, res: Response, next: NextFunction) {
10
const postId = req.params.postId
11
12
if (!postId) {
13
throw new BadRequestException('Post ID 파라미터는 필수입니다.')
14
}
15
16
const exists = await this.postService.checkPostExistsById(parseInt(postId))
17
18
if (!exists) {
19
throw new BadRequestException('Post가 존재하지 않습니다.')
20
}
21
22
next() // 다음 로직을 실행
23
}
24
}

9. PostExists Middleware CommentsController에 적용

등록하려는 모듈(comments)에 PostExists Middleware를 적용시킬 것이다.

comments.module.ts
1
@Module({
2
imports: [
3
TypeOrmModule.forFeature([CommentsModel]), //
4
CommonModule,
5
AuthModule,
6
UsersModule,
7
PostsModule,
8
],
9
controllers: [CommentsController],
10
providers: [CommentsService],
11
})
12
export class CommentsModule implements NestModule {
13
configure(consumer: MiddlewareConsumer) {
14
consumer.apply(PostExistsMiddelware).forRoutes(CommentsController)
15
}
16
}

그리고 posts 모듈을 export한다.

posts.module.ts
1
@Module({
2
// 생략
3
exports: [PostsService],
4
})
5
export class PostsModule {}