Skip to content

Commit

Permalink
WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
ronag committed Nov 6, 2024
1 parent 74c1599 commit 5cb8b0c
Showing 1 changed file with 40 additions and 27 deletions.
67 changes: 40 additions & 27 deletions lib/interceptor/cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,46 +108,59 @@ module.exports = (opts = {}) => {
*/
const handleStream = (stream) => {
if (!stream) {
// Request isn't cached
return dispatch(opts, new CacheHandler(globalOpts, opts, handler))
}

assert(util.isStream(stream))

// TODO (fix): It's weird that "value" lives on stream.
const { value } = stream

// Dump body if cached...
// TODO (fix): This is a bit suspect.
if (util.isStream(opts.body)) {
opts.body?.on('error', () => {}).resume()
}

// Check if the response is stale
const now = Date.now()
if (now >= value.staleAt) {
if (now < value.staleAt) {
// Dump body.
if (util.isStream(opts.body)) {
opts.body.on('error', () => {}).resume()
}
respondWithCachedValue(stream, value)
} else if (util.isStream(opts.body) && util.bodyLength(opts.body) !== 0) {
// If body is is stream we can't revalidate...
// TODO (fix): This could be less strict...
dispatch(opts, new CacheHandler(globalOpts, opts, handler))
} else {
// Need to revalidate the response
return dispatch(
{
...opts,
headers: {
...opts.headers,
'if-modified-since': new Date(value.cachedAt).toUTCString()
}
},
new CacheRevalidationHandler(
() => respondWithCachedValue(stream, value),
new CacheHandler(globalOpts, opts, handler)
try {
return dispatch(
{
...opts,
headers: {
...opts.headers,
'if-modified-since': new Date(value.cachedAt).toUTCString()
}
},
new CacheRevalidationHandler(
() => respondWithCachedValue(stream, value),
new CacheHandler(globalOpts, opts, handler)
)
)
)
} catch (err) {
if (typeof handler.onError === 'function') {
handler.onError(err)
}
}
}

respondWithCachedValue(stream, value)
}

Promise.resolve(stream).then(handleStream, err => {
if (typeof handler.onError === 'function') {
handler.onError(err)
}
})
if (util.isStream(stream)) {
handleStream(stream)
} else {
Promise.resolve(stream).then(handleStream, err => {
if (typeof handler.onError === 'function') {
handler.onError(err)
}
})
}

return true
}
Expand Down

0 comments on commit 5cb8b0c

Please sign in to comment.