api/src/lib/cache/kv.ts
23 lines · 672 bytes
1 symbol in this file
1/* Workers KV backed Storage */
2import type { Storage, StoredEntry } from '@/lib/cache'
3import { wrapFetch } from '@/lib/cache'
4
5export const kvStorage = (kv: KVNamespace): Storage => {
6 const storage: Storage = {
7 async get<T>(key: string) {
8 return (await kv.get<StoredEntry<T>>(key, 'json')) ?? null
9 },
10 async set<T>(key: string, value: T) {
11 // No expirationTtl, entries are kept indefinitely
12 await kv.put(
13 key,
14 JSON.stringify({ value, cachedAt: Date.now() } satisfies StoredEntry<T>),
15 )
16 },
17 fetch: async () => {
18 throw new Error('uninit')
19 },
20 }
21 storage.fetch = wrapFetch(storage)
22 return storage
23}