Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

208
Vistas
Inject service into NestJS guard

We use ThrottlerGuard in our NestJS application from @nestjs/throttler package to rate limit connections and it's implemented like this:

@Injectable()
export class RateLimiter extends ThrottlerGuard {
  RATE_LIMIT_EXCEEDED = 'Rate limit exceeded.';

  async handleRequest(context: ExecutionContext, limit: number, ttl: number) {
    const wsData = context.switchToWs().getData();
    const metadata: MetadataObject = wsData.internalRepr;
    const clientTokenMetadata = metadata.get(TOKEN_NAME) as MetadataValue[];
    const clientToken = clientTokenMetadata[0].toString();
    const tokensArray = await this.storageService.getRecord(clientToken);

    if (tokensArray.length >= limit) {
      throw new RpcException({
        code: Status.UNAVAILABLE,
        message: this.RATE_LIMIT_EXCEEDED,
      });
    }

    await this.storageService.addRecord(clientToken, ttl);

    return true;
  }
}

Now, I need to inject another service, let's say ConfigService with the usage of constructor, but because it is an extended class, I need to call super(); method which required three more original arguments inherited from ThrottlerGuard, but they are not exported from the package. Is there any other way to make it work besides the method with DI in constructor?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

What you can do, instead of extending ThrottleGuard is injecting it in your constructor and call canActivate() in handleRequest(). Benefit when not extending you don'

I haven't tested this but you can try the following:

import {ExecutionContext, Injectable} from "@nestjs/common";
import {ConfigService} from "@nestjs/config";
import {InjectThrottlerStorage, ThrottlerGuard, ThrottlerStorage} from '@nestjs/throttler'

@Injectable()
export class RateLimiter {

  constructor(
        private throttle: ThrottlerGuard,
        private configService: ConfigService,
        @InjectThrottlerStorage() private storage: ThrottlerStorage) {
  }

  async handleRequest(context: ExecutionContext, limit: number, ttl: number) {
    // TODO something with ConfigService
    return this.throttle.canActivate(context);
  }
}

ThrottleGuard source code

about 4 years ago · Juan Pablo Isaza Denunciar

0

read the docs: Property-based injection

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda