77 lines
1.9 KiB
TypeScript
77 lines
1.9 KiB
TypeScript
import { fetchApi } from './server-api-util';
|
||
|
||
// 全局缓存对象
|
||
const cache: Record<string, { data: any; timestamp: number }> = {};
|
||
const CACHE_DURATION = 5 * 60 * 1000; // 5分钟缓存时间
|
||
|
||
/**
|
||
* 预取数据并缓存
|
||
* @param url API地址
|
||
* @param forceRefresh 是否强制刷新缓存
|
||
* @returns 返回Promise,解析为获取到的数据
|
||
*/
|
||
export const prefetchData = async <T>(url: string, forceRefresh = false): Promise<T> => {
|
||
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<T>(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<Array<{ session_id: string; title: string; latest_message?: any }>>('/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 = <T>(url: string): T | null => {
|
||
const cached = cache[url];
|
||
if (cached && (Date.now() - cached.timestamp < CACHE_DURATION)) {
|
||
return cached.data as T;
|
||
}
|
||
return null;
|
||
};
|