Created
July 20, 2018 04:21
-
-
Save sdawood/fdc309d6b2dfdf493e33bc07eb136ae9 to your computer and use it in GitHub Desktop.
Patching limiter with async getTokens
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const {RateLimiter} = require('limiter'); | |
| RateLimiter.prototype.getTokens = async function (count) { | |
| const that = this; | |
| if (count <= this.tokenBucket.bucketSize) { | |
| return new Promise((resolve, reject) => { | |
| this.removeTokens(count, (err, remaining) => { | |
| if (err) { | |
| return reject(err); | |
| } | |
| return resolve(count); | |
| }); | |
| }); | |
| } | |
| const interval = this.tokenBucket.interval; | |
| const tokensPerInterval = this.tokenBucket.tokensPerInterval; | |
| const shapingTimeMs = Math.ceil(count * (interval / tokensPerInterval)); | |
| const numIntervals = shapingTimeMs / interval; | |
| let consumed = 0; | |
| let chunk = this.tokenBucket.bucketSize; | |
| while (consumed < count) { | |
| chunk = Math.min(chunk, count - consumed); | |
| consumed += await new Promise((resolve, reject) => { | |
| that.removeTokens(chunk, (error, remaining) => { | |
| if (error) { | |
| reject(error); | |
| } else { | |
| resolve(chunk); | |
| } | |
| }); | |
| }); | |
| } | |
| return consumed; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment