123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117 |
- // @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<string, InstructionsCache> = {};
- 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());
- }
- }
|