// @ts-ignore import md5 from '../../encryption/md5'; import storage from "$utils/tool/storage"; import { InstructionsCacheType } from '$utils/request/const/request'; export default class Cache { static key:string='cache:' // 缓存的数据 caches:Record = {}; static sign(requestData:LibRequestOptions) { let keys = Object.keys(requestData.data || {}).sort(); let sign:string = ''; // 执行 建立 数据记录 合集 for (let i = 0, count = keys.length; i < count; i++) { // @ts-ignore let value = requestData.data[keys[i]]; if (value === undefined) value = ''; sign += keys[i]+':'+value; } // 构造唯一值 // @ts-ignore return md5(requestData.url +'-'+ sign); } // 获取缓存 getCache(sign:string,expire:boolean = true):InstructionsCache | undefined{ // 查看内存是否存在且可以使用 if (this.caches[sign]) { if (expire && Cache.isExpire(this.caches[sign])) { return this.caches[sign]; } else { return this.caches[sign]; } } // 否则查询缓存 else { let data:InstructionsCache = storage.getItem(Cache.key+':'+sign); if (data) { data.first = undefined; return this.setCache(sign,data); } } return undefined; } // 设置缓存 setCache(sign:string,cache:InstructionsCache):InstructionsCache{ let resultCache:InstructionsCache; if (typeof cache === 'boolean') { resultCache = {}; } else { resultCache = {...cache}; } resultCache.expireTime = resultCache.expireTime || 0; // 设置过期时间 resultCache.expireTime = !resultCache.expireTime || resultCache.expireTime<=0 ? resultCache.expireTime : Cache.getNowTime() + resultCache.expireTime; if (this.caches[sign]) { resultCache.first = this.caches[sign].first; } // 设置是否为第一次 resultCache.first = resultCache.first === undefined; this.caches[sign] = resultCache; // 设置缓存 if ( resultCache.type === undefined || resultCache.type === InstructionsCacheType.storage ) { if (resultCache.expireTime != null) { storage.setItem(Cache.key + ':' + sign, resultCache, resultCache.expireTime); } } return resultCache; } // 验证是否过期 static isExpire(data:InstructionsCache):boolean { return !data.expireTime || data.expireTime <=0 || Cache.getNowTime() < data.expireTime; } // 获取当前时间 static getNowTime(){ return parseInt((new Date().getTime() / 1000).toString()); } }