diff --git a/src/utils/modelApi.js b/src/utils/modelApi.js index eb6ef7a..21010f9 100644 --- a/src/utils/modelApi.js +++ b/src/utils/modelApi.js @@ -1,4 +1,4 @@ -import { fetchPlatformModels as fetchModelsRaw } from '@/apis/display' +import { fetchPlatformModels as fetchModelsRaw, requestModelConfig, requestModelConfigsBatch } from '@/apis/display' const CACHE_PREFIX = 'platform_models_' const CACHE_TTL = 30 * 1000 // 30秒有效期 @@ -93,10 +93,89 @@ export async function getModelId(type, modelName) { const code = getPlatformCode(type) const models = await fetchPlatformModels(code) - const found = models.find(m => m.name === modelName || m.display_name === modelName) + const found = models.find((m) => m.name === modelName || m.display_name === modelName) return found?.id || '' } +// ==================== 模型配置缓存 ==================== + +const CONFIG_CACHE_PREFIX = 'model_config_' +const CONFIG_CACHE_TTL = 60 * 1000 // 60 秒 +const pendingConfigRequests = new Map() + +/** + * 批量预加载模型配置到缓存 + * @param {string[]} modelIds - 模型 UUID 列表 + */ +export async function preloadModelConfigs(modelIds) { + if (!modelIds.length) return + const result = await requestModelConfigsBatch(modelIds) + const data = result?.data || {} + const now = Date.now() + modelIds.forEach((id) => { + const config = data[id] + if (config) { + const cacheEntry = { config, timestamp: now } + try { + localStorage.setItem(CONFIG_CACHE_PREFIX + id, JSON.stringify(cacheEntry)) + } catch { + // localStorage 满时静默失败 + } + } + }) +} + +/** + * 获取单个模型配置(优先读缓存,未命中调 API) + * @param {string} modelId - 模型 UUID + * @returns {Promise} 模型配置对象 + */ +export async function getModelConfig(modelId) { + if (!modelId) return null + + // 1. 读缓存 + try { + const cached = localStorage.getItem(CONFIG_CACHE_PREFIX + modelId) + if (cached) { + const { config, timestamp } = JSON.parse(cached) + if (Date.now() - timestamp < CONFIG_CACHE_TTL) { + return config + } + } + } catch { + // 缓存解析失败,走 API + } + + // 2. 并发去重 + if (pendingConfigRequests.has(modelId)) { + return pendingConfigRequests.get(modelId) + } + + // 3. 调单条 API + const promise = (async () => { + try { + const result = await requestModelConfig(modelId) + const config = result?.data + if (config) { + const cacheEntry = { config, timestamp: Date.now() } + try { + localStorage.setItem(CONFIG_CACHE_PREFIX + modelId, JSON.stringify(cacheEntry)) + } catch { + // 静默 + } + } + return config || null + } catch { + return null + } finally { + pendingConfigRequests.delete(modelId) + } + })() + + pendingConfigRequests.set(modelId, promise) + return promise +} + // 清除所有平台模型缓存 export function clearPlatformModelCache() { const keysToRemove = [] @@ -106,5 +185,5 @@ export function clearPlatformModelCache() { keysToRemove.push(key) } } - keysToRemove.forEach(key => localStorage.removeItem(key)) + keysToRemove.forEach((key) => localStorage.removeItem(key)) }