@@ -74,6 +74,29 @@ function createRateLimit(options = {}) {
74
74
skip,
75
75
} = options
76
76
77
+ /**
78
+ * Helper function to add rate limit headers to a response
79
+ * @param {Response } response - Response object to add headers to
80
+ * @param {number } totalHits - Current hit count
81
+ * @param {Date } resetTime - When the rate limit resets
82
+ * @returns {Response } Response with headers added
83
+ */
84
+ const addRateLimitHeaders = ( response , totalHits , resetTime ) => {
85
+ if ( standardHeaders && response && response . headers ) {
86
+ response . headers . set ( 'X-RateLimit-Limit' , max . toString ( ) )
87
+ response . headers . set (
88
+ 'X-RateLimit-Remaining' ,
89
+ Math . max ( 0 , max - totalHits ) . toString ( ) ,
90
+ )
91
+ response . headers . set (
92
+ 'X-RateLimit-Reset' ,
93
+ Math . ceil ( resetTime . getTime ( ) / 1000 ) . toString ( ) ,
94
+ )
95
+ response . headers . set ( 'X-RateLimit-Used' , totalHits . toString ( ) )
96
+ }
97
+ return response
98
+ }
99
+
77
100
return async function rateLimitMiddleware ( req , next ) {
78
101
// Allow test to inject a fresh store for isolation
79
102
const activeStore = req && req . rateLimitStore ? req . rateLimitStore : store
@@ -92,22 +115,6 @@ function createRateLimit(options = {}) {
92
115
const key = await keyGenerator ( req )
93
116
const { totalHits, resetTime} = await activeStore . increment ( key , windowMs )
94
117
95
- const createResponse = ( response ) => {
96
- if ( standardHeaders && response && response . headers ) {
97
- response . headers . set ( 'X-RateLimit-Limit' , max . toString ( ) )
98
- response . headers . set (
99
- 'X-RateLimit-Remaining' ,
100
- Math . max ( 0 , max - totalHits ) . toString ( ) ,
101
- )
102
- response . headers . set (
103
- 'X-RateLimit-Reset' ,
104
- Math . ceil ( resetTime . getTime ( ) / 1000 ) . toString ( ) ,
105
- )
106
- response . headers . set ( 'X-RateLimit-Used' , totalHits . toString ( ) )
107
- }
108
- return response
109
- }
110
-
111
118
if ( totalHits > max ) {
112
119
let response
113
120
@@ -121,7 +128,7 @@ function createRateLimit(options = {}) {
121
128
}
122
129
}
123
130
124
- return createResponse ( response )
131
+ return addRateLimitHeaders ( response , totalHits , resetTime )
125
132
}
126
133
127
134
// Set rate limit context
@@ -143,7 +150,7 @@ function createRateLimit(options = {}) {
143
150
144
151
const response = await next ( )
145
152
if ( response instanceof Response ) {
146
- return createResponse ( response )
153
+ return addRateLimitHeaders ( response , totalHits , resetTime )
147
154
}
148
155
return response
149
156
} catch ( error ) {
@@ -173,7 +180,7 @@ function createRateLimit(options = {}) {
173
180
174
181
const response = await next ( )
175
182
if ( response instanceof Response ) {
176
- return response
183
+ return addRateLimitHeaders ( response , totalHits , resetTime )
177
184
}
178
185
return response
179
186
} catch ( e ) {
0 commit comments