interface CacheDetail { value: any; expiresTimeStamp: number; } interface CacheMap { [cacheKey: string]: CacheDetail; } /** * 默认过期时间 */ export const DEFAULT_EXPIRES = 5 * 60 * 1000; let data: CacheMap = {}; export default class { /** * 插入指定名称数据 * @param {string} name * @param {T} cache * @param {number} expires 有效时间(毫秒时间戳) */ static set(name: string, cache: T, expires: number = DEFAULT_EXPIRES) { data[name] = { value: cache, expiresTimeStamp: Date.now() + expires, }; return this; } static get(name: string): T | null { const detail = data[name]; if (!detail) return null; try { if (detail.expiresTimeStamp && detail.expiresTimeStamp > Date.now()) { return detail.value || null; } } catch (err) {} this.clear(name); return null; } /** * 获取指定名称数据 * @param {string} name */ static clear(name: string) { delete data[name]; return this; } /** * 清除所有数据 */ static clearAll() { data = {}; return this; } }