Skip to content

Commit

Permalink
fixes #34
Browse files Browse the repository at this point in the history
	will set a new item in database if ttl is -1 or less which indicates the key has been decreased after ttl has expired
  • Loading branch information
scttcper committed Nov 2, 2016
1 parent 7a7e3ab commit 27a767d
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 3 deletions.
6 changes: 6 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,12 @@ function ratelimit(opts) {
ctx.set(headers);
return next();
}
if (expires < 0) {
debug(`${name} is stuck. Resetting.`);
debug('remaining %s/%s %s', opts.max - 1, opts.max, id);
opts.db.set(name, opts.max - 1, 'PX', opts.duration || 3600000, 'NX');
return next();
}
// user maxed
headers['Retry-After'] = t;
headers[opts.headers.remaining] = n;
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"type": "git",
"url": "git+https://github.com/scttcper/koa-simple-ratelimit.git"
},
"version": "2.1.0",
"version": "2.1.1",
"keywords": [
"koa",
"middleware",
Expand Down
40 changes: 38 additions & 2 deletions test/ratelimit.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const ratelimit = require('..');
const db = redis.createClient();

describe('ratelimit middleware', () => {
const rateLimitDuration = 1000;
const rateLimitDuration = 300;
const goodBody = 'Num times hit: ';

before((done) => {
Expand Down Expand Up @@ -55,7 +55,7 @@ describe('ratelimit middleware', () => {
}, rateLimitDuration);
});

it('responds with 429 when rate limit is exceeded', (done) => {
it('should respond with 429 when rate limit is exceeded', (done) => {
request(app.listen())
.get('/')
.expect('X-RateLimit-Remaining', '0')
Expand All @@ -74,6 +74,42 @@ describe('ratelimit middleware', () => {
});
});

describe('shortlimit', () => {
let guard;
let app;

const routeHitOnlyOnce = () => {
guard.should.be.equal(1);
};

beforeEach((done) => {
app = new Koa();

app.use(ratelimit({
duration: 1,
db: db,
max: 1,
}));

app.use((ctx, next) => {
guard += 1;
ctx.body = goodBody + guard;
return next();
});

guard = 0;
done();
});

it('should respond with 429 when rate limit is exceeded', (done) => {
request(app.listen())
.get('/')
.expect('X-RateLimit-Remaining', '0')
.expect(429)
.end(done);
});
});

describe('limit with throw', () => {
let guard;
let app;
Expand Down

0 comments on commit 27a767d

Please sign in to comment.