Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: cache #3804

Merged
merged 17 commits into from
Nov 6, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
WIP
  • Loading branch information
ronag committed Nov 6, 2024
commit d92b39e1f148a99ec9017b3252d225c5362410fb
52 changes: 30 additions & 22 deletions lib/interceptor/cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,12 @@ module.exports = (opts = {}) => {
try {
stream
.on('error', function (err) {
if (!this.readableEnded && typeof handler.onError === 'function') {
handler.onError(err)
if (!this.readableEnded) {
if (typeof handler.onError === 'function') {
handler.onError(err)
} else {
throw err
}
}
})
.on('close', function () {
Expand Down Expand Up @@ -116,22 +120,22 @@ module.exports = (opts = {}) => {
// TODO (fix): It's weird that "value" lives on stream.
const { value } = stream

// Check if the response is stale
const now = Date.now()
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
try {
return dispatch(
try {
// Check if the response is stale
const now = Date.now()
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
dispatch(
{
...opts,
headers: {
Expand All @@ -144,10 +148,12 @@ module.exports = (opts = {}) => {
new CacheHandler(globalOpts, opts, handler)
)
)
} catch (err) {
if (typeof handler.onError === 'function') {
handler.onError(err)
}
}
} catch (err) {
if (typeof handler.onError === 'function') {
handler.onError(err)
} else {
throw err
}
}
}
Expand All @@ -158,6 +164,8 @@ module.exports = (opts = {}) => {
Promise.resolve(stream).then(handleStream, err => {
if (typeof handler.onError === 'function') {
handler.onError(err)
} else {
throw err
}
})
}
Expand Down
Loading