const CACHE_DO_NAME = 'cachev1' export interface Cache { get(key: string): Promise put(key: string, value: T): Promise } export function cacheFromEnv(env: any): Cache { return { async get(key: string): Promise { const id = env.DO_CACHE.idFromName(CACHE_DO_NAME) const stub = env.DO_CACHE.get(id) const res = await stub.fetch('http://cache/' + key) if (!res.ok) { throw new Error(`DO cache returned ${res.status}: ${await res.text()}`) } return (await res.json()) as T }, async put(key: string, value: T): Promise { const id = env.DO_CACHE.idFromName(CACHE_DO_NAME) const stub = env.DO_CACHE.get(id) const res = await stub.fetch('http://cache/', { method: 'PUT', body: JSON.stringify({ key, value }), }) if (!res.ok) { throw new Error(`DO cache returned ${res.status}: ${await res.text()}`) } }, } }