import { Injectable, ExecutionContext } from '@nestjs/common';
import { ThrottlerGuard, ThrottlerException, ThrottlerOptions } from '@nestjs/throttler';
import { ThrottlerStorage } from '@nestjs/throttler/dist/throttler-storage.interface';
@Injectable()
export class WsThrottlerGuard extends ThrottlerGuard {
constructor(private readonly storageService: ThrottlerStorage) { // Inject ThrottlerStorage
super();
}
async handleRequest(
context: ExecutionContext,
limit: number,
ttl: number,
): Promise<boolean> { // Remove throttler: ThrottlerOptions
const client = context.switchToWs().getClient();
const ip = client._socket.remoteAddress;
const key = this.generateKey(context, ip); // Remove throttler
const { totalHits } = await this.storageService.increment(key, ttl, limit); // Use limit
if (totalHits > limit) {
throw new ThrottlerException();
}
return true;
}
protected generateKey(context: ExecutionContext, ip?: string): string {
if (!ip) {
throw new Error('Invalid IP address');
}
const route = this.getRoute(context);
return `${route}:${ip}`;
}
}
#Throttler with websockets
2 messages · Page 1 of 1 (latest)
-
TS2416: Property 'handleRequest' in type 'WsThrottlerGuard' is not assignable to the same property in base type 'ThrottlerGuard'.This indicates a type mismatch. The
handleRequestmethod in yourWsThrottlerGuardclass doesn't adhere to the signature expected by the base class,ThrottlerGuard. We need to align the parameters and return type. -
TS2554: Expected 5 arguments, but got 2.This error occurs specifically within the
this.storageService.incrementcall. It suggests theincrementmethod in your storage service requires five arguments, but you're providing only two (key and TTL). -
throttler-storage.interface.d.ts(3, 41): An argument for limit was not provided.This pinpoints the missing
limitargument within theincrementmethod call.