1.1.10 • Published 1 year ago

nestjs-graphql-rate-limiting v1.1.10

Weekly downloads
-
License
UNLICENSED
Repository
github
Last release
1 year ago

Description

A Rate-Limiter for NestJS, in the context of graphql

This package is only based on redis storage

Installation

$ yarn add nestjs-graphql-rate-limiting

Uage

Import the module (RateLimitingModule) at the root module of your app, and pass in default options for rate limiting. Value for clientIdentifierPath field can also be provided here as a default value.

import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { RateLimitingModule } from 'nestjs-graphql-rate-limiting';
import { ApolloDriver } from '@nestjs/apollo';

@Module({
  imports: [
    RateLimitingModule.forRoot({
      ttl: 900,
      maxAttempts: 6,
      redisHost: 'localhost',
      redisPort: 6379
    }),
  ],
  controllers: [],
})
export class AppModule {}

And use the decorator (RateLimiting) at provider scope or at method scope, and optionally pass in options which will overwrite the default options provided when initializing the module

import { Query, Resolver } from '@nestjs/graphql';
import { RateLimiting } from 'nestjs-graphql-rate-limiting';
import { UsersService } from './users.service';
import { User } from './users.type';

@Resolver()
export class UsersResolver {
  constructor(private readonly usersService: UsersService) {}

  @Query(() => [User], { name: 'findUsers', nullable: 'items' })
  @RateLimiting({
    redisHost: 'localhost',
    redisPort: 6379,
    maxAttempts: 6,
    ttl: 900,
    clientIdentifierPath: 'body.getUser().id'
  })
  findUsers() {
    const users = this.usersService.findUsers();
    return users;
  }

}

Note that the field (clientIdentifierPath) is required, which will be used to uniquely identify the requesting user, and any other field other than body can be specified but it has to exist in the request object. () is used to mean the function which will be called, followed by any sub fields (e.g., 'headers.ip'). Options for redis connection can also provided in the decorator level, which will be used only for routes that this decorator is binded to