GitXplorerGitXplorer
l

stopcock

public
18 stars
1 forks
0 issues

Commits

List of commits on branch master.
Unverified
408c1bc7749a906c4c685b76ad276e303c73faf5

[ci] Update actions/setup-node action to v4

llpinca committed a year ago
Unverified
1d024317915f1922c9867ae2db00c1e9317ff44e

[ci] Update actions/checkout action to v4

llpinca committed a year ago
Unverified
26aa34c38bf7892e343f6f77a3dfb4c792e54d2f

[ci] Update coverallsapp/github-action action to v2

llpinca committed 2 years ago
Unverified
aef07178c0b9f19518725ef1d49942c66f856cbc

[doc] Fix CI badge URL

llpinca committed 2 years ago
Unverified
5dc2c328832979ffd8b2dd852192e77c0e228fc0

[ci] Test on node 18

llpinca committed 3 years ago
Unverified
811a73c40abaf244f59557cf861f488cff57e1ff

[ci] Do not test on node 17

llpinca committed 3 years ago

README

The README file for this repository.

stopcock

Version npm Build Status Coverage Status

Limit the execution rate of a function using the token bucket algorithm. Useful for scenarios such as REST APIs consumption where the amount of requests per unit of time should not exceed a given threshold.

Install

npm install --save stopcock

API

The module exports a single function that takes two arguments.

stopcock(fn[, options])

Returns a function which should be called instead of fn.

Arguments

  • fn - The function to rate limit calls to.
  • options - A plain JavaScript object that contains the configuration options.

Options

  • limit - The maximum number of allowed calls per interval. Defaults to 2.
  • interval - The timespan where limit is calculated. Defaults to 1000.
  • bucketSize - The capacity of the bucket. Defaults to 40.
  • queueSize - The maximum size of the internal queue. Defaults to 2^32 - 1 which is the maximum array size in JavaScript.

Return value

A function that returns a promise which resolves to the value returned by the original fn function. The returned function has a size accessor property which returns the internal queue size. When the queue is at capacity the promise is rejected.

Example

const stopcock = require('stopcock');

function request(i) {
  return Promise.resolve(`${i} - ${new Date().toISOString()}`);
}

function log(data) {
  console.log(data);
}

const get = stopcock(request, { bucketSize: 5 });

for (let i = 0; i < 10; i++) {
  get(i).then(log);
}

/*
0 - 2017-03-30T16:46:39.938Z
1 - 2017-03-30T16:46:39.940Z
2 - 2017-03-30T16:46:39.940Z
3 - 2017-03-30T16:46:39.940Z
4 - 2017-03-30T16:46:39.940Z
5 - 2017-03-30T16:46:40.443Z
6 - 2017-03-30T16:46:40.943Z
7 - 2017-03-30T16:46:41.441Z
8 - 2017-03-30T16:46:41.942Z
9 - 2017-03-30T16:46:42.439Z
*/

License

MIT