menuApiCache.js 2.47 KB
/**
 * @file 首页菜单异步 Provider 用 API 缓存(in-flight + TTL)
 * 精品 / 权益共用;切店时由 invalidateMenuAndApiCaches 清空。
 */

import { invalidateSharedMenuApiCaches } from './invalidateMenuApiCaches.js'

const CACHE_TTL_MS = 60 * 1000
const cache = new Map()
const pending = new Map()

/** 清空菜单 API 内存缓存(不含 isNeed gate) */
export function clearMenuApiCache() {
	cache.clear()
	pending.clear()
}

/**
 * 切店等场景:菜单 API 缓存 + 共用 isNeed 缓存一并失效
 */
export function invalidateMenuAndApiCaches() {
	clearMenuApiCache()
	invalidateSharedMenuApiCaches()
}

function cacheKey(prefix, id) {
	return `${prefix}:${id == null ? '' : String(id)}`
}

function readCache(key) {
	const entry = cache.get(key)
	if (!entry) return null
	if (Date.now() - entry.ts > CACHE_TTL_MS) {
		cache.delete(key)
		return null
	}
	return entry.value
}

function writeCache(key, value) {
	cache.set(key, { value, ts: Date.now() })
}

async function cachedCall(key, fn) {
	const cached = readCache(key)
	if (cached !== null) return cached

	if (pending.has(key)) return pending.get(key)

	const promise = Promise.resolve()
		.then(fn)
		.then(res => {
			writeCache(key, res)
			return res
		})
		.finally(() => {
			pending.delete(key)
		})

	pending.set(key, promise)
	return promise
}

/**
 * 工资申诉入口:has.performance.config.formerchant
 * @param {Object} api - 含 hasPerformanceConfig 方法
 * @param {string} [merchantId]
 */
export function cachedHasPerformanceConfig(api, merchantId) {
	const key = cacheKey('hasPerformanceConfig', merchantId || '')
	return cachedCall(key, () =>
		api.hasPerformanceConfig({ merchantId: merchantId || '' })
	)
}

/**
 * 接待缺失:resident.direct.sale.merchant
 * @param {Object} api - 含 checkMerchantDirect 方法
 * @param {{ merchantId: string, scene: number }} params
 */
export function cachedCheckMerchantDirect(api, params) {
	const key = cacheKey(
		'checkMerchantDirect',
		`${params?.merchantId || ''}|${params?.scene ?? ''}`
	)
	return cachedCall(key, () => api.checkMerchantDirect(params))
}

/**
 * 驻店目标:staffTargetCheck.getTargetCheck
 * @param {Object} api - 含 getStaffTargetTaskApi 方法
 * @param {{ merchantId: string, sceneType: number }} params
 */
export function cachedGetStaffTargetTask(api, params) {
	const key = cacheKey(
		'getStaffTargetTask',
		`${params?.merchantId || ''}|${params?.sceneType ?? ''}`
	)
	return cachedCall(key, () => api.getStaffTargetTaskApi(params))
}