109 lines
2.0 KiB
TypeScript
109 lines
2.0 KiB
TypeScript
import pkg from '../../package.json';
|
|
|
|
// 默认缓存期限为7天
|
|
const DEFAULT_CACHE_TIME = 60 * 60 * 24 * 7;
|
|
|
|
const getKey = (key: string) => `${pkg.name}-${key}`.toUpperCase();
|
|
|
|
/**
|
|
* 本地缓存类
|
|
* @class Storage
|
|
*/
|
|
class _Storage {
|
|
readonly length = 0
|
|
storage: Storage = null
|
|
/**
|
|
* 初始化
|
|
*/
|
|
constructor(storage: Storage) {
|
|
this.storage = storage;
|
|
}
|
|
/**
|
|
* 获取存储中的第 n 个键名
|
|
*/
|
|
key(index: number) {
|
|
return this.storage.key(index);
|
|
}
|
|
/**
|
|
* 获取缓存
|
|
*/
|
|
getItem(key: string) {
|
|
return this.storage.getItem(getKey(key));
|
|
}
|
|
/**
|
|
* 设置缓存
|
|
*/
|
|
setItem(key: string, value: any) {
|
|
return this.storage.setItem(getKey(key), value);
|
|
}
|
|
/**
|
|
* 删除缓存
|
|
*/
|
|
removeItem(key: string) {
|
|
this.storage.removeItem(getKey(key));
|
|
}
|
|
/**
|
|
* 设置缓存
|
|
*/
|
|
set(key: string, value: any, expire: number = DEFAULT_CACHE_TIME) {
|
|
const json = JSON.stringify({
|
|
value,
|
|
expire: expire !== null ? new Date().getTime() + expire * 1000 : null
|
|
});
|
|
this.setItem(key, json);
|
|
}
|
|
|
|
/**
|
|
* 读取缓存
|
|
*/
|
|
get(key: string, def: any = null) {
|
|
const item = this.getItem(key);
|
|
if (item) {
|
|
try {
|
|
const data = JSON.parse(item);
|
|
const { value, expire } = data;
|
|
// 在有效期内直接返回
|
|
if (expire === null || expire >= Date.now()) {
|
|
return value;
|
|
}
|
|
this.remove(key);
|
|
} catch (e) {
|
|
return def;
|
|
}
|
|
}
|
|
return def;
|
|
}
|
|
|
|
/**
|
|
* 从缓存删除某项
|
|
*/
|
|
remove(key: string) {
|
|
this.removeItem(key);
|
|
}
|
|
|
|
/**
|
|
* 清空所有缓存
|
|
*/
|
|
clear() {
|
|
this.storage.clear();
|
|
}
|
|
}
|
|
|
|
export const local = new Proxy(new _Storage(localStorage), {
|
|
get(target: _Storage, key) {
|
|
if (key === 'length') {
|
|
return localStorage.length
|
|
}
|
|
return target[key]
|
|
}
|
|
});
|
|
export const session = new Proxy(new _Storage(sessionStorage), {
|
|
get(target: _Storage, key) {
|
|
if (key === 'length') {
|
|
return localStorage.length
|
|
}
|
|
return target[key]
|
|
}
|
|
});
|
|
|