Skip to content

Instantly share code, notes, and snippets.

@kasir-barati
Created April 14, 2022 10:12
Show Gist options
  • Save kasir-barati/f34b906f1ae58458ea613932ab8e37f0 to your computer and use it in GitHub Desktop.
Save kasir-barati/f34b906f1ae58458ea613932ab8e37f0 to your computer and use it in GitHub Desktop.
Global throttler, Throttler behind the proxy with custom message in nestjs
import { Module } from '@nestjs/common';
import { ThrottlerModule } from '@nestjs/throttler';
import { ThrottlerStorageRedisService } from 'nestjs-throttler-storage-redis';
import { AppService } from './service/app.service';
import { AppController } from './app.controller';
import { APP_GUARD } from '@nestjs/core';
import { GlobalThrottlerGuard } from './guards/global-throttler.guard';
@Module({
imports: [
ThrottlerModule.forRoot({
ttl: 50,
limit: 10,
storage: new ThrottlerStorageRedisService({
host: process.env.REDIS_HOST,
port: +process.env.REDIS_PORT,
db: 1,
}),
}),
],
controllers: [AppController],
providers: [
AppService,
{
provide: APP_GUARD,
useClass: GlobalThrottlerGuard,
},
],
})
export class AppModule {}
import { Injectable } from '@nestjs/common';
import {
ThrottlerException,
ThrottlerGuard,
} from '@nestjs/throttler';
@Injectable()
export class GlobalThrottlerGuard extends ThrottlerGuard {
protected throwThrottlingException(): void {
throw new ThrottlerException(
'تعداد درخواست های ارسال شده از حد مجاز رد شده است',
);
}
}
import {
ThrottlerException,
ThrottlerGuard,
} from '@nestjs/throttler';
import { Injectable } from '@nestjs/common';
@Injectable()
export class ThrottlerBehindProxyGuard extends ThrottlerGuard {
protected getTracker(req: Record<string, any>): string {
return req.ips.length ? req.ips[0] : req.ip;
}
protected throwThrottlingException(): void {
throw new ThrottlerException(
'تعداد درخواست های ارسال شده از حد مجاز رد شده است',
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment