import { convertExpire } from '../util'; /** * 内存缓存数据 key 值 */ export type MemoryCacheKey = string | number | symbol; /** * 内存缓存数据的类型 */ export type MemoryCacheCachedData = { /** * 缓存内容 */ value: any; /** * 缓存过期时间 */ expires: number; /** * 创建时间 */ createTime: number; }; export type MemoryCache = { get(key: MemoryCacheKey, defaultValue?: any): any; set(key: MemoryCacheKey, value: any, expires?: number | string): Map; remove(key: MemoryCacheKey): boolean; clear(): void; }; /** * Creates a MemoryCache instance that can be used by a WechatMiniprogram app. * 内存缓存工具 */ export function createMemoryCache(): MemoryCache { const memoryCache = new Map(); function get(key: MemoryCacheKey, defaultValue?: any) { const data = memoryCache.get(key); if (data) { const { expires, value } = data; if (expires === -1 || expires > Date.now()) return value; // delete expired data remove(key); } return defaultValue; } function set(key: MemoryCacheKey, value: any, expires?: number | string) { const timestamp = Date.now(); const expiresAt = convertExpire(expires || -1) + timestamp; const data = { value, expires: expiresAt, createTime: Date.now(), }; return memoryCache.set(key, data); } function remove(key: MemoryCacheKey) { return memoryCache.delete(key); } function clear() { return memoryCache.clear(); } return { get, set, remove, clear, }; }