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

feat: add shouldInvalidateCache option to cache utils #746

Merged
merged 6 commits into from
Jan 16, 2023
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
fix: add h3event param
  • Loading branch information
yassilah committed Dec 10, 2022
commit da79e5ba468fcfe461357a4128efa7182392aba0
11 changes: 7 additions & 4 deletions src/runtime/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export interface CacheOptions<T = any> {
getKey?: (...args: any[]) => string;
transform?: (entry: CacheEntry<T>, ...args: any[]) => any;
validate?: (entry: CacheEntry<T>) => boolean;
refresh?: () => boolean;
refresh?: (...args: any[]) => boolean;
group?: string;
integrity?: any;
maxAge?: number;
Expand Down Expand Up @@ -54,7 +54,8 @@ export function defineCachedFunction<T = any>(

async function get(
key: string,
resolver: () => T | Promise<T>
resolver: () => T | Promise<T>,
refresh?: boolean
): Promise<CacheEntry<T>> {
// Use extension for key to avoid conflicting with parent namespace (foo/bar and foo/bar/baz)
const cacheKey = [opts.base, group, name, key + ".json"]
Expand All @@ -70,7 +71,7 @@ export function defineCachedFunction<T = any>(
}

const expired =
opts.refresh?.() ||
refresh ||
pi0 marked this conversation as resolved.
Show resolved Hide resolved
entry.integrity !== integrity ||
(ttl && Date.now() - (entry.mtime || 0) > ttl) ||
!validate(entry);
Expand Down Expand Up @@ -109,7 +110,8 @@ export function defineCachedFunction<T = any>(

return async (...args) => {
const key = (opts.getKey || getKey)(...args);
const entry = await get(key, () => fn(...args));
const refresh = opts.refresh?.(...args);
const entry = await get(key, () => fn(...args), refresh);
let value = entry.value;
if (opts.transform) {
value = (await opts.transform(entry, ...args)) || value;
Expand All @@ -135,6 +137,7 @@ export interface CachedEventHandlerOptions<T = any>
CacheOptions<ResponseCacheEntry<T>>,
"getKey" | "transform" | "validate"
> {
refresh?: (event: H3Event) => boolean;
headersOnly?: boolean;
}

Expand Down