File tree Expand file tree Collapse file tree 2 files changed +19
-6
lines changed Expand file tree Collapse file tree 2 files changed +19
-6
lines changed Original file line number Diff line number Diff line change 1
- var rateLimiter = require ( './rate-limiter' ) ;
1
+ var rateLimiter = require ( './rate-limiter' ) ;
2
2
3
3
module . exports = function ( opts ) {
4
4
var limiter = rateLimiter ( opts ) ;
@@ -7,8 +7,15 @@ module.exports = function(opts) {
7
7
if ( err ) {
8
8
next ( ) ;
9
9
} else {
10
+ res . set ( {
11
+ 'X-RateLimit-Limit' : rate . limit ,
12
+ 'X-RateLimit-Remaining' : rate . current > rate . limit ? 0 : rate . limit - rate . current ,
13
+ 'X-RateLimit-Reset' : ( rate . reset / 1000 ) | 0
14
+ } ) ;
10
15
if ( rate . current > rate . limit ) {
11
- res . writeHead ( 429 ) ;
16
+ var after = rate . reset - Date . now ( ) ;
17
+ res . set ( 'Retry-After' , ( after / 1000 ) | 0 ) ;
18
+ res . send ( 429 , 'Rate limit exceeded, retry after ' + after + 'ms' ) ;
12
19
res . end ( ) ;
13
20
} else {
14
21
next ( ) ;
Original file line number Diff line number Diff line change @@ -10,21 +10,27 @@ module.exports = function(opts) {
10
10
. setex ( tempKey , opts . window ( ) , 0 )
11
11
. renamenx ( tempKey , realKey )
12
12
. incr ( realKey )
13
- . ttl ( realKey )
13
+ . pttl ( realKey )
14
14
. exec ( function ( err , results ) {
15
15
if ( err ) {
16
16
callback ( err ) ;
17
17
} else {
18
- if ( results [ 3 ] == - 1 ) { // automatically recover from possible race condition
19
- opts . redis . expire ( realKey , opts . window ( ) ) ;
18
+ var reset , ttl = results [ 3 ] ;
19
+ if ( ttl == - 1 ) { // automatically recover from possible race condition
20
+ opts . redis . expire ( realKey , opts . window ( ) ) ;
21
+ reset = Date . now ( ) + opts . window ( ) * 1000 ;
22
+ }
23
+ else {
24
+ reset = Date . now ( ) + ttl ;
20
25
}
21
26
var current = results [ 2 ] ;
22
27
callback ( null , {
23
28
key : key ,
24
29
current : current ,
25
30
limit : opts . limit ( ) ,
26
31
window : opts . window ( ) ,
27
- over : ( current > opts . limit ( ) )
32
+ over : ( current > opts . limit ( ) ) ,
33
+ reset : reset
28
34
} ) ;
29
35
}
30
36
} ) ;
You can’t perform that action at this time.
0 commit comments