Skip to content

Rate limiter with a maximum number of calls per given period of time

License

Notifications You must be signed in to change notification settings

Borewit/rate-limit-threshold

Repository files navigation

Node.js CI CodeQL NPM version npm downloads Coverage Status Codacy Badge Known Vulnerabilities DeepScan grade bundlejs.com badge

rate-limit-threshold

Module designed to handle rate-limiting by allowing developers to set thresholds for the maximum number of requests that can be made within a specified time period. This helps to prevent exceeding the rate limits imposed by APIs or services. The module provides configurable options and is useful for managing API consumption in a controlled manner.

Installation

npm install rate-limit-threshold

This package is an ESM (ECMAScript Module) package. Therefore, your project must also use the ESM format. For more details, refer to this guide.

Compatibility

This package is compatible with:

  1. Pure ESM environments
  2. ECMAScript 2020 (11th Edition) standard.

Support the Project

If you find this project useful and would like to support its development, consider sponsoring or contributing:

Usage

A rate-limit-threshold helps enforce rate limits by restricting the maximum number of calls allowed within a specified time frame. More information about rate limiting can be found here.

Example

import { RateLimitThreshold } from 'rate-limit-threshold';

(async () => {
    const rateLimitThreshold = new RateLimitThreshold(3, 1); // Allow a maximum of 3 requests per second

    for (let n = 0; n < 7; ++n) {
        const delayInMs = await rateLimitThreshold.limit(); // Apply delay to comply with the rate limit
        console.log('Timeout applied to comply with rate limit:', delayInMs);
        // After the limit() has been applied, proceed with your rate-limited request
    }
})();

API Documentation

RateLimitThreshold

Constructor

Create an instance of RateLimitThreshold with the following syntax:

new RateLimitThreshold(requests, period);
Parameters:
  • requests (number): The maximum number of requests allowed within the specified period.
  • period (number): The time period (in seconds) within which the specified number of requests are allowed.

limit

The limit() method ensures that the number of function calls does not exceed the specified requests within the given period. This method should be called before the function you wish to rate limit.

const timeSleptInMs = await rateLimitThreshold.limit();
Returns:

A promise that resolves after a delay, with the time (in milliseconds) that the execution was paused.

About

Rate limiter with a maximum number of calls per given period of time

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 3

  •  
  •  
  •