28-interceptor
1. Interceptor 소개

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

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
1import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common'2import { Observable } from 'rxjs'3import { tap } from 'rxjs/operators'45@Injectable()6export class LoggingInterceptor implements NestInterceptor {7intercept(context: ExecutionContext, next: CallHandler): Observable<any> {8console.log('Before...')910const now = Date.now()11return next12.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
1import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common'2import { Observable, tap } from 'rxjs'34@Injectable()5export class LogInterceptor implements NestInterceptor {6intercept(context: ExecutionContext, next: CallHandler<any>): Observable<any> {7/**8* 요청이 들어올때 REQ 요청이 들어온 타임스탬프를 찍는다.9* [REQ] {요청 path} {요청 시간}10*11* 요청이 끝날때 (응답이 나갈때) 다시 타임스탬프를 찍는다.12* [RES] {요청 path} {응답 시간} {얼마나 걸렸는지 ms}13*/14const now = new Date()1516const req = context.switchToHttp().getRequest()1718/***19* /posts20* /common/image21*/22const path = req.originalUrl2324// [REQ] {요청 path} {요청 시간}25console.log(`[REQ] ${path} ${now.toLocaleString('kr')}`)2627/***28* return next.handle()을 실행하는 순간29* 라우트의 로직이 전부 실행되고 응답이 반환된다.30* observable로31*/32return next.handle().pipe(33tap(34// [RES] {요청 path} {응답 시간} {얼마나 걸렸는지 ms}35observable =>36console.log(37`[RES] ${path} ${new Date().toLocaleString('kr')} ${38new Date().getMilliseconds() - now.getMilliseconds()39}ms`,40),41),42)43}44}
그리고 posts 컨트롤러에 위에 작성한 Interceptor를 추가해준다.
posts.controller.ts
1// posts.controller.ts 생략2/*** 1) GET /posts3* 모든 post를 다 가져온다4*/5@Get()6@UseInterceptors(LogInterceptor)7getPosts(@Query() query: PaginatePostDto) {8return this.postsService.paginatePosts(query)9}
2.1 RxJS
- https://rxjs.dev/guide/operators#creation-operators-1
- Interceptor에 대해서 더 깊게 알기 위해서 RxJS의 공식문서에서 API들을 찾아서 공부하면 된다.
3. Transaction Interceptor 생성
common/interceptor/transaction.interceptor 파일을 만든다.
common/interceptor/transaction.interceptor
1import {2CallHandler,3ExecutionContext,4Injectable,5InternalServerErrorException,6NestInterceptor,7} from '@nestjs/common'8import { Observable, catchError, tap } from 'rxjs'9import { DataSource } from 'typeorm'1011@Injectable()12export class TransactionInterceptor implements NestInterceptor {13constructor(private readonly dataSource: DataSource) {}1415async intercept(context: ExecutionContext, next: CallHandler<any>): Promise<Observable<any>> {16const req = context.switchToHttp().getRequest()1718// 트랜잭션과 관련되 모든 쿼리를 담당할 쿼리 러너를 생성한다.19const qr = this.dataSource.createQueryRunner()2021// 쿼리 러너에 연결한다.22await qr.connect()2324/*** 쿼리 러너에서 트랜잭션을 시작한다.25* 이 시점부터 같은 쿼리 러너를 사용하면, 트랜잭션 안에서 데이터베이스 액션을 실행 할 수 있다.26*/27await qr.startTransaction()2829req.queryRunner = qr3031return next.handle().pipe(32catchError(async e => {33await qr.rollbackTransaction()34await qr.release()3536throw new InternalServerErrorException(e.message)37}),38tap(async () => {39await qr.commitTransaction()40await qr.release()41}),42)43}44}
4. QueryRunner 커스텀 데코레이터 생성 & Transaction Interceptor 적용
common/decorator/query-runner.decorator.ts 파일을 만든다.
common/decorator/query-runner.decorator.ts
1import { ExecutionContext, InternalServerErrorException, createParamDecorator } from '@nestjs/common'23export const QueryRunner = createParamDecorator((data, context: ExecutionContext) => {4const req = context.switchToHttp().getRequest()56if (!req.queryRunner) {7throw new InternalServerErrorException(8`QueryRunner Decorator를 사용하려면 TransactionInterceptor를 적용해야 합니다.`,9)10}1112return req.queryRunner13})
posts 컨트롤러에 Transaction Interceptor을 적용한다.
posts.controller.ts
1// 생략2import { DataSource, QueryRunner as QR } from 'typeorm'3import { TransactionInterceptor } from 'src/common/interceptor/transaction.interceptor'4import { QueryRunner } from 'src/common/decorator/query-runner.decorator'56// 생략7@Post()8@UseGuards(AccessTokenGuard)9@UseInterceptors(TransactionInterceptor)10async 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) {17const post = await this.postsService.createPost(userId, body, qr)1819for (let i = 0; i < body.images.length; i++) {20await this.postsImagesService.createPostImage(21{22post,23order: i,24path: body.images[i],25type: ImageModelType.POST_IMAGE,26},27qr,28)29}30return this.postsService.getPostById(post.id, qr)31}
posts 서비스에 qr 파라미터를 넣어 수정한다.
posts.service.ts
1// posts.service.ts 생략2// **** 6) ID별 포스트 가져오기3async getPostById(id: number, qr?: QueryRunner) {4const repository = this.getRepository(qr)5const post = await repository.findOne({6...DEFAULT_POST_FIND_OPTIONS,7// PostsModel의 id가 입력받은 id와 같은지 필터링8where: {9id,10},11})12if (!post) {13throw new NotFoundException()14}15return post16}