From 2a627efcdfbef4e03f130aac122da3a352170be7 Mon Sep 17 00:00:00 2001 From: Roman Voloboev Date: Sat, 30 Jun 2018 01:06:42 +1000 Subject: [PATCH] Added: get method to memory limiter --- lib/RateLimiterMemory.js | 9 +++++++++ test/RateLimiterMemory.test.js | 26 ++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/lib/RateLimiterMemory.js b/lib/RateLimiterMemory.js index b5058f8..5b24f78 100644 --- a/lib/RateLimiterMemory.js +++ b/lib/RateLimiterMemory.js @@ -69,6 +69,15 @@ class RateLimiterMemory extends RateLimiterAbstract { this._memoryStorage.set(this.getKey(key), initPoints, msDuration); return Promise.resolve(new RateLimiterRes(0, msDuration, initPoints)); } + + get(key) { + const res = this._memoryStorage.get(this.getKey(key)); + if (res !== null) { + res.remainingPoints = this.points - res.consumedPoints; + } + + return Promise.resolve(res); + } } module.exports = RateLimiterMemory; diff --git a/test/RateLimiterMemory.test.js b/test/RateLimiterMemory.test.js index 0be274b..b14ff50 100644 --- a/test/RateLimiterMemory.test.js +++ b/test/RateLimiterMemory.test.js @@ -176,4 +176,30 @@ describe('RateLimiterMemory with fixed window', function () { done(); }); }); + + it('get by key', (done) => { + const testKey = 'get'; + const rateLimiterMemory = new RateLimiterMemory({ points: 2, duration: 5 }); + rateLimiterMemory.consume(testKey) + .then(() => { + rateLimiterMemory.get(testKey) + .then((res) => { + expect(res.remainingPoints).to.equal(1); + done(); + }); + }) + .catch(() => { + done(Error('must not reject')); + }); + }); + + it('get resolves null if key is not set', (done) => { + const testKey = 'getbynotexistingkey'; + const rateLimiterMemory = new RateLimiterMemory({ points: 2, duration: 5 }); + rateLimiterMemory.get(testKey) + .then((res) => { + expect(res).to.equal(null); + done(); + }); + }); });