From b5ed021b6ba1dcfaf3162a5e1f686187c209a815 Mon Sep 17 00:00:00 2001 From: mat Date: Tue, 17 May 2022 22:39:57 -0500 Subject: improve caching logic --- src/util.ts | 50 +++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 49 insertions(+), 1 deletion(-) (limited to 'src/util.ts') diff --git a/src/util.ts b/src/util.ts index 91f202d..9af95c7 100644 --- a/src/util.ts +++ b/src/util.ts @@ -103,4 +103,52 @@ export type RecursivePartial = { T[P] extends (infer U)[] ? RecursivePartial[] : T[P] extends object ? RecursivePartial : T[P] -} \ No newline at end of file +} + +let caches: Map = new Map() + +export async function withCache(key: string, ttl: number | ((arg: T) => Date), task: () => Promise): Promise { + if (caches.get(key)?.data && caches.get(key)!.nextUpdate > new Date()) + return caches.get(key)!.data + + // if it's currently fetching the election data and it doesn't have it, + // wait until we do have the election data + if (caches.get(key)?.isFetching && !caches.get(key)?.data) { + await new Promise(resolve => { + const interval = setInterval(() => { + if (caches.get(key)?.data) { + clearInterval(interval) + resolve(caches.get(key)!.data) + } + }, 100) + }) + } + + caches.set(key, { + ...(caches.get(key) ?? { data: undefined, nextUpdate: new Date(0) }), + isFetching: true, + }) + const data = await task() + caches.set(key, { + ...caches.get(key)!, + isFetching: false, + }) + if (!data) return undefined as any + + caches.set(key, { + ...caches.get(key)!, + data + }) + + const nextUpdate = typeof ttl === 'number' ? new Date(Date.now() + ttl) : ttl(data) + + caches.set(key, { + ...caches.get(key)!, + nextUpdate + }) + return data +} -- cgit