diff --git a/lib/RateLimiterMemory.js b/lib/RateLimiterMemory.js index a7d4b57..a79a67c 100644 --- a/lib/RateLimiterMemory.js +++ b/lib/RateLimiterMemory.js @@ -48,7 +48,7 @@ class RateLimiterMemory extends RateLimiterAbstract { return new Promise((resolve) => { const secDuration = this._getKeySecDuration(options); const res = this._memoryStorage.incrby(rlKey, points, secDuration); - res.remainingPoints = this.points - res.consumedPoints; + res.remainingPoints = Math.max(this.points - res.consumedPoints, 0); resolve(res); }); } @@ -58,7 +58,7 @@ class RateLimiterMemory extends RateLimiterAbstract { return new Promise((resolve) => { const secDuration = this._getKeySecDuration(options); const res = this._memoryStorage.incrby(rlKey, -points, secDuration); - res.remainingPoints = this.points - res.consumedPoints; + res.remainingPoints = Math.max(this.points - res.consumedPoints, 0); resolve(res); }); } @@ -91,7 +91,7 @@ class RateLimiterMemory extends RateLimiterAbstract { get(key) { const res = this._memoryStorage.get(this.getKey(key)); if (res !== null) { - res.remainingPoints = this.points - res.consumedPoints; + res.remainingPoints = Math.max(this.points - res.consumedPoints, 0); } return Promise.resolve(res); diff --git a/test/RateLimiterMemory.test.js b/test/RateLimiterMemory.test.js index 5b591a0..cd2ea24 100644 --- a/test/RateLimiterMemory.test.js +++ b/test/RateLimiterMemory.test.js @@ -361,6 +361,7 @@ describe('RateLimiterMemory with fixed window', function RateLimiterMemoryTest() rateLimiter.get(testKey) .then((res) => { expect(res.consumedPoints).to.equal(12); + expect(res.remainingPoints).to.equal(0); done(); }); })