Skip to content

Commit

Permalink
Added: get method to memory limiter
Browse files Browse the repository at this point in the history
  • Loading branch information
animir committed Jun 29, 2018
1 parent 015238b commit 2a627ef
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
9 changes: 9 additions & 0 deletions lib/RateLimiterMemory.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
26 changes: 26 additions & 0 deletions test/RateLimiterMemory.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
});
});

0 comments on commit 2a627ef

Please sign in to comment.