Skip to Content
BackendNestJs28-interceptor

1. Interceptor 소개

nestjs-request-life-cycle

  • 그림의 잘 보면 Interceptor가 요청할 때도 있고, 응답할 때도 2개가 있다.
  • 즉, Interceptor를 사용하면, 요청을 변경할 수도 있고, 응답을 변경할 수도 있다.

Interceptors_1

Interceptor 란?

  • 인터셉터는 @Injectable() 데코레이터로 주석이 달린 클래스다.
  • NestInterceptor 인터페이스를 상속(implements)받는다.
  • NestJS에서 유일하게 요청이 들어올 때 그리고 응답이 나갈 때 모두 로직을 실행 할 수 있는 미들웨어다
  • 추가적으로 1개의 Interceptor로 요청과 변경을 모두 제어할 수 있다.
  • 공식문서 : https://docs.nestjs.com/interceptors 

Interceptors에는 AOP(Aspect Oriented Programming ) 기술에서 영감을 받은 일련의 유용한 기능이 있습니다. 이를 통해 다음을 수행할 수 있습니다.

  • 메서드를 실행하기 전, 후에 추가 로직을 작성할 수 있다. (bind extra logic)
  • 함수에서 반환된 결과를 변형할 수 있다.
  • 함수에서 던진 에러를 변형할 수 있다.
  • 기본으로 작성한 함수 로직에다 추가 기능을 넣을 수 있다.
    • (extend the basic function behavior)
  • 어떤 함수의 기능을 완전히 오버라이드 할 수 있다. (e.g. 캐싱 목적으로)

결론은 Interceptor는 요청과 응답을 모두 핸들링할 수 있기에, 원한다면 Interceptor를 적용한 함수의 모든 전체 기능을 다 변경을 할 수도 있다.

Interceptor Response 핸들링은 기본적으로 RxJS를 사용한다


1.1 Interceptor 구현방법

typescript
1
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common'
2
import { Observable } from 'rxjs'
3
import { tap } from 'rxjs/operators'
4
5
@Injectable()
6
export class LoggingInterceptor implements NestInterceptor {
7
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
8
console.log('Before...')
9
10
const now = Date.now()
11
return next
12
.handle() //
13
.pipe(tap(() => console.log(`After... ${Date.now() - now}ms`)))
14
}
15
}

2. Interceptor를 이용해 로거 구현

common/interceptor/log.interceptor.ts 파일을 만든다.

common/interceptor/log.interceptor.ts
1
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common'
2
import { Observable, tap } from 'rxjs'
3
4
@Injectable()
5
export class LogInterceptor implements NestInterceptor {
6
intercept(context: ExecutionContext, next: CallHandler<any>): Observable<any> {
7
/**
8
* 요청이 들어올때 REQ 요청이 들어온 타임스탬프를 찍는다.
9
* [REQ] {요청 path} {요청 시간}
10
*
11
* 요청이 끝날때 (응답이 나갈때) 다시 타임스탬프를 찍는다.
12
* [RES] {요청 path} {응답 시간} {얼마나 걸렸는지 ms}
13
*/
14
const now = new Date()
15
16
const req = context.switchToHttp().getRequest()
17
18
/***
19
* /posts
20
* /common/image
21
*/
22
const path = req.originalUrl
23
24
// [REQ] {요청 path} {요청 시간}
25
console.log(`[REQ] ${path} ${now.toLocaleString('kr')}`)
26
27
/***
28
* return next.handle()을 실행하는 순간
29
* 라우트의 로직이 전부 실행되고 응답이 반환된다.
30
* observable로
31
*/
32
return next.handle().pipe(
33
tap(
34
// [RES] {요청 path} {응답 시간} {얼마나 걸렸는지 ms}
35
observable =>
36
console.log(
37
`[RES] ${path} ${new Date().toLocaleString('kr')} ${
38
new Date().getMilliseconds() - now.getMilliseconds()
39
}ms`,
40
),
41
),
42
)
43
}
44
}

그리고 posts 컨트롤러에 위에 작성한 Interceptor를 추가해준다.

posts.controller.ts
1
// posts.controller.ts 생략
2
/*** 1) GET /posts
3
* 모든 post를 다 가져온다
4
*/
5
@Get()
6
@UseInterceptors(LogInterceptor)
7
getPosts(@Query() query: PaginatePostDto) {
8
return this.postsService.paginatePosts(query)
9
}

2.1 RxJS


3. Transaction Interceptor 생성

common/interceptor/transaction.interceptor 파일을 만든다.

common/interceptor/transaction.interceptor
1
import {
2
CallHandler,
3
ExecutionContext,
4
Injectable,
5
InternalServerErrorException,
6
NestInterceptor,
7
} from '@nestjs/common'
8
import { Observable, catchError, tap } from 'rxjs'
9
import { DataSource } from 'typeorm'
10
11
@Injectable()
12
export class TransactionInterceptor implements NestInterceptor {
13
constructor(private readonly dataSource: DataSource) {}
14
15
async intercept(context: ExecutionContext, next: CallHandler<any>): Promise<Observable<any>> {
16
const req = context.switchToHttp().getRequest()
17
18
// 트랜잭션과 관련되 모든 쿼리를 담당할 쿼리 러너를 생성한다.
19
const qr = this.dataSource.createQueryRunner()
20
21
// 쿼리 러너에 연결한다.
22
await qr.connect()
23
24
/*** 쿼리 러너에서 트랜잭션을 시작한다.
25
* 이 시점부터 같은 쿼리 러너를 사용하면, 트랜잭션 안에서 데이터베이스 액션을 실행 할 수 있다.
26
*/
27
await qr.startTransaction()
28
29
req.queryRunner = qr
30
31
return next.handle().pipe(
32
catchError(async e => {
33
await qr.rollbackTransaction()
34
await qr.release()
35
36
throw new InternalServerErrorException(e.message)
37
}),
38
tap(async () => {
39
await qr.commitTransaction()
40
await qr.release()
41
}),
42
)
43
}
44
}

4. QueryRunner 커스텀 데코레이터 생성 & Transaction Interceptor 적용

common/decorator/query-runner.decorator.ts 파일을 만든다.

common/decorator/query-runner.decorator.ts
1
import { ExecutionContext, InternalServerErrorException, createParamDecorator } from '@nestjs/common'
2
3
export const QueryRunner = createParamDecorator((data, context: ExecutionContext) => {
4
const req = context.switchToHttp().getRequest()
5
6
if (!req.queryRunner) {
7
throw new InternalServerErrorException(
8
`QueryRunner Decorator를 사용하려면 TransactionInterceptor를 적용해야 합니다.`,
9
)
10
}
11
12
return req.queryRunner
13
})

posts 컨트롤러에 Transaction Interceptor을 적용한다.

posts.controller.ts
1
// 생략
2
import { DataSource, QueryRunner as QR } from 'typeorm'
3
import { TransactionInterceptor } from 'src/common/interceptor/transaction.interceptor'
4
import { QueryRunner } from 'src/common/decorator/query-runner.decorator'
5
6
// 생략
7
@Post()
8
@UseGuards(AccessTokenGuard)
9
@UseInterceptors(TransactionInterceptor)
10
async postPosts(
11
@User('id') userId: number, //
12
@Body() body: CreatePostDto,
13
@QueryRunner() qr: QR,
14
// 기본값을 true로 설정하는 파이프
15
// @Body('isPublic', new DefaultValuePipe(true)) isPublic: boolean,
16
) {
17
const post = await this.postsService.createPost(userId, body, qr)
18
19
for (let i = 0; i < body.images.length; i++) {
20
await this.postsImagesService.createPostImage(
21
{
22
post,
23
order: i,
24
path: body.images[i],
25
type: ImageModelType.POST_IMAGE,
26
},
27
qr,
28
)
29
}
30
return this.postsService.getPostById(post.id, qr)
31
}

posts 서비스에 qr 파라미터를 넣어 수정한다.

posts.service.ts
1
// posts.service.ts 생략
2
// **** 6) ID별 포스트 가져오기
3
async getPostById(id: number, qr?: QueryRunner) {
4
const repository = this.getRepository(qr)
5
const post = await repository.findOne({
6
...DEFAULT_POST_FIND_OPTIONS,
7
// PostsModel의 id가 입력받은 id와 같은지 필터링
8
where: {
9
id,
10
},
11
})
12
if (!post) {
13
throw new NotFoundException()
14
}
15
return post
16
}