Skip to content

Commit

Permalink
feat: add shouldBypassCache option to cache utils (#874)
Browse files Browse the repository at this point in the history
  • Loading branch information
MiniDigger authored Jan 25, 2023
1 parent 5f142cc commit f5a5a8e
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 0 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 @@ -20,6 +20,7 @@ const cachedFn = cachedEventHandler(fn, options);
- `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.
- `shouldBypassCache`: A function that returns a boolean to bypass the current cache without invalidating the existing entry.

## Examples

Expand Down
2 changes: 2 additions & 0 deletions examples/cached-handler/routes/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
export default defineCachedEventHandler(async () => {
await new Promise((resolve) => setTimeout(resolve, 1000));
return `Response generated at ${new Date().toISOString()} (took 1 second)`;
}, {
shouldBypassCache: (e) => e.node.req.url.includes("preview")
});
6 changes: 6 additions & 0 deletions src/runtime/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export interface CacheOptions<T = any> {
transform?: (entry: CacheEntry<T>, ...args: any[]) => any;
validate?: (entry: CacheEntry<T>) => boolean;
shouldInvalidateCache?: (...args: any[]) => boolean;
shouldBypassCache?: (...args: any[]) => boolean;
group?: string;
integrity?: any;
maxAge?: number;
Expand Down Expand Up @@ -117,6 +118,10 @@ export function defineCachedFunction<T = any>(
}

return async (...args) => {
const shouldBypassCache = opts.shouldBypassCache?.(...args);
if (shouldBypassCache) {
return fn(...args);
}
const key = (opts.getKey || getKey)(...args);
const shouldInvalidateCache = opts.shouldInvalidateCache?.(...args);
const entry = await get(key, () => fn(...args), shouldInvalidateCache);
Expand All @@ -143,6 +148,7 @@ export interface ResponseCacheEntry<T = any> {
export interface CachedEventHandlerOptions<T = any>
extends Omit<CacheOptions<ResponseCacheEntry<T>>, "transform" | "validate"> {
shouldInvalidateCache?: (event: H3Event) => boolean;
shouldBypassCache?: (event: H3Event) => boolean;
getKey?: (event: H3Event) => string;
headersOnly?: boolean;
}
Expand Down

0 comments on commit f5a5a8e

Please sign in to comment.