Here's a modular, type-safe implementation of cachify-function:
// types.ts
export interface CachifyOptions {
max_age: number;
max_age_auto_invalidate?: number | false;
suppress_stale_revalidate_errors?: boolean;
}
export interface CacheEntry<T> {
value: T;
timestamp: number;
invalidateTimeout?: NodeJS.Timeout | number;
}
export interface CachifyFunctionContext<TFunc extends (...args: any[]) => any> {
func: TFunc;
options: Required<CachifyOptions>;
cache: Map<string, CacheEntry<Awaited<ReturnType<TFunc>>>>;
inflight: Map<string, Promise<Awaited<ReturnType<TFunc>>>>;
}
// utils.ts
export function createCacheKey(args: any[]): string {
return JSON.stringify(args);
}
export function isExpired(entry: CacheEntry<any>, maxAge: number): boolean {
return Date.now() - entry.timestamp > maxAge;
}
export function isStale(entry: CacheEntry<any>, maxAge: number, maxAgeAutoInvalidate: number | false): boolean {
if (maxAgeAutoInvalidate === false || maxAgeAutoInvalidate === 0) {
return false;
}
return Date.now() - entry.timestamp > maxAgeAutoInvalidate;
}
// cachify.ts
export function cachify<TFunc extends (...args: any[]) => any>(
func: TFunc,
options: CachifyOptions
): CachifyFunctionContext<TFunc> {
const maxAgeAutoInvalidate = options.max_age_auto_invalidate ?? options.max_age * 1.5;
if (maxAgeAutoInvalidate !== false && maxAgeAutoInvalidate !== 0 && maxAgeAutoInvalidate < options.max_age) {
throw new Error('max_age_auto_invalidate must be greater than or equal to max_age');
}
return {
func,
options: {
max_age: options.max_age,
max_age_auto_invalidate: maxAgeAutoInvalidate,
suppress_stale_revalidate_errors: options.suppress_stale_revalidate_errors ?? true
},
cache: new Map(),
inflight: new Map()
};
}
// run-cache.ts
export async function runCache<TFunc extends (...args: any[]) => any>(
cfc: CachifyFunctionContext<TFunc>,
...args: Parameters<TFunc>
): Promise<Awaited<ReturnType<TFunc>>> {
const key = createCacheKey(args);
const inflightPromise = cfc.inflight.get(key);
if (inflightPromise) {
return inflightPromise;
}
const entry = cfc.cache.get(key);
if (entry && !isExpired(entry, cfc.options.max_age)) {
return entry.value;
}
return runFresh(cfc, ...args);
}
// run-stale.ts
export async function runStale<TFunc extends (...args: any[]) => any>(
cfc: CachifyFunctionContext<TFunc>,
...args: Parameters<TFunc>
): Promise<Awaited<ReturnType<TFunc>>> {
const key = createCacheKey(args);
const inflightPromise = cfc.inflight.get(key);
if (inflightPromise) {
return inflightPromise;
}
const entry = cfc.cache.get(key);
if (!entry) {
throw new Error('No cached value available');
}
if (isExpired(entry, cfc.options.max_age)) {
runFresh(cfc, ...args).catch(err => {
if (!cfc.options.suppress_stale_revalidate_errors) {
throw err;
}
});
}
return entry.value;
}
// run-fresh.ts
export async function runFresh<TFunc extends (...args: any[]) => any>(
cfc: CachifyFunctionContext<TFunc>,
...args: Parameters<TFunc>
): Promise<Awaited<ReturnType<TFunc>>> {
const key = createCacheKey(args);
const promise = Promise.resolve(cfc.func(...args));
cfc.inflight.set(key, promise);
try {
const value = await promise;
const entry = cfc.cache.get(key);
if (entry?.invalidateTimeout) {
clearTimeout(entry.invalidateTimeout);
}
const newEntry: CacheEntry<Awaited<ReturnType<TFunc>>> = {
value,
timestamp: Date.now()
};
if (cfc.options.max_age_auto_invalidate !== false && cfc.options.max_age_auto_invalidate !== 0) {
newEntry.invalidateTimeout = setTimeout(() => {
cfc.cache.delete(key);
}, cfc.options.max_age_auto_invalidate);
}
cfc.cache.set(key, newEntry);
return value;
} catch (error) {
throw error;
} finally {
cfc.inflight.delete(key);
}
}
// run-fresh-cached.ts
export async function runFreshCached<TFunc extends (...args: any[]) => any>(
cfc: CachifyFunctionContext<TFunc>,
...args: Parameters<TFunc>
): Promise<Awaited<ReturnType<TFunc>>> {
const key = createCacheKey(args);
const inflightPromise = cfc.inflight.get(key);
if (inflightPromise) {
return inflightPromise;
}
return runFresh(cfc, ...args);
}
// invalidate.ts
export function invalidate<TFunc extends (...args: any[]) => any>(
cfc: CachifyFunctionContext<TFunc>,
...args: Parameters<TFunc>
): void {
const key = createCacheKey(args);
const entry = cfc.cache.get(key);
if (entry?.invalidateTimeout) {
clearTimeout(entry.invalidateTimeout);
}
cfc.cache.delete(key);
}
export function invalidateAll<TFunc extends (...args: any[]) => any>(
cfc: CachifyFunctionContext<TFunc>
): void {
for (const [, entry] of cfc.cache) {
if (entry.invalidateTimeout) {
clearTimeout(entry.invalidateTimeout);
}
}
cfc.cache.clear();
}
// index.ts
export { cachify } from './cachify';
export { runCache } from './run-cache';
export { runStale } from './run-stale';
export { runFresh } from './run-fresh';
export { runFreshCached } from './run-fresh-cached';
export { invalidate, invalidateAll } from './invalidate';
export type { CachifyOptions, CachifyFunctionContext } from './types';