@@ -61,8 +61,12 @@ function needsRevalidation (now, value, age, cacheControlDirectives) {
61
61
62
62
if ( cacheControlDirectives ?. [ 'min-fresh' ] ) {
63
63
// https://www.rfc-editor.org/rfc/rfc9111.html#section-5.2.1.3
64
- const gracePeriod = age + ( cacheControlDirectives [ 'min-fresh' ] * 1000 )
65
- return ( now - value . staleAt ) > gracePeriod
64
+
65
+ // At this point, staleAt is always > now
66
+ const timeLeftTillStale = value . staleAt - now
67
+ const threshold = cacheControlDirectives [ 'min-fresh' ] * 1000
68
+
69
+ return timeLeftTillStale <= threshold
66
70
}
67
71
68
72
return false
@@ -119,16 +123,19 @@ module.exports = (opts = {}) => {
119
123
return dispatch ( opts , new CacheHandler ( globalOpts , opts , handler ) )
120
124
}
121
125
122
- let onErrorCalled = false
126
+ const now = Date . now ( )
123
127
124
128
/**
125
129
* @param {import('../../types/cache-interceptor.d.ts').default.CacheStoreReadable } stream
126
130
* @param {import('../../types/cache-interceptor.d.ts').default.CacheStoreValue } value
131
+ * @param {number } age
127
132
*/
128
- const respondWithCachedValue = ( stream , value ) => {
133
+ const respondWithCachedValue = ( stream , value , age ) => {
129
134
const ac = new AbortController ( )
130
135
const signal = ac . signal
131
136
137
+ let onErrorCalled = false
138
+
132
139
signal . onabort = ( _ , err ) => {
133
140
stream . destroy ( )
134
141
if ( ! onErrorCalled ) {
@@ -153,8 +160,6 @@ module.exports = (opts = {}) => {
153
160
if ( typeof handler . onHeaders === 'function' ) {
154
161
// Add the age header
155
162
// https://www.rfc-editor.org/rfc/rfc9111.html#name-age
156
- const age = Math . round ( ( Date . now ( ) - value . cachedAt ) / 1000 )
157
-
158
163
value . rawHeaders . push ( AGE_HEADER , Buffer . from ( `${ age } ` ) )
159
164
160
165
handler . onHeaders ( value . statusCode , value . rawHeaders , stream . resume , value . statusMessage )
@@ -209,7 +214,6 @@ module.exports = (opts = {}) => {
209
214
210
215
const { value } = stream
211
216
212
- const now = Date . now ( )
213
217
const age = Math . round ( ( now - value . cachedAt ) / 1000 )
214
218
if ( requestCacheControl ?. [ 'max-age' ] && age >= requestCacheControl [ 'max-age' ] ) {
215
219
// Response is considered expired for this specific request
@@ -250,7 +254,7 @@ module.exports = (opts = {}) => {
250
254
return
251
255
}
252
256
253
- respondWithCachedValue ( stream , value )
257
+ respondWithCachedValue ( stream , value , age )
254
258
}
255
259
256
260
Promise . resolve ( stream ) . then ( handleStream ) . catch ( handler . onError )
0 commit comments