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 4f6d4cb
Showing 1 changed file with 23 additions and 14 deletions.
37 changes: 23 additions & 14 deletions lib/interceptor/cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,24 +106,31 @@ module.exports = (opts = {}) => {
/**
* @param {import('../../types/cache-interceptor.d.ts').default.CacheStoreReadable | undefined} stream
*/
// TODO (fix): Make sure handleStream doesn't throw!
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(
{
Expand All @@ -139,15 +146,17 @@ module.exports = (opts = {}) => {
)
)
}

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 4f6d4cb

Please sign in to comment.