Skip to content

Commit

Permalink
Allow the expected number of attempts on a route - Fixes issue ded#3
Browse files Browse the repository at this point in the history
  • Loading branch information
Christopher De Cairos committed Sep 2, 2014
1 parent 99c10ed commit 965842d
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 2 deletions.
4 changes: 3 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ module.exports = function (app, db) {
limit.remaining = opts.total
}

var last = Number(limit.remaining) === 1;

// do not allow negative remaining
limit.remaining = Math.max(Number(limit.remaining) - 1, 0)
db.set(key, JSON.stringify(limit), 'PX', opts.expire, function (e) {
Expand All @@ -34,7 +36,7 @@ module.exports = function (app, db) {
res.set('X-RateLimit-Remaining', limit.remaining)
}

if (limit.remaining) return next()
if (limit.remaining || last) return next()

var after = (limit.reset - Date.now()) / 1000

Expand Down
2 changes: 1 addition & 1 deletion tests/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ describe('rate-limiter', function () {
})

it('should work', function (done) {
var map = [10, 9, 8, 7, 6, 5, 4, 3, 2]
var map = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
var clock = sinon.useFakeTimers()

limiter({
Expand Down

1 comment on commit 965842d

@cjthompson
Copy link

Choose a reason for hiding this comment

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

I found the same error but solved it in a slightly different way:

        // do not allow negative remaining
        limit.remaining = Math.max(Number(limit.remaining) - 1, -1)
        db.set(key, JSON.stringify(limit), 'PX', opts.expire, function (e) {
          if (!opts.skipHeaders) {
            res.set('X-RateLimit-Limit', limit.total)
            res.set('X-RateLimit-Remaining', Math.max(limit.remaining,0))
          }

          if (limit.remaining >= 0) return next()

Please sign in to comment.