import TypeTools, { TYPES } from './type-tools'; class StorageData { data: any; type: string; timeout: number; constructor(data: any, type: string, timeout: number) { this.data = data; this.type = type; this.timeout = timeout; } /** * 判断缓存是否过期 */ isExpired(): boolean { if (!this.timeout) return false; return new Date().getTime() > this.timeout; } getData(): any { if(this.type === TYPES.DATE){ return new Date(parseInt(this.data)); }else if(this.type== TYPES.OBJ || this.type== TYPES.ARRAY){ return JSON.parse(this.data); }else if(this.type== TYPES.REGEXP){ return new RegExp(this.data.pattern, this.data.flags); }else if(this.type== TYPES.BOOLEAN){ return this.data === 'true'; }else if(this.type== TYPES.NUMBER){ return new Number(this.data); }else if(this.type== TYPES.STRING){ return this.data; } return this.data; } static fromData(data: any,timeout?: number): StorageData { if(timeout==undefined) timeout = new Date().getTime() + 600000; // Default timeout to 10 minutes from now let type = TypeTools.parseType(data); if(type === TYPES.UNKNOWN ||type== TYPES.FUNCTION || type== TYPES.JSON){ throw new Error('错误的数据类型,不能保存'); } let sdata = data; if(type === TYPES.DATE){ sdata = data.getTime(); }else if(type== TYPES.OBJ || type== TYPES.ARRAY){ sdata = JSON.stringify(data); }else if(type== TYPES.REGEXP){ sdata = JSON.stringify({ pattern: data.pattern, flags: data.flags }); } return new StorageData(sdata,type,timeout); } static fromJSON(json: string): StorageData { const data = JSON.parse(json); return new StorageData(data.data,data.type,data.timeout); } } const TStorage = { TIME:{SECOND:1000,MINUTE:60000,HOUR:3600000,DAY:86400000}, timeOf(type: number,total:number): number { return type*total; }, set(key: string, data: any, timeout: number = 0) { const storageData = StorageData.fromData(data,timeout); localStorage.setItem(key, JSON.stringify(storageData)); }, get(key: string,timeout?:number) { const sData = localStorage.getItem(key); if (sData) { const data = StorageData.fromJSON(sData); if (data.isExpired()) { if(timeout && timeout > 0){ data.timeout = new Date().getTime() + timeout; localStorage.setItem(key,JSON.stringify(data)); }else{ localStorage.removeItem(key); return null; } } return data.getData(); } return null; } } export async function cache(key:string, timeout: number = 0, promise: Promise):Promise{ return new Promise((resolve, reject) => { const cachedData = TStorage.get(key,timeout); if (cachedData!=undefined) { resolve(cachedData); } else { promise.then((data) => { TStorage.set(key, data, timeout); resolve(data); }).catch((err) => { reject(err); }); } }); } export default TStorage;