import {Cache, FlexStorage} from "../types.js" export function storageCache({ storage, lifespan, storageKey, load, }: { lifespan: number storageKey: string storage: FlexStorage load: () => Promise }) { async function getValidCache(): Promise> { let valid = false const cache = await storage.read>(storageKey) if (cache) { const since = Date.now() - cache.time const alive = since < lifespan if (alive) valid = true } return valid ? cache : undefined } async function loadFreshAndWriteCache() { const data = await load() const time = Date.now() await storage.write>(storageKey, {data, time}) return data } return { async read(): Promise { const cache = await getValidCache() return cache ? cache.data : loadFreshAndWriteCache() }, async readFresh(): Promise { return loadFreshAndWriteCache() }, async readCached(): Promise { const cache = await getValidCache() return cache?.data }, async clear(): Promise { await storage.write>(storageKey, undefined) }, async write(data: xData, time = Date.now()) { await storage.write>(storageKey, {data, time}) }, } }