Skip to content

Commit

Permalink
feat: support staleMaxAge: -1 to always respond stale value (#857)
Browse files Browse the repository at this point in the history
  • Loading branch information
yassilah authored Jan 20, 2023
1 parent a52c832 commit 456f82a
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 5 deletions.
1 change: 1 addition & 0 deletions docs/content/1.guide/1.introduction/5.cache.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const cachedFn = cachedEventHandler(fn, options);
- `getKey`: A function that accepts same arguments of normal function and should generate cache key. If not provided, a built-in hash function will be used.
- `integrity`: A value that changing it, will invalidate all caches for function. By default will be computed from **function code**.
- `maxAge`: Maximum age that cache is valid in seconds. Default is `1` second.
- `staleMaxAge`: Maximum age that a stale cache is valid in seconds. If set to `-1` a stale value will still be sent to the client, while updating the cache in the background.
- `swr`: Enable Stale-While-Revalidate behavior. Enabled by default.
- `base`: Name of the storage mointpoint to use for caching (`/cache` by default)
- `shouldInvalidateCache`: A function that returns a boolean to invalidate the current cache and create a new one.
Expand Down
12 changes: 7 additions & 5 deletions src/runtime/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,11 +78,13 @@ export function defineCachedFunction<T = any>(

const _resolve = async () => {
if (!pending[key]) {
// Remove cached entry to prevent using expired cache on concurrent requests
entry.value = undefined;
entry.integrity = undefined;
entry.mtime = undefined;
entry.expires = undefined;
if (entry.value !== undefined && (opts.staleMaxAge || 0) >= 0) {
// Remove cached entry to prevent using expired cache on concurrent requests
entry.value = undefined;
entry.integrity = undefined;
entry.mtime = undefined;
entry.expires = undefined;
}
pending[key] = Promise.resolve(resolver());
}
entry.value = await pending[key];
Expand Down

0 comments on commit 456f82a

Please sign in to comment.