|
| 1 | +type CacheEntry<Value> = { |
| 2 | + metadata: { |
| 3 | + createdTime: number |
| 4 | + ttl?: number | null |
| 5 | + swr?: number | null |
| 6 | + } |
| 7 | + value: Value |
| 8 | +} |
| 9 | + |
| 10 | +const lruStore = new Map<string, CacheEntry<unknown>>() |
| 11 | +const sqliteStore = new Map<string, CacheEntry<unknown>>() |
| 12 | + |
| 13 | +export const lruCache = { |
| 14 | + name: 'test-lru-cache', |
| 15 | + set: (key: string, value: CacheEntry<unknown>) => { |
| 16 | + lruStore.set(key, value) |
| 17 | + return value |
| 18 | + }, |
| 19 | + get: (key: string) => lruStore.get(key), |
| 20 | + delete: (key: string) => lruStore.delete(key), |
| 21 | +} |
| 22 | + |
| 23 | +export const cache = { |
| 24 | + name: 'test-sqlite-cache', |
| 25 | + async get(key: string) { |
| 26 | + return sqliteStore.get(key) ?? null |
| 27 | + }, |
| 28 | + async set(key: string, entry: CacheEntry<unknown>) { |
| 29 | + sqliteStore.set(key, entry) |
| 30 | + return entry |
| 31 | + }, |
| 32 | + async delete(key: string) { |
| 33 | + sqliteStore.delete(key) |
| 34 | + }, |
| 35 | +} |
| 36 | + |
| 37 | +export async function getAllCacheKeys(limit: number) { |
| 38 | + const sqlite = [...sqliteStore.keys()].slice(0, limit) |
| 39 | + const lru = [...lruStore.keys()].slice(0, limit) |
| 40 | + return { sqlite, lru } |
| 41 | +} |
| 42 | + |
| 43 | +export async function searchCacheKeys(search: string, limit: number) { |
| 44 | + const matches = (value: string) => value.includes(search) |
| 45 | + const sqlite = [...sqliteStore.keys()].filter(matches).slice(0, limit) |
| 46 | + const lru = [...lruStore.keys()].filter(matches).slice(0, limit) |
| 47 | + return { sqlite, lru } |
| 48 | +} |
| 49 | + |
| 50 | +export async function cachified<Value>( |
| 51 | + options: { |
| 52 | + getFreshValue: () => Promise<Value> | Value |
| 53 | + }, |
| 54 | +): Promise<Value> { |
| 55 | + return options.getFreshValue() |
| 56 | +} |
0 commit comments