node-rate-limiter-flexible icon indicating copy to clipboard operation
node-rate-limiter-flexible copied to clipboard

Feature Request: decorators

Open dmurvihill opened this issue 1 year ago • 4 comments

I'd like to wrap my functions like this:

let limiter: RateLimiterAbstract;

//...

@limiter.enforce
// or for more tokens: @limiter.enforce(2)
function limitedFunction() {
  // implementation
}

And the same on RateLimiterQueue.

Any interest in this feature?

dmurvihill avatar Oct 27 '24 20:10 dmurvihill

@dmurvihill Hey, interesting approach. It could be created as a new package based on rate-limiter-flexible. After that we could add it to docs.

animir avatar Oct 28 '24 13:10 animir

This is the implementation:

import { RateLimiterQueue } from "rate-limiter-flexible";

export function limitWith<Args extends unknown[], Return>(
  queue: RateLimiterQueue,
  cost: number = 1,
) {
  return (f: (...args: Args) => Return) => {
    return async (...args: Args) => {
      await queue.removeTokens(cost);
      return f(...args);
    };
  };
}

I don't really want to publish an entire NPM package just for that, or have it as a separate dependency for that matter. (anyone remember left-pad?)

dmurvihill avatar Oct 29 '24 07:10 dmurvihill

@dmurvihill Could you write a usage example? Probably, for RateLimiterRedis as it is the most popular limiter. I'll add it to the docs.

animir avatar Nov 03 '24 11:11 animir

See the original comment for suggested usage.

dmurvihill avatar Dec 13 '24 19:12 dmurvihill