feat: update throttler (#7957)

This commit is contained in:
darkskygit
2024-08-23 13:52:47 +00:00
parent 49c8a25fce
commit 0b3c7d1407
4 changed files with 31 additions and 26 deletions

View File

@@ -8,8 +8,8 @@ import {
ThrottlerGuard,
ThrottlerModule,
type ThrottlerModuleOptions,
ThrottlerOptions,
ThrottlerOptionsFactory,
ThrottlerRequest,
ThrottlerStorageService,
} from '@nestjs/throttler';
import type { Request } from 'express';
@@ -74,12 +74,15 @@ export class CloudThrottlerGuard extends ThrottlerGuard {
return `${tracker};${throttler}`;
}
override async handleRequest(
context: ExecutionContext,
limit: number,
ttl: number,
throttlerOptions: ThrottlerOptions
) {
override async handleRequest(request: ThrottlerRequest) {
const {
context,
throttler: throttlerOptions,
ttl,
blockDuration,
} = request;
let limit = request.limit;
// give it 'default' if no throttler is specified,
// so the unauthenticated users visits will always hit default throttler
// authenticated users will directly bypass unprotected APIs in [CloudThrottlerGuard.canActivate]
@@ -118,13 +121,11 @@ export class CloudThrottlerGuard extends ThrottlerGuard {
tracker,
throttlerOptions.name ?? 'default'
);
const { timeToExpire, totalHits } = await this.storageService.increment(
key,
ttl
);
const { timeToExpire, totalHits, isBlocked, timeToBlockExpire } =
await this.storageService.increment(key, ttl, limit, blockDuration, key);
if (totalHits > limit) {
res.header('Retry-After', timeToExpire.toString());
if (isBlocked) {
res.header('Retry-After', timeToBlockExpire.toString());
await this.throwThrottlingException(context, {
limit,
ttl,
@@ -132,6 +133,8 @@ export class CloudThrottlerGuard extends ThrottlerGuard {
tracker,
totalHits,
timeToExpire,
isBlocked,
timeToBlockExpire,
});
}