Skip to content

Commit 009aade

Browse files
committed
fix: fixed tests and onLimited functionality (per #69)
1 parent 0da2286 commit 009aade

File tree

3 files changed

+10
-7
lines changed

3 files changed

+10
-7
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,9 @@ app.use(ratelimit({
5656
},
5757
blacklist: (ctx) => {
5858
// some logic that returns a boolean
59+
},
60+
onLimited: (ctx) => {
61+
// optional function to run when a user is rate limited
5962
}
6063
}));
6164

index.js

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ module.exports = function ratelimit(opts = {}) {
4646
reset: 'X-RateLimit-Reset',
4747
total: 'X-RateLimit-Limit'
4848
},
49-
onLimit: undefined
49+
onLimited: undefined
5050
};
5151

5252
opts = { ...defaultOpts, ...opts };
@@ -64,7 +64,6 @@ module.exports = function ratelimit(opts = {}) {
6464
typeof opts.whitelist === 'function' && (await opts.whitelist(ctx));
6565
const blacklisted =
6666
typeof opts.blacklist === 'function' && (await opts.blacklist(ctx));
67-
const { onLimited } = opts;
6867

6968
if (blacklisted) {
7069
ctx.throw(403, 'Forbidden');
@@ -119,7 +118,7 @@ module.exports = function ratelimit(opts = {}) {
119118
ctx.state.rateLimit = { after, headers, id, message };
120119
ctx.status = opts.status || 429;
121120

122-
if (onLimited) onLimited(ctx);
121+
if (opts.onLimited) opts.onLimited(ctx);
123122

124123
if (opts.throw) {
125124
headers['Retry-After'] = after;

test/memory.spec.js

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -408,8 +408,8 @@ describe('ratelimit middleware with memory driver', () => {
408408
});
409409
});
410410

411-
describe('onLimit', async () => {
412-
it('should allow specifying an onLimit callback', async () => {
411+
describe('onLimited', async () => {
412+
it('should allow specifying an onLimited callback', async () => {
413413
const app = new Koa();
414414
let testValue = 0;
415415

@@ -418,7 +418,7 @@ describe('ratelimit middleware with memory driver', () => {
418418
driver: 'memory',
419419
db,
420420
max: 0,
421-
onLimit(ctx) {
421+
onLimited(ctx) {
422422
testValue = 1;
423423
}
424424
})
@@ -427,7 +427,8 @@ describe('ratelimit middleware with memory driver', () => {
427427
await request(app.listen())
428428
.get('/')
429429
.set('foo', 'bar')
430-
.expect(testValue, 1);
430+
.expect(429)
431+
.expect(() => testValue.should.equal(1));
431432
});
432433
});
433434
});

0 commit comments

Comments
 (0)