All files / src/utils cache.ts

100% Statements 16/16
100% Branches 7/7
100% Functions 1/1
100% Lines 16/16

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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69                                                                                                        1x 3x 2x 2x 4x 1x 1x 3x 3x 3x 4x 2x 1x 2x 2x 1x  
/**
 * 缓存处理函数的类型定义
 *
 * @template T - 缓存数据的类型
 * @param name - 缓存项的唯一标识符
 * @param fetch - 获取数据的异步函数
 * @returns 返回缓存的数据或新获取的数据
 *
 * @example
 * ```ts
 * const cache = createCache(true);
 *
 * // 第一次调用会执行 fetch 函数
 * const data1 = await cache('key', async () => {
 *   return await fetchSomeData();
 * });
 *
 * // 第二次调用会直接返回缓存的结果
 * const data2 = await cache('key', async () => {
 *   return await fetchSomeData();
 * });
 * ```
 */
export type CacheHandle = <T>(
    name: string,
    fetch: () => Promise<T>
) => Promise<T>;
 
/**
 * 创建一个缓存处理函数
 *
 * @param enable - 是否启用缓存功能
 * @returns 返回一个缓存处理函数
 *
 * @description
 * 当 enable 为 true 时,会创建一个带有内存缓存的处理函数,相同的 name 只会执行一次 fetch。
 * 当 enable 为 false 时,每次调用都会执行 fetch 函数,不会缓存结果。
 *
 * @example
 * ```ts
 * // 创建一个启用缓存的处理函数
 * const cacheEnabled = createCache(true);
 *
 * // 创建一个禁用缓存的处理函数
 * const cacheDisabled = createCache(false);
 *
 * // 使用缓存处理函数
 * const result = await cacheEnabled('userProfile', async () => {
 *   return await fetchUserProfile(userId);
 * });
 * ```
 */
export function createCache(enable: boolean) {
    if (enable) {
        const map = new Map<string, any>();
        return async <T>(name: string, fetch: () => Promise<T>): Promise<T> => {
            if (map.has(name)) {
                return map.get(name);
            }
            const result = await fetch();
            map.set(name, result);
            return result;
        };
    }
    return <T>(name: string, fetch: () => Promise<T>): Promise<T> => {
        return fetch();
    };
}