#Throttler with websockets

2 messages · Page 1 of 1 (latest)

sour ember
#
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}`;
  }
}
#
  1. TS2416: Property 'handleRequest' in type 'WsThrottlerGuard' is not assignable to the same property in base type 'ThrottlerGuard'.

    This indicates a type mismatch. The handleRequest method in your WsThrottlerGuard class doesn't adhere to the signature expected by the base class, ThrottlerGuard. We need to align the parameters and return type.

  2. TS2554: Expected 5 arguments, but got 2.

    This error occurs specifically within the this.storageService.increment call. It suggests the increment method in your storage service requires five arguments, but you're providing only two (key and TTL).

  3. throttler-storage.interface.d.ts(3, 41): An argument for limit was not provided.

    This pinpoints the missing limit argument within the increment method call.