DDos 같은 공격을 어느정도 대비하기위해 사용하려고 합니다.
이 Rate limit 사용하기위해서는 우선 아래 코드를 다운받아야합니다.
npm i @nestjs/throttler
이제 app.module에서 코드를 수정해줍니다.
import {
CacheModule,
MiddlewareConsumer,
Module,
NestModule,
RequestMethod,
} from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { AppController } from "./app.controller";
import { AppService } from "./app.service";
import { BoardModule } from "./board/board.module";
import { TypeOrmConfigService } from "./config/typeorm.config.service";
import { UserModule } from "./user/user.module";
import { ConfigModule, ConfigService } from "@nestjs/config";
import { JwtModule } from "@nestjs/jwt";
import { JwtConfigService } from "./config/jwt.config.service";
import { AuthMiddleware } from "./auth/auth.middleware";
import { ThrottlerGuard, ThrottlerModule } from "@nestjs/throttler";
import { APP_GUARD } from "@nestjs/core";
@Module({
imports: [
...
ThrottlerModule.forRoot({
ttl: 60,
limit: 10, // ttl 동안 limit 만큼의 요청만 받는다.
}),
...
],
...
providers: [
...
{
provide: APP_GUARD,
useClass: ThrottlerGuard,
},
],
})
export class AppModule implements NestModule {
...
}
그리고 board controller로 가서 수정해줍니다.
@SkipThrottle() // 데코레이터 추가!
@Get("/articles")
async getArticles() {
return await this.boardService.getArticles();
}
이경우에는 /articles를 호출해도 Rate limit가 적용되지 않고 계속 호출이 되는 것을 확인할 수 있습니다.
특별하게 적용하고 싶으면 @Throttle(limit, ttl) 데코레이터를 추가하면 됩니다.
@Throttle(5, 60) // 이렇게 하면 60초에 5번 호출만 가능!
@Get("/articles/:id")
async getArticleById(@Param("id") articleId: number) {
return await this.boardService.getArticleById(articleId);
}