feat(projects): 添加cryptojs,对本地缓存数据进行加密

This commit is contained in:
Soybean
2022-01-01 22:52:05 +08:00
parent 25d3404c9c
commit 7a0648dba5
5 changed files with 994 additions and 775 deletions

View File

@@ -1,21 +1,37 @@
import { encrypto, decrypto } from '../crypto';
interface StorageData {
value: unknown;
expire: number | null;
}
/** 默认缓存期限为7天 */
const DEFAULT_CACHE_TIME = 60 * 60 * 24 * 7;
export function setLocal(key: string, value: unknown, expire: number | null = DEFAULT_CACHE_TIME) {
const json = JSON.stringify({ value, expire: expire !== null ? new Date().getTime() + expire * 1000 : null });
const storageData: StorageData = { value, expire: expire !== null ? new Date().getTime() + expire * 1000 : null };
const json = encrypto(storageData);
window.localStorage.setItem(key, json);
}
export function getLocal<T>(key: string) {
const json = window.localStorage.getItem(key);
if (json) {
const data = JSON.parse(json);
const { value, expire } = data;
/** 在有效期内直接返回 */
if (expire === null || expire >= Date.now()) {
return value as T;
let storageData: StorageData | null = null;
try {
storageData = decrypto(json);
} catch {
// 防止解析失败
}
if (storageData) {
const { value, expire } = storageData;
// 在有效期内直接返回
if (expire === null || expire >= Date.now()) {
return value as T;
}
}
removeLocal(key);
return null;
}
return null;
}