aboutsummaryrefslogtreecommitdiffstats
path: root/code/app/src/utilities/cache.ts
blob: 101f192c89843d606a75545eab72bccc2d46577c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import {Temporal} from "temporal-polyfill";

let cache = {};

export const CacheKeys = {
    isAuthenticated: "isAuthenticated",
};

export async function cached_result_async<T>(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;
    }

    console.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;
    console.debug("Cleared cache with key: " + key);
}