diff --git a/docs/content/1.guide/1.introduction/5.cache.md b/docs/content/1.guide/1.introduction/5.cache.md index 97e5165799..0dcb02e8e7 100644 --- a/docs/content/1.guide/1.introduction/5.cache.md +++ b/docs/content/1.guide/1.introduction/5.cache.md @@ -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 diff --git a/examples/cached-handler/routes/index.ts b/examples/cached-handler/routes/index.ts index 235e8977e0..5c82c013af 100644 --- a/examples/cached-handler/routes/index.ts +++ b/examples/cached-handler/routes/index.ts @@ -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") }); diff --git a/src/runtime/cache.ts b/src/runtime/cache.ts index 83160c21c6..850f452333 100644 --- a/src/runtime/cache.ts +++ b/src/runtime/cache.ts @@ -22,6 +22,7 @@ export interface CacheOptions { transform?: (entry: CacheEntry, ...args: any[]) => any; validate?: (entry: CacheEntry) => boolean; shouldInvalidateCache?: (...args: any[]) => boolean; + shouldBypassCache?: (...args: any[]) => boolean; group?: string; integrity?: any; maxAge?: number; @@ -117,6 +118,10 @@ export function defineCachedFunction( } 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); @@ -143,6 +148,7 @@ export interface ResponseCacheEntry { export interface CachedEventHandlerOptions extends Omit>, "transform" | "validate"> { shouldInvalidateCache?: (event: H3Event) => boolean; + shouldBypassCache?: (event: H3Event) => boolean; getKey?: (event: H3Event) => string; headersOnly?: boolean; }