From 900bb5e845c3ad44defbd427cae3d44a4a43321f Mon Sep 17 00:00:00 2001 From: ivarlovlie Date: Sat, 25 Feb 2023 13:15:44 +0100 Subject: feat: Initial commit --- code/app/src/utilities/cache.ts | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 code/app/src/utilities/cache.ts (limited to 'code/app/src/utilities/cache.ts') diff --git a/code/app/src/utilities/cache.ts b/code/app/src/utilities/cache.ts new file mode 100644 index 0000000..db9be9a --- /dev/null +++ b/code/app/src/utilities/cache.ts @@ -0,0 +1,38 @@ +import { Temporal } from "temporal-polyfill"; +import { log_debug } from "$utilities/logger"; + +let cache = {}; + +export const CacheKeys = { + isAuthenticated: "isAuthenticated" +} + +export async function cached_result_async(key: string, staleAfterSeconds: number, get_result: any, forceRefresh: boolean = false) { + if (!cache[key]) { + cache[key] = { + l: 0, + c: undefined as T, + }; + } + const staleEpoch = ((cache[key]?.l ?? 0) + staleAfterSeconds); + const isStale = forceRefresh || (staleEpoch < Temporal.Now.instant().epochSeconds); + if (isStale || !cache[key]?.c) { + cache[key].c = typeof get_result === "function" ? await get_result() : get_result; + cache[key].l = Temporal.Now.instant().epochSeconds; + } + + log_debug("Ran cached_result_async", { + cacheKey: key, + isStale, + cache: cache[key], + staleEpoch, + }); + + return cache[key].c as T; +} + +export function clear_cache_key(key: string) { + if (!key) throw new Error("No key was specified"); + cache[key].c = undefined; + log_debug("Cleared cache with key: " + key); +} \ No newline at end of file -- cgit v1.3