Przemek Wit
Przemek Wit

Reputation: 265

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?

Upvotes: 1

Views: 1575

Answers (1)

Dominic
Dominic

Reputation: 3483

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

Upvotes: 1

Related Questions