NestJS - CacheInterceptor

Woody·2023년 1월 17일
0

Caching

목록 보기
1/2

CacheManager 를 커스터마이징하여 쓰다보니 Key 값에 대한 정의를 Unique 하게끔 하는 신경써야하는 부분이 귀찮음을 유발한다. 이럴때 쓰면 좋은 UseInterceptor 데코레이터를 활용한 CacheInterceptor 기능을 소개하려고 한다.

일단 NestInterceptor 를 오버라이딩하는 방법도 있지만 특별한 경우가 아닌 상황이라면 @nestjs/common 에서 기본 제공하는 CacheInterceptor를 사용하면 될 것 같다.

📝 사용하기

@UseInterceptor(CacheInterceptor)

Controller, Method 상관없이 라우트핸들러 데코레이터가 있는 곳이라면 원하는곳에 선언하면 된다.
Controller 에 적용할 경우 당연히 Controller 전역에 설정되게 되며 Controller에 선언하지않고 Method에만 선언하게되면 해당 API에만 적용이 되는것이다.

@CacheTTL

Cache 에 대한 TimeToLive 를 설정하는 데코레이터

@CacheKey

Cache에 대한 Key 값을 설정하는 데코레이터
( ℹ️ 이 데코레이터를 정의 하지 않는경우 [URL + Parameter] 를 Key값으로 사용하여 저장 )

[Controller에 사용]

import {
  Controller,
  Get,
  UseInterceptors,
  CacheInterceptor,
} from '@nestjs/common';

const USER_CACHE_TTL = 60 * 5;

@Controller('user')
@UseInterceptor(CacheInterceptor)
export class UserController {
	constructor(
    	private readonly userService: UserService
    ) {}
    
    @CacheKey('user')
    @CacheTTL(USER_CACHE_TTL)
	async getUser(@Param() userId: string) {
    	return await this.userService.findUser(userId);
    }
}

[Method에 사용]

import {
  Controller,
  Get,
  UseInterceptors,
  CacheInterceptor,
} from '@nestjs/common';

const USER_CACHE_TTL = 60 * 5;

@Controller('user')
export class UserController {
	constructor(
    	private readonly userService: UserService
    ) {}
    
    @UseInterceptor(CacheInterceptor)
    @CacheKey('user')
    @CacheTTL(USER_CACHE_TTL)
	async getUser(@Param() userId: string) {
    	return await this.userService.findUser(userId);
    }
}

끝.

profile
1일 1한숨 Back-End 개발자

0개의 댓글