npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@zedquads/nestjs-bottleneck

v1.0.8

Published

A NestJS module providing rate limiting features using the Bottleneck package.

Downloads

42

Readme

Bottleneck Module for NestJS

This package provides a NestJS module and decorators to easily integrate the bottleneck rate-limiting library with your NestJS applications, supporting both REST and GraphQL.

Installation

First, install the package along with its peer dependencies:

npm install @zedquads/nestjs-bottleneck bottleneck

optional:

npm install ioredis redis

Usage

Module Setup Register the BottleneckModule in your NestJS application.

Static Configuration:

import { Module } from '@nestjs/common';
import { BottleneckModule } from '@zedquads/nestjs-bottleneck';

@Module({
  imports: [
    BottleneckModule.forRoot({
      maxConcurrent: 5,
      minTime: 100,
      datastore: 'ioredis',
      connection: { host: 'localhost', port: 6379 },
      isGlobal: true, // Set to 'false' to make the module local
    }),
  ],
})
export class AppModule {}

Async Configuration:

import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { BottleneckModule } from '@zedquads/nestjs-bottleneck';

@Module({
  imports: [
    ConfigModule.forRoot(),
    BottleneckModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => ({
        maxConcurrent: configService.get<number>('BOTTLENECK_MAX_CONCURRENT'),
        minTime: configService.get<number>('BOTTLENECK_MIN_TIME'),
        datastore: 'ioredis',
        connection: {
          host: configService.get<string>('REDIS_HOST'),
          port: configService.get<number>('REDIS_PORT'),
        },
      }),
      inject: [ConfigService],
      isGlobal: true, // Set to 'false' to make the module local
    }),
  ],
})
export class AppModule {}

Decorator Usage

Use the @Bottleneck decorator to apply rate limiting to your methods. It can be used in both REST controllers and GraphQL resolvers.

REST Example:

import { Controller, Get, Query } from '@nestjs/common';
import { Bottleneck } from '@zedquads/nestjs-bottleneck';

@Controller('example')
export class ExampleController {
  @Get()
  @Bottleneck() // Default key: ExampleController:exampleMethod
  async exampleMethod() {
    return 'This method is rate limited by Bottleneck.';
  }

  @Get('custom')
  @Bottleneck('custom-key') // Custom static key
  async customKeyMethod() {
    return 'This method is rate limited by Bottleneck with a custom key.';
  }

  @Get('mapped')
  @Bottleneck((param) => `mapped-key:${param}`, {
    maxConcurrent: 3,
    minTime: 200,
  }) // Dynamic key and options
  async mappedKeyMethod(@Query('param') param: string) {
    return `This method is rate limited by Bottleneck with a dynamic key: ${param}.`;
  }
}

GraphQL Example:

import { Resolver, Query, Args } from '@nestjs/graphql';
import { Bottleneck } from '@zedquads/nestjs-bottleneck';

@Resolver()
export class ExampleResolver {
  @Query(() => String)
  @Bottleneck() // Default key: ExampleResolver:exampleMethod
  async exampleMethod() {
    return 'This method is rate limited by Bottleneck.';
  }

  @Query(() => String)
  @Bottleneck('custom-key') // Custom static key
  async customKeyMethod() {
    return 'This method is rate limited by Bottleneck with a custom key.';
  }

  @Query(() => String)
  @Bottleneck((param) => `mapped-key:${param}`, {
    maxConcurrent: 3,
    minTime: 200,
  }) // Dynamic key and options
  async mappedKeyMethod(@Args('param') param: string) {
    return `This method is rate limited by Bottleneck with a dynamic key: ${param}.`;
  }
}

Wrapping Functions You can also use the Bottleneck service to wrap functions:

import { Injectable } from '@nestjs/common';
import { BottleneckService } from '@zedquads/nestjs-bottleneck';

@Injectable()
export class ExampleService {
  constructor(private readonly bottleneckService: BottleneckService) {}

  async wrapFunctionExample() {
    const wrappedFunction = this.bottleneckService
      .getGroupLimiter(
        'example-group',
        'example-key',
        { maxConcurrent: 3, minTime: 200 }, // Optional custom options
      )
      .wrap(async (param: string) => {
        // Function logic here
        return `Processed: ${param}`;
      });

    return wrappedFunction('exampleParam');
  }
}

Custom Decorator Create custom decorators to use Bottleneck options:

import { Inject } from '@nestjs/common';
import { BOTTLENECK_OPTIONS } from '@zedquads/nestjs-bottleneck';

export const InjectBottleneckOptions = () => Inject(BOTTLENECK_OPTIONS);

Refer to the official Bottleneck documentation for more detailed configurations and options: Bottleneck on npm.