Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,15 +69,21 @@ Limiter.prototype.get = function (fn) {
.zcard([key])
.zadd([key, now, now])
.zrange([key, 0, 0])
.zrange([key, -max, -max])
.pexpire([key, duration])
.exec(function (err, res) {
if (err) return fn(err);
var count = parseInt(Array.isArray(res[0]) ? res[1][1] : res[1]);
var oldest = parseInt(Array.isArray(res[0]) ? res[3][1] : res[3]);

var isIoRedis = Array.isArray(res[0]);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh, now I understood better why this check is necessary. I removed it from the promise equivalent package:

https://github.com/tj/node-ratelimiter/pull/44/files#diff-168726dbe96b3ce427e7fedce31bb0bcR77

Making it a bit faster, thanks 🙂

(I will add this PR as well)

var count = parseInt(isIoRedis ? res[1][1] : res[1]);
var oldest = parseInt(isIoRedis ? res[3][1] : res[3]);
var oldestInRange = parseInt(isIoRedis ? res[4][1] : res[4]);
var resetMicro = (Number.isNaN(oldestInRange) ? oldest : oldestInRange) + duration * 1000;

fn(null, {
remaining: count < max ? max - count : 0,
reset: Math.floor((oldest + duration * 1000) / 1000000),
resetMs: Math.floor((oldest + duration * 1000) / 1000),
reset: Math.floor(resetMicro / 1000000),
resetMs: Math.floor(resetMicro / 1000),
total: max
});
});
Expand Down
40 changes: 30 additions & 10 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,23 +88,43 @@ var Limiter = require('..'),
});

describe('when the limit is exceeded', function() {
it('should retain .remaining at 0', function(done) {
var limit = new Limiter({
var limit;

beforeEach(function (done) {
limit = new Limiter({
max: 2,
id: 'something',
db: db
});

limit.get(function() {
limit.get(function() {
done();
});
});
});

it('should retain .remaining at 0', function(done) {
limit.get(function(err, res) {
res.remaining.should.equal(2);
// function caller should reject this call
res.remaining.should.equal(0);
done();
});
});

it('should return an increasing reset time after each call', function (done) {
setTimeout(function () {
limit.get(function(err, res) {
res.remaining.should.equal(1);
limit.get(function(err, res) {
// function caller should reject this call
res.remaining.should.equal(0);
done();
});
var originalResetMs = res.resetMs;

setTimeout(function() {
limit.get(function (err, res) {
res.resetMs.should.be.greaterThan(originalResetMs);
done();
});
}, 10);
});
});
}, 10);
});
});

Expand Down