Skip to content

Commit a0b52e3

Browse files
committed
add tests
Signed-off-by: flakey5 <[email protected]>
1 parent cf3396c commit a0b52e3

File tree

2 files changed

+365
-9
lines changed

2 files changed

+365
-9
lines changed

lib/interceptor/cache.js

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,12 @@ function needsRevalidation (now, value, age, cacheControlDirectives) {
6161

6262
if (cacheControlDirectives?.['min-fresh']) {
6363
// 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
6670
}
6771

6872
return false
@@ -119,16 +123,19 @@ module.exports = (opts = {}) => {
119123
return dispatch(opts, new CacheHandler(globalOpts, opts, handler))
120124
}
121125

122-
let onErrorCalled = false
126+
const now = Date.now()
123127

124128
/**
125129
* @param {import('../../types/cache-interceptor.d.ts').default.CacheStoreReadable} stream
126130
* @param {import('../../types/cache-interceptor.d.ts').default.CacheStoreValue} value
131+
* @param {number} age
127132
*/
128-
const respondWithCachedValue = (stream, value) => {
133+
const respondWithCachedValue = (stream, value, age) => {
129134
const ac = new AbortController()
130135
const signal = ac.signal
131136

137+
let onErrorCalled = false
138+
132139
signal.onabort = (_, err) => {
133140
stream.destroy()
134141
if (!onErrorCalled) {
@@ -153,8 +160,6 @@ module.exports = (opts = {}) => {
153160
if (typeof handler.onHeaders === 'function') {
154161
// Add the age header
155162
// https://www.rfc-editor.org/rfc/rfc9111.html#name-age
156-
const age = Math.round((Date.now() - value.cachedAt) / 1000)
157-
158163
value.rawHeaders.push(AGE_HEADER, Buffer.from(`${age}`))
159164

160165
handler.onHeaders(value.statusCode, value.rawHeaders, stream.resume, value.statusMessage)
@@ -209,7 +214,6 @@ module.exports = (opts = {}) => {
209214

210215
const { value } = stream
211216

212-
const now = Date.now()
213217
const age = Math.round((now - value.cachedAt) / 1000)
214218
if (requestCacheControl?.['max-age'] && age >= requestCacheControl['max-age']) {
215219
// Response is considered expired for this specific request
@@ -250,7 +254,7 @@ module.exports = (opts = {}) => {
250254
return
251255
}
252256

253-
respondWithCachedValue(stream, value)
257+
respondWithCachedValue(stream, value, age)
254258
}
255259

256260
Promise.resolve(stream).then(handleStream).catch(handler.onError)

0 commit comments

Comments
 (0)