jhurliman/node-rate-limiter

How to use rate limiter and retrieve my business method result

Closed this issue · 1 comments

Hi
I'm trying to use this library in order to limit number of http call my app is doing to and external provider.
So my rate limited method MUST provide an promise result (api result).

Business method example:

function getDocs() {
  return fetch("https://provider.com/api/docs")
}

I'm asking myself on how to do that with this library.

I will soon suggest a linked PR with some usage examples.

  • one blocking wait (seems not good practice),
  • one using async promise suggested by @sunknudsen in #63

I would like to know:

  • does current library could embed a samples/ directory with some ready-to-use examples,
  • what is the best way to handle and get promise result with this (waiting mode) rate limit?

Best regards

in creharmony/node-etsy-client#20, I finally opt for an async promise (like the one #63 suggested by synjnudsen). And that's fine without node-rate-limiter update.

Here is an example:

  limitedApiFetch(endpoint, options) {
    var client = this;
    if (!client.isRateLimitEnabled()) {
      return client.apiFetch(endpoint, options);
    } else {
      return new Promise((resolve, reject) => {
        client.asyncRemoveTokens(1)
          .then((remainingRequests)=> {
            client.apiFetch(endpoint, options)
                .then(resolve).catch(reject);
          })
          .catch(reject)
      });
    }
  }


  asyncRemoveTokens(count) {
    var client = this;
    return new Promise((resolve, reject) => {
      client.limiter.removeTokens(count, (error, remainingRequests) => {
        if (remainingRequests < 0 && !client.shouldWait) {
          reject("rate limit reached");
        }
        if (error) return reject(error)
        resolve(remainingRequests)
      })
    })
  }

In this use-case I could make my own error on limit reached when wait is disabled.