1 import { defaultExpiry, getFetchedEphemeral as defaultGetFetchedEphemeral, isNotStale } from './fetchedAt';
2 import { CacheType, type ReducerValue } from './interface';
4 const context: { cache?: CacheType; fetchedEphemeral: ReturnType<typeof defaultGetFetchedEphemeral> } = {
5 cache: CacheType.StaleRefetch,
6 fetchedEphemeral: defaultGetFetchedEphemeral(),
9 export const configureCache = ({
10 cache = CacheType.StaleRefetch,
11 getFetchedEphemeral = defaultGetFetchedEphemeral,
14 getFetchedEphemeral?: typeof defaultGetFetchedEphemeral;
16 context.cache = cache;
17 context.fetchedEphemeral = getFetchedEphemeral();
20 export const getIsStaleRefetch = (
21 fetchedEphemeral: ReturnType<typeof defaultGetFetchedEphemeral> | undefined,
24 return cache === CacheType.StaleRefetch && fetchedEphemeral !== context.fetchedEphemeral;
27 export const cacheHelper = <Returned>({
32 cache = context.cache,
33 expiry = defaultExpiry,
36 get: (key: string) => Promise<Returned> | undefined;
37 set: (key: string, promise: Promise<Returned>) => void;
40 select: () => ReducerValue<Returned> | undefined;
41 cb: () => Promise<Returned>;
44 }): Promise<Returned> => {
45 const promise = store.get(key);
49 if (cache === CacheType.Stale || cache === CacheType.StaleRefetch) {
50 const state = select();
51 if (state && state.value !== undefined && isNotStale(state.meta.fetchedAt, expiry)) {
52 if (getIsStaleRefetch(state.meta.fetchedEphemeral, cache)) {
53 const newPromise = cb();
54 store.set(key, newPromise);
56 return Promise.resolve(state.value);
59 const newPromise = cb();
60 store.set(key, newPromise);
64 export const createPromiseStore = <Returned>() => {
65 let promise: Promise<Returned> | undefined = undefined;
67 const set = (key: string, newPromise: Promise<Returned>) => {
76 const get = () => promise;
81 export const createPromiseMapStore = <Returned>() => {
82 const map = new Map<string, Promise<Returned>>();
84 const set = (id: string, newPromise: Promise<Returned>) => {
85 map.set(id, newPromise);
93 const get = (id: string) => map.get(id);