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
1 change: 1 addition & 0 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ limit.get(function(err, limit){
- `db` - redis connection instance
- `max` - max requests within `duration` [2500]
- `duration` - of limit in milliseconds [3600000]
- `tidy` - limit the records count, no greater than `max` [false]

# License

Expand Down
22 changes: 14 additions & 8 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ module.exports = Limiter;
function Limiter(opts) {
this.id = opts.id;
this.db = opts.db;
this.tidy = opts.tidy || false;
assert(this.id, '.id required');
assert(this.db, '.db required');
this.max = opts.max || 2500;
Expand Down Expand Up @@ -58,19 +59,24 @@ Limiter.prototype.inspect = function() {

Limiter.prototype.get = function (fn) {
var db = this.db;
var tidy = this.key;
var duration = this.duration;
var key = this.key;
var max = this.max;
var now = microtime.now();
var start = now - duration * 1000;

db.multi()
.zremrangebyscore([key, 0, start])
.zcard([key])
.zadd([key, now, now])
.zrange([key, 0, 0])
.zrange([key, -max, -max])
.pexpire([key, duration])
var operations = [
['zremrangebyscore', key, 0, start],
['zcard', key],
['zadd', key, now, now],
['zrange', key, 0, 0],
['zrange', key, -max, -max],
['pexpire', key, duration],
]
if (tidy) {
operations.splice(5, 0, ['zremrangebyrank', key, 0, -(max + 1)])
}
db.multi(operations)
.exec(function (err, res) {
if (err) return fn(err);

Expand Down
Loading