jimlim

Promise-based rate limiter allowing IDs for each instance to be accessed out of scope

Usage no npm install needed!

<script type="module">
  import jimlim from 'https://cdn.skypack.dev/jimlim';
</script>

README

JimLim

A generic promise-based rate limiter optionally assigning IDs to instances to be accessed in separate scopes.

Features

  • Limits the number of times code can be run in a given period
  • Supports both syncronous and asyncronous code
  • Give an instance an ID and then reaccess it in other parts of the application (relies on require caching)

Brief Usage

First you'll need to npm install the module:

npm install jimlim

Then require the module:

const Limiter = require('jimlim')

Create a limiter instance allowing 100 calls in 10 minutes (period is currently in ms):

const limiter = new Limiter(100, 10 * 60 * 1000)

Now execute some code using the limiter. The .execute() function always returns a promise which resolves if the given function runs without errors:

limiter.execute(() => 'some value')
    .then(console.log) // some value
    .catch(console.log)

You can also provide .execute() with an async function. In this case, the returned promise resolves if the async function resolves:

limiter.execute(async () => 'some value')
    .then(console.log) // some value
    .catch(console.log)

Now on to why this module was created! When .execute() is called more times than specified in the given time period, the returned promise is rejected. This is based on the constructor params above (100 calls in 10 minutes):

for (let i = 1; i <= 150; i++) {
    limiter.execute(async () => 'some value')
        .then(console.log) // called 100 times
        .catch(console.log) // called 50 times
}

Now after 10 minutes, you'll be able to call execute again and the promises will be fulfilled.