| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139 |
- /**
- * 本地缓存类,可配置缓存时间,长久保存
- */
- class localStorageEngine {
- constructor() {
- try {
- if (window.localStorage) {
- this.ok = true;
- this.key = '';
- this.expTime = 0;
- }
- } catch (e) {
- console.log('localStorage not exist');
- }
- }
- getItem() {
- if (this.ok) {
- let value = window.localStorage.getItem(this.key);
- if (value && value !== 'undefined') {
- value = JSON.parse(value);
- this.expTime = value.expTime;
- } else {
- return null;
- }
- return value.data;
- }
- return null;
- }
- setItem(time, value) {
- if (this.ok) {
- value = JSON.stringify({ data: value, expTime: time });
- window.localStorage.setItem(this.key, value);
- return true;
- }
- return false;
- }
- removeItem() {
- if (this.ok) {
- window.localStorage.removeItem(this.key);
- this.expTime = 0;
- return true;
- }
- return false;
- }
- }
- class Cache extends localStorageEngine {
- constructor(key) {
- super();
- this.key = key;
- this.value = null;
- }
- setCache(value, time, local) {
- if (time) {
- this.expTime = Math.ceil(Date.now() / 1000) + time;
- }
- this.value = value;
- if (local) {
- this.setItem(this.expTime, value);
- }
- }
- getCache(local) {
- if (this.hasCache(local)) {
- return this.value;
- }
- return null;
- }
- clearCache(local) {
- this.value = null;
- if (local) this.removeItem();
- }
- hasCache(local) {
- if (!this.value && local) this.value = this.getItem();
- if (this.expTime !== 0 && Math.ceil(Date.now() / 1000) > this.expTime) {
- this.clearCache(local);
- return false;
- }
- return !!this.value;
- }
- }
- export default class CacheManage {
- constructor() {
- this.cacheMap = {};
- this.prefix = __BASE_NAME__.substr(1, __BASE_NAME__.length - 1) || 'base';
- }
- formatKey(key) {
- return `gj:${key}`.toUpperCase();
- }
- getCache(key, local = true) {
- /**
- * 获取缓存
- * key 密钥
- * local 是否本地缓存
- */
- key = this.formatKey(key);
- if (!this.cacheMap[key]) {
- this.cacheMap[key] = CacheManage.makeCache(key);
- }
- return this.cacheMap[key].getCache(local);
- }
- setCache(key, value, time, local = true) {
- /**
- * 设置缓存
- * key 密钥
- * value 值
- * time 缓存时间
- * local 是否本地缓存
- */
- key = this.formatKey(key);
- if (!this.cacheMap[key]) {
- this.cacheMap[key] = CacheManage.makeCache(key);
- }
- this.cacheMap[key].setCache(value, time, local);
- }
- removeCache(key, local = true) {
- key = this.formatKey(key);
- if (this.cacheMap[key]) {
- this.cacheMap[key].clearCache(local);
- }
- }
- static getApiCacheKey() {
- return '';
- }
- static makeCache(key) {
- return new Cache(key);
- }
- }
|