Files
td_official/src/plugins/cache.ts
2025-06-17 09:49:15 +08:00

90 lines
1.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const sessionCache = {
set(key: string, value: any) {
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);
}
},
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
};