All files / src/models createCache.ts

91.67% Statements 11/12
100% Branches 2/2
66.67% Functions 2/3
91.67% Lines 11/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                      4x 2x   2x 3x 3x 1x   2x 2x 2x     2x       2x          
/*!
 * Copyright 2020 Cognite AS
 */
 
type RequestDelegate<T_ID, T> = (id: T_ID) => Promise<T>;
 
interface SimpleCache<T_ID, T> {
  request: RequestDelegate<T_ID, T>;
  clearCache: () => void;
}
 
export function createSimpleCache<T_ID, T>(request: RequestDelegate<T_ID, T>): SimpleCache<T_ID, T> {
  const results = new Map<T_ID, Promise<T>>();
 
  const requestCached = async (id: T_ID) => {
    const existing = results.get(id);
    if (existing) {
      return existing;
    }
    const result: Promise<T> = request(id);
    results.set(id, result);
    return result;
  };
 
  const clearCache = () => {
    results.clear();
  };
 
  return {
    request: requestCached,
    clearCache
  };
}