jhurliman / node-rate-limiter

A generic rate limiter for node.js. Useful for API clients, web crawling, or other tasks that need to be throttled
MIT License
1.51k stars 135 forks source link

How to use rate limiter and retrieve my business method result #68

Closed boly38 closed 3 years ago

boly38 commented 3 years ago

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.

I would like to know:

Best regards

boly38 commented 3 years ago

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.