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
클라이언트가 API를 무제한으로 요청할 수 있다면 서버에 부하가 심해질 수 있습니다. 일반적으로 AWS 같은 CDC를 이용하면 디도스 공격을 방어해주긴 하지만 더 확실하게 안정성을 부여하기 위해서 API 호출 횟수에 제한을 두는 것도 좋다고 생각합니다.
설치
npm install @nestjs/throttler
// yarn 사용시
yarn add @nestjs/throttler
호출 횟수 제한 방법
1. 특정 API에만 적용하기
@Throttle 데코레이터를 활용해 특정 API에만 호출 횟수 제한을 둘 수 있습니다.
// 예제
@Throttle({ default: { limit: 3, ttl: 60000 } })
@Get()
findAll() {
return "List users works with custom rate limiting.";
}
2. 전역으로 적용하기
다음과 같이 app.module.ts 에 전역으로 설정할 수도 있습니다.
✅ 저는 현재 yarn berry(3버전)을 이용해 패키지를 설치하고 있습니다. 이로 인해 설치하는 패키지 버전이 달라 설정이 다를 수 있습니다! 예를 들면 구 버전과 달리 현재 yarn을 통해 설치한 @nestjs/throttler는 limit이나 ttl같은 옵션을 throttlers라는 파라미터에 배열 형식으로 설정해야하는 식으로 수정되었습니다.
// app.module에 해당 코드 추가
imports: [
ThrottlerModule.forRoot({
throttlers: [
{
limit: 2,
ttl: 6000000,
},
],
}),
],
providers: [
{
provide: APP_GUARD,
useClass: ThrottlerGuard,
},
],
그리고 해당 방법을 사용했을 때는 역으로 특정 API에만 호출 횟수 제한을 제거하고 싶을 수 있습니다. 이 경우에는 @SkipThrottle 데코레이터를 사용합니다.
// 예제
@SkipThrottle()
@Controller('users')
export class UsersController {}
'백엔드 > NestJS' 카테고리의 다른 글
[TypeORM] Join없이 외래키값만 간단히 활용하기 - @RelationId, @Column (0) | 2024.12.12 |
---|---|
[NestJS] 컨트롤러 파라미터 유효성 검증 방법 (Pipes, DTO, @Transform) (0) | 2024.12.04 |
[NestJS] 동적 라우팅 오류 없애기( route paramter, path variable ) (0) | 2024.11.28 |
[NestJS] 컨트롤러에서 브레이크 포인트 안 걸릴 때 체크해야할 것들! ( 동적 경로, 정적 경로, route parameter ) (0) | 2024.11.25 |
[NestJS]Jest를 이용해 테스트하자 - 1. 유닛 테스트(Unit Testing) (0) | 2024.11.12 |