api/src/lib/cache/memory.ts

22 lines · 665 bytes

 1/* In-process Map storage cache for Node/Bun */
 2import type { Storage, StoredEntry } from '@/lib/cache'
 3import { wrapFetch } from '@/lib/cache'
 4
 5const store = new Map<string, StoredEntry>()
 6
 7export const memoryStorage = (): Storage => {
 8  const storage: Storage = {
 9    async get<T>(key: string) {
10      return (store.get(key) as StoredEntry<T>) ?? null
11    },
12    async set<T>(key: string, value: T) {
13      // Kept indefinitely, freshness is decided by the caller not by expiry
14      store.set(key, { value, cachedAt: Date.now() })
15    },
16    fetch: async () => {
17      throw new Error('uninit')
18    },
19  }
20  storage.fetch = wrapFetch(storage)
21  return storage
22}