Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

216
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

0

read the docs: Property-based injection

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda