interface Value { data: T; timestamp: number; } interface Options { /** 过期时间,单位毫秒 */ expires?: number; /** 是否保存在本地 */ isSaveLoacl?: boolean; } abstract class Storage { protected data = new Map(); protected abstract _setItem(key: string, value: string): void; protected abstract _getItem(key: string): string | null; /** 设置缓存 */ public setItem(key: string, data: string | null, options?: Options) { if (data === null) { this.data.delete(key); this._setItem(key, ""); } const expires = options?.expires || 0; const value: Value = { data: data, timestamp: expires === 0 ? 0 : Date.now() + expires }; const valueStr = JSON.stringify(value); this.data.set(key, valueStr); if (expires > 0) { this._setItem(key, valueStr); } } /** 读取缓存 */ public getItem(key: string): T | null { const dist = this.data.get(key) || this._getItem(key); if (dist) { const storage = JSON.parse(dist) as Value; // 如果未设置时间,则是走内存 if (storage.timestamp === 0) { return storage.data; } // 缓存过期 if (storage.timestamp - Date.now() <= 0) { this.setItem(key, null); return null; } return storage.data; } return null; } } export default Storage;