/** * 简单的内存缓存实现 */ interface CacheItem { value: T expiry: number } class MemoryCache { private cache: Map> = new Map() /** * 获取缓存项 * @param key 缓存键 * @returns 缓存值或undefined */ get(key: string): T | undefined { const item = this.cache.get(key) if (!item) { return undefined } if (Date.now() > item.expiry) { this.cache.delete(key) return undefined } return item.value } /** * 设置缓存项 * @param key 缓存键 * @param value 缓存值 * @param ttlMs 过期时间(毫秒) */ set(key: string, value: T, ttlMs: number): void { this.cache.set(key, { value, expiry: Date.now() + ttlMs, }) } /** * 删除缓存项 * @param key 缓存键 */ delete(key: string): void { this.cache.delete(key) } /** * 清空所有缓存 */ clear(): void { this.cache.clear() } } export const memoryCache = new MemoryCache() /** * 带缓存的数据获取函数 * @param key 缓存键 * @param fetchFn 获取数据的函数 * @param ttlMs 缓存过期时间(毫秒) * @returns Promise */ export async function fetchWithCache( key: string, fetchFn: () => Promise, ttlMs = 60000, // 默认1分钟 ): Promise { const cachedData = memoryCache.get(key) if (cachedData !== undefined) { return cachedData } const data = await fetchFn() memoryCache.set(key, data, ttlMs) return data }