~james/core

core/web/src/lib/api/cache.ts -rw-r--r-- 709 bytes
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 15 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import { browser } from "$app/env";

type Entry = { value: unknown; expires: number };
const store = new Map<string, Entry>();

// browser only, a server map would leak viewer-scoped data across requests
export async function cached<T>(key: string, ttlMs: number, fn: () => Promise<T>): Promise<T> {
	if (!browser) return fn();
	const hit = store.get(key);
	if (hit && hit.expires > Date.now()) return hit.value as T;
	try {
		const value = await fn();
		store.set(key, { value, expires: Date.now() + ttlMs });
		return value;
	} catch (cause) {
		store.delete(key);
		throw cause;
	}
}

export function invalidate(key: string): void {
	store.delete(key);
}

export function clear(): void {
	store.clear();
}