Created
April 14, 2022 10:12
-
-
Save kasir-barati/f34b906f1ae58458ea613932ab8e37f0 to your computer and use it in GitHub Desktop.
Global throttler, Throttler behind the proxy with custom message in nestjs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 {} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@nestjs/common'; | |
import { | |
ThrottlerException, | |
ThrottlerGuard, | |
} from '@nestjs/throttler'; | |
@Injectable() | |
export class GlobalThrottlerGuard extends ThrottlerGuard { | |
protected throwThrottlingException(): void { | |
throw new ThrottlerException( | |
'تعداد درخواست های ارسال شده از حد مجاز رد شده است', | |
); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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