rolling-rate-limiter
Advanced tools
Comparing version 0.1.1 to 0.1.2
18
index.js
@@ -21,2 +21,17 @@ var assert = require("assert"); | ||
if (redis) { | ||
// If redis is going to be potentially returning buffers OR an array from | ||
// ZRANGE, need a way to safely convert either of these types to an array | ||
// of numbers. Otherwise, we can just assume that the result is an array | ||
// and safely map over it. | ||
var zrangeToUserSet; | ||
if (redis.options.return_buffers || redis.options.detect_buffers) { | ||
zrangeToUserSet = function(str) { | ||
return String(str).split(",").map(Number); | ||
} | ||
} else { | ||
zrangeToUserSet = function(arr) { | ||
return arr.map(Number); | ||
} | ||
} | ||
return function (id, cb) { | ||
@@ -28,2 +43,3 @@ if (!cb) { | ||
assert.equal(typeof cb, "function", "Callback must be a function."); | ||
@@ -43,3 +59,3 @@ | ||
var userSet = resultArr[1].map(Number); | ||
var userSet = zrangeToUserSet(resultArr[1]); | ||
@@ -46,0 +62,0 @@ var tooManyInInterval = userSet.length >= maxInInterval; |
{ | ||
"name": "rolling-rate-limiter", | ||
"version": "0.1.1", | ||
"version": "0.1.2", | ||
"description": "Rate limiter that supports a rolling window, either in-memory or backed by redis", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
@@ -268,8 +268,9 @@ var sinon = require("sinon"); | ||
beforeEach(function() { | ||
redis.fast = false; | ||
redis.fast = false; // mock redis network latency. | ||
}); | ||
it("prevents requests that exceed the maximum over the interval", function(done) { | ||
var client = redis.createClient(); | ||
var counter = RateLimitedCounter({ | ||
redis: redis.createClient(), | ||
redis: client, | ||
interval: 300, | ||
@@ -288,2 +289,22 @@ maxInInterval: 30 | ||
it("works when redis is in buffer mode", function(done) { | ||
var client = redis.createClient({return_buffers: true}); | ||
// fakeredis seems to hide this option. | ||
client.options = {}; | ||
client.options.return_buffers = true; | ||
var counter = RateLimitedCounter({ | ||
redis: client, | ||
interval: 300, | ||
maxInInterval: 30 | ||
}); | ||
async.times(100, function(n, next) { | ||
counter.increment(next); | ||
}, function(err) { | ||
if (err) throw err; | ||
expect(counter.getCount()).to.equal(30); | ||
done(); | ||
}); | ||
}); | ||
it("keeps seperate counts for multiple users", function(done) { | ||
@@ -290,0 +311,0 @@ var counter = RateLimitedCounter({ |
24127
531