Skip to content

Commit

Permalink
add tests
Browse files Browse the repository at this point in the history
Signed-off-by: flakey5 <[email protected]>
  • Loading branch information
flakey5 committed Nov 2, 2024
1 parent 19b4339 commit d034c54
Show file tree
Hide file tree
Showing 2 changed files with 364 additions and 8 deletions.
20 changes: 12 additions & 8 deletions lib/interceptor/cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,12 @@ function needsRevalidation (now, value, age, cacheControlDirectives) {

if (cacheControlDirectives?.['min-fresh']) {
// https://www.rfc-editor.org/rfc/rfc9111.html#section-5.2.1.3
const gracePeriod = age + (cacheControlDirectives['min-fresh'] * 1000)
return (now - value.staleAt) > gracePeriod

// At this point, staleAt is always > now
const timeLeftTillStale = value.staleAt - now
const threshold = cacheControlDirectives['min-fresh'] * 1000

return timeLeftTillStale <= threshold
}

return false
Expand Down Expand Up @@ -121,16 +125,19 @@ module.exports = (opts = {}) => {
return dispatch(opts, new CacheHandler(globalOpts, opts, handler))
}

let onErrorCalled = false
const now = Date.now()

/**
* @param {import('../../types/cache-interceptor.d.ts').default.CacheStoreReadable} stream
* @param {import('../../types/cache-interceptor.d.ts').default.CacheStoreValue} value
* @param {number} age
*/
const respondWithCachedValue = (stream, value) => {
const respondWithCachedValue = (stream, value, age) => {
const ac = new AbortController()
const signal = ac.signal

let onErrorCalled = false

signal.onabort = (_, err) => {
stream.destroy()
if (!onErrorCalled) {
Expand All @@ -155,8 +162,6 @@ module.exports = (opts = {}) => {
if (typeof handler.onHeaders === 'function') {
// Add the age header
// https://www.rfc-editor.org/rfc/rfc9111.html#name-age
const age = Math.round((Date.now() - value.cachedAt) / 1000)

value.rawHeaders.push(AGE_HEADER, Buffer.from(`${age}`))

handler.onHeaders(value.statusCode, value.rawHeaders, stream.resume, value.statusMessage)
Expand Down Expand Up @@ -211,7 +216,6 @@ module.exports = (opts = {}) => {

const { value } = stream

const now = Date.now()
const age = Math.round((now - value.cachedAt) / 1000)
if (requestCacheControl?.['max-age'] && age >= requestCacheControl['max-age']) {
// Response is considered expired for this specific request
Expand Down Expand Up @@ -252,7 +256,7 @@ module.exports = (opts = {}) => {
return
}

respondWithCachedValue(stream, value)
respondWithCachedValue(stream, value, age)
}

Promise.resolve(stream).then(handleStream).catch(handler.onError)
Expand Down
Loading

0 comments on commit d034c54

Please sign in to comment.