Files
td_official/src/plugins/cache.ts

90 lines
1.9 KiB
TypeScript
Raw Normal View History

2025-05-21 11:24:53 +08:00
const sessionCache = {
set(key: string, value: any) {
2025-06-17 09:49:15 +08:00
if (!sessionStorage || key == null || value == null) return;
try {
const str = typeof value === 'string' ? value : JSON.stringify(value);
// 限制:如果数据超过 1MB就不存
if (str.length > 1024 * 1024) {
console.warn(`sessionStorage.setItem(${key}) 跳过,数据过大(${(str.length / 1024).toFixed(2)} KB`);
return;
}
sessionStorage.setItem(key, str);
} catch (e) {
console.error(`sessionStorage.setItem(${key}) 失败:`, e);
2025-05-21 11:24:53 +08:00
}
},
2025-06-17 09:49:15 +08:00
2025-05-21 11:24:53 +08:00
get(key: string) {
if (!sessionStorage) {
return null;
}
if (key == null) {
return null;
}
return sessionStorage.getItem(key);
},
setJSON(key: string, jsonValue: any) {
if (jsonValue != null) {
this.set(key, JSON.stringify(jsonValue));
}
},
getJSON(key: string) {
const value = this.get(key);
if (value != null) {
return JSON.parse(value);
}
return null;
},
remove(key: string) {
sessionStorage.removeItem(key);
}
};
const localCache = {
set(key: string, value: any) {
if (!localStorage) {
return;
}
if (key != null && value != null) {
localStorage.setItem(key, value);
}
},
get(key: string) {
if (!localStorage) {
return null;
}
if (key == null) {
return null;
}
return localStorage.getItem(key);
},
setJSON(key: string, jsonValue: any) {
if (jsonValue != null) {
this.set(key, JSON.stringify(jsonValue));
}
},
getJSON(key: string) {
const value = this.get(key);
if (value != null) {
return JSON.parse(value);
}
return null;
},
remove(key: string) {
localStorage.removeItem(key);
}
};
export default {
/**
*
*/
session: sessionCache,
/**
*
*/
local: localCache
};