import type { ChatHistoryItem } from '@af-mobile-client-vue3/components/common/MateChat/types' import { ref } from 'vue' /** * 历史会话缓存项 */ interface HistoryCacheItem { list: ChatHistoryItem[] timestamp: number } /** * 历史会话缓存管理 * 使用 Map 存储不同 appId 的缓存数据 */ const historyCache = ref>(new Map()) /** * 缓存过期时间(毫秒),默认 5 分钟 */ const CACHE_EXPIRY_TIME = 5 * 60 * 1000 /** * 生成缓存 key */ function getCacheKey(appId: string, appKey: string): string { return `${appId}_${appKey}` } /** * 检查缓存是否有效 */ function isCacheValid(cacheItem: HistoryCacheItem | undefined): boolean { if (!cacheItem) { return false } const now = Date.now() return now - cacheItem.timestamp < CACHE_EXPIRY_TIME } /** * 历史会话缓存管理组合式函数 */ export function useChatHistoryCache() { /** * 获取缓存的历史会话列表 * @param appId FastGPT 应用 ID * @param appKey FastGPT API Key * @returns 缓存的历史会话列表,如果缓存不存在或已过期则返回 null */ function getCachedHistory(appId: string, appKey: string): ChatHistoryItem[] | null { const key = getCacheKey(appId, appKey) const cacheItem = historyCache.value.get(key) if (isCacheValid(cacheItem)) { return cacheItem!.list } // 缓存无效,清除 if (cacheItem) { historyCache.value.delete(key) } return null } /** * 设置历史会话列表缓存 * @param appId FastGPT 应用 ID * @param appKey FastGPT API Key * @param list 历史会话列表 */ function setCachedHistory(appId: string, appKey: string, list: ChatHistoryItem[]): void { const key = getCacheKey(appId, appKey) historyCache.value.set(key, { list, timestamp: Date.now(), }) } /** * 清除指定应用的历史会话缓存 * @param appId FastGPT 应用 ID * @param appKey FastGPT API Key */ function clearCache(appId: string, appKey: string): void { const key = getCacheKey(appId, appKey) historyCache.value.delete(key) } /** * 清除所有历史会话缓存 */ function clearAllCache(): void { historyCache.value.clear() } /** * 检查是否有有效的缓存 * @param appId FastGPT 应用 ID * @param appKey FastGPT API Key * @returns 是否有有效缓存 */ function hasValidCache(appId: string, appKey: string): boolean { const key = getCacheKey(appId, appKey) const cacheItem = historyCache.value.get(key) return isCacheValid(cacheItem) } return { getCachedHistory, setCachedHistory, clearCache, clearAllCache, hasValidCache, } }