본문 바로가기
NestJS

[NestJS] Interceptors

by NJ94 2023. 9. 9.

Spring AOP

 

AOP Aspect Oriented

핵심 로직과 부가 기능을 분리하여 애플리케이션 전체에 걸쳐 사용되는 부가 기능을 모듈화하여

재사용할 수 있도록 지원하는 것 (관점 지향 프로그래밍) 

 

Around -> Before -> After -> After Returing -> After Throwing

 

1. 선언적 트랜잭션 관리

 

https://docs.spring.io/spring-framework/reference/data-access/transaction/declarative.html

 

Declarative Transaction Management :: Spring Framework

The Spring Framework’s declarative transaction management is made possible with Spring aspect-oriented programming (AOP). However, as the transactional aspects code comes with the Spring Framework distribution and may be used in a boilerplate fashion, AO

docs.spring.io

 

2. AOP로 OOP 사용을 보완하여 사용자 정의 측면 구현 

 

https://docs.spring.io/spring-framework/reference/core/aop/introduction-defn.html

 

AOP Concepts :: Spring Framework

Let us begin by defining some central AOP concepts and terminology. These terms are not Spring-specific. Unfortunately, AOP terminology is not particularly intuitive. However, it would be even more confusing if Spring used its own terminology. Around advic

docs.spring.io

 


ExecutionContext

 

https://docs.nestjs.com/fundamentals/execution-context

 

Documentation | NestJS - A progressive Node.js framework

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Rea

docs.nestjs.com

: 실행 컨텍스트, Nest는 여러 애플리케이션 컨텍스트( ex) Nest HTTP 서버 기반, 마이크로서비스, WebSocket, 애플리케이션 컨텍스트)에서

작동하는 애플리케이션을 쉽게 작성하는 데 도움이 되는 여러 유틸리티 클래스를 제공한다

 

이러한 유틸리티는 광범위한 컨트롤러, 메서드 및 실행 컨텍스트 집합에서 작동할 수 있는 Guard, Filter, Interceptor 구축 하는데

사용할 수 있는 실행 컨텍스트에 대한 정보를 제공한다.

 

ArgumentsHost

: 핸들러에 전달되는 인수를 검색하기 위한 메서드를 제공.

 


😃 Interceptors

 

- 메소드 실행 전/후에 추가 로직 바인딩

- 함수에서 반환된 결과를 변환 

- 함수에서 발생한 예외 변환

- 기본 기능 동작 확장

- 특정조건(캐싱 목적)에 따라 기능 완전히 재정의

 

 

interceptor.controller.ts

import { Controller, Get, UseInterceptors } from "@nestjs/common";
import { LoggingInterceptor } from "src/common/interceptor/logging.interceptor";

@Controller("/interceptor/test")
export class InterceptorTestController {

    @UseInterceptors(LoggingInterceptor)
    @Get()
    findOne() {
        console.log('.....');
        return 'interceptor controller test..';        
    }
}

 

logging.intercetor.ts

import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from "@nestjs/common";
import { Observable } from "rxjs";
import { tap } from "rxjs/operators";

@Injectable()
export class LoggingInterceptor implements NestInterceptor{

    intercept(context: ExecutionContext, next: CallHandler<any>): Observable<any> | Promise<Observable<any>> {
        console.log('[Interceptor] Before...');

        const now = Date.now();

        return next
            .handle()
            .pipe(
                tap(() => console.log(`After... ${Date.now() - now}ms`)),
            );
    }
    
}

 

 

https://docs.nestjs.com/fundamentals/execution-context

 

Documentation | NestJS - A progressive Node.js framework

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Rea

docs.nestjs.com

 

 

 

 

 

 

 

 

 

 

 

 

'NestJS' 카테고리의 다른 글

[NestJS] custom-providers  (0) 2023.09.11
[NestJS] custom-decorators  (0) 2023.09.09
[NestJS] Guards  (0) 2023.09.08
[NestJS] Pipes  (0) 2023.09.06
[NestJS] exception-filters  (0) 2023.09.05