@@ -32,11 +32,13 @@ export class RateLimiterService {
32
32
33
33
@bindThis
34
34
public limit ( limitation : IEndpointMeta [ 'limit' ] & { key : NonNullable < string > } , actor : string , factor = 1 ) {
35
- return new Promise < void > ( ( ok , reject ) => {
36
- if ( this . disabled ) ok ( ) ;
35
+ {
36
+ if ( this . disabled ) {
37
+ return Promise . resolve ( ) ;
38
+ }
37
39
38
40
// Short-term limit
39
- const min = ( ) : void => {
41
+ const min = new Promise < void > ( ( ok , reject ) => {
40
42
const minIntervalLimiter = new Limiter ( {
41
43
id : `${ actor } :${ limitation . key } :min` ,
42
44
duration : limitation . minInterval ! * factor ,
@@ -46,25 +48,25 @@ export class RateLimiterService {
46
48
47
49
minIntervalLimiter . get ( ( err , info ) => {
48
50
if ( err ) {
49
- return reject ( 'ERR' ) ;
51
+ return reject ( { code : 'ERR' , info } ) ;
50
52
}
51
53
52
54
this . logger . debug ( `${ actor } ${ limitation . key } min remaining: ${ info . remaining } ` ) ;
53
55
54
56
if ( info . remaining === 0 ) {
55
- reject ( 'BRIEF_REQUEST_INTERVAL' ) ;
57
+ return reject ( { code : 'BRIEF_REQUEST_INTERVAL' , info } ) ;
56
58
} else {
57
59
if ( hasLongTermLimit ) {
58
- max ( ) ;
60
+ return max ;
59
61
} else {
60
- ok ( ) ;
62
+ return ok ( ) ;
61
63
}
62
64
}
63
65
} ) ;
64
- } ;
66
+ } ) ;
65
67
66
68
// Long term limit
67
- const max = ( ) : void => {
69
+ const max = new Promise < void > ( ( ok , reject ) => {
68
70
const limiter = new Limiter ( {
69
71
id : `${ actor } :${ limitation . key } ` ,
70
72
duration : limitation . duration ! * factor ,
@@ -74,18 +76,18 @@ export class RateLimiterService {
74
76
75
77
limiter . get ( ( err , info ) => {
76
78
if ( err ) {
77
- return reject ( 'ERR' ) ;
79
+ return reject ( { code : 'ERR' , info } ) ;
78
80
}
79
81
80
82
this . logger . debug ( `${ actor } ${ limitation . key } max remaining: ${ info . remaining } ` ) ;
81
83
82
84
if ( info . remaining === 0 ) {
83
- reject ( 'RATE_LIMIT_EXCEEDED' ) ;
85
+ return reject ( { code : 'RATE_LIMIT_EXCEEDED' , info } ) ;
84
86
} else {
85
- ok ( ) ;
87
+ return ok ( ) ;
86
88
}
87
89
} ) ;
88
- } ;
90
+ } ) ;
89
91
90
92
const hasShortTermLimit = typeof limitation . minInterval === 'number' ;
91
93
@@ -94,12 +96,12 @@ export class RateLimiterService {
94
96
typeof limitation . max === 'number' ;
95
97
96
98
if ( hasShortTermLimit ) {
97
- min ( ) ;
99
+ return min ;
98
100
} else if ( hasLongTermLimit ) {
99
- max ( ) ;
101
+ return max ;
100
102
} else {
101
- ok ( ) ;
103
+ return Promise . resolve ( ) ;
102
104
}
103
- } ) ;
105
+ }
104
106
}
105
107
}
0 commit comments