Rate Limit in NestJS with decorators


@Controller('api/v1/locations')
export class LocationController {
constructor(private readonly locationApi: LocationApi) {
}
@Get()
async getLocations() {
return this.locationApi.getCountrySuggestions();
}
}
  1. Install utils-decorators lib:
npm install --save utils-decorators
import {rateLimit} from 'utils-decorators';

@Controller('api/v1/locations')
export class LocationController {
constructor(private readonly locationApi: LocationApi) {
}

@rateLimit({
allowedCalls: 10,
timeSpanMs: 1000 * 60 * 60, // one minute
keyResolver: (req: Request) => req.ip,
exceedHandler: () => {
throw new HttpException('Rate limit exceeded', HttpStatus.TOO_MANY_REQUESTS);
},
})
@Get()
async getLocations(@Req() req: Request) {
return this.locationApi.getCountrySuggestions();
}
}
import {rateLimit} from 'utils-decorators';

@Injectable()
export class LocationRateLimitInterceptor implements NestInterceptor {

@rateLimit({
allowedCalls: 10,
timeSpanMs: 1000 * 60 * 60, // one minute
keyResolver: (context: ExecutionContext) =>
context.switchToHttp().getRequest().ip,
exceedHandler: () => throw new HttpException(
'Rate limit exceeded', HttpStatus.TOO_MANY_REQUESTS);
},
})
intercept(context: ExecutionContext, next: CallHandler<any>): Observable<any> {
return next.handle();
}
}
export class LocationController {
constructor(private readonly locationApi: LocationApi) {
}

@UseInterceptors(new LocationRateLimitInterceptor())
@Get()
async getLocations() {
return this.locationApi.getCountrySuggestions();
}
}

--

--

--

Father, Husband & FullStack Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Amazon-clone using React, Material-ui and Firebase (Part 2)

A solution for HTTP access control (CORS) issues

Pass data between React Components using Hooks and Context

Understanding Modules in Node.js

Hot reload all the things!

Creating a dynamic database using Postgres and Sequelize.

Flutter vs React Native in 2020

Hi, Could you please help me with the script for hive Metadata can be replicated in AWS cloud using…

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vlad Ioffe

Vlad Ioffe

Father, Husband & FullStack Developer

More from Medium

NestJS: Use a solo @injectable class as a singleton Provider

Repository pattern in Nest.js

TypeScript-based caching decorators

Build a Tasks Processor in NestJS — Communication between Micro-services with RabbitMQ