diff --git a/lib/interceptor/cache.js b/lib/interceptor/cache.js index 4087d38bae3..2a80d529c69 100644 --- a/lib/interceptor/cache.js +++ b/lib/interceptor/cache.js @@ -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 }