/** * 订单模块「基础参照数据」请求缓存(快递公司 / 平台 / 店铺)。 * * 背景:订单管理 8 个页签各自在 mounted 里拉取这 3 个列表(仅用于 ScanBox 筛选下拉与 * 「分配快递号」等弹窗的选项)。页签切换(KeepAlive 淘汰后重建)会重复请求同一份 * 几乎不变的数据,属于无效开销。 * * 设计: * - 缓存的是**原始接口响应**,调用方仍按各自逻辑解析,互不影响; * - 缓存 key 带当前 token:切换账号后自动失效,避免跨租户脏数据; * - 请求失败即从缓存移除,下次进入页面会重试; * - 默认 TTL 60s,参照数据变更(设置页新增快递公司等)最迟 1 分钟内可见。 */ import { getToken } from '@/utils/auth' import * as indexApi from '@/api/index/index' import type { GetExpressListParams, GetPlatformListParams } from '@/api/index/index' /** 参照数据缓存有效期(毫秒) */ export const ORDER_META_CACHE_TTL = 60_000 type CacheEntry = { at: number; promise: Promise } const cache = new Map() function sessionKey(name: string) { return `${name}|${getToken() ?? ''}` } function cachedRequest(name: string, loader: () => Promise, ttl = ORDER_META_CACHE_TTL): Promise { const key = sessionKey(name) const now = Date.now() const hit = cache.get(key) if (hit && now - hit.at < ttl) return hit.promise as Promise const promise = loader().catch((error) => { // 失败不留在缓存里,避免一次网络抖动导致整段时间都用不到数据 if (cache.get(key)?.promise === promise) cache.delete(key) throw error }) cache.set(key, { at: now, promise }) return promise } /** 快递公司列表(systemOnly 不同视为不同缓存项) */ export function loadExpressListCached(params?: GetExpressListParams) { const name = params?.systemOnly === 'true' ? 'express:systemOnly' : 'express:all' return cachedRequest(name, () => indexApi.getExpressList(params)) } /** 平台列表(订单页统一用 systemOnly=true) */ export function loadPlatformListCached(params: GetPlatformListParams = { systemOnly: 'true' }) { const name = params.systemOnly === 'true' ? 'platform:systemOnly' : 'platform:all' return cachedRequest(name, () => indexApi.getPlatformList(params)) } /** 货主店铺列表(ScanBox 货主筛选项) */ export function loadStoresCached() { return cachedRequest('stores', () => indexApi.loadStores()) } /** 清空参照数据缓存(如基础数据被编辑后可手动调用) */ export function clearOrderMetaCache() { cache.clear() }