import { fetchApi } from './server-api-util'; // 全局缓存对象 const cache: Record = {}; const CACHE_DURATION = 5 * 60 * 1000; // 5分钟缓存时间 /** * 预取数据并缓存 * @param url API地址 * @param forceRefresh 是否强制刷新缓存 * @returns 返回Promise,解析为获取到的数据 */ export const prefetchData = async (url: string, forceRefresh = false): Promise => { const now = Date.now(); // 检查缓存是否存在且未过期 if (!forceRefresh && cache[url] && (now - cache[url].timestamp < CACHE_DURATION)) { return cache[url].data as T; } try { const data = await fetchApi(url); // 缓存数据 cache[url] = { data, timestamp: now, }; return data; } catch (error) { console.error(`Prefetch failed for ${url}:`, error); // 如果缓存中有旧数据,返回旧数据 if (cache[url]) { return cache[url].data as T; } throw error; } }; /** * 预取聊天列表 */ export const prefetchChats = async () => { return prefetchData>('/chats'); }; /** * 预取单个聊天详情 */ export const prefetchChatDetail = async (sessionId: string) => { return prefetchData(`/chats/${sessionId}/message-history`); }; /** * 清除指定URL的缓存 */ export const clearCache = (url?: string) => { if (url) { delete cache[url]; } else { // 清除所有缓存 Object.keys(cache).forEach(key => { delete cache[key]; }); } }; /** * 获取缓存数据 */ export const getCachedData = (url: string): T | null => { const cached = cache[url]; if (cached && (Date.now() - cached.timestamp < CACHE_DURATION)) { return cached.data as T; } return null; };