storage.ts
2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/**
* 本地存储工具类
* 支持 localStorage 和 sessionStorage
*/
type StorageType = 'local' | 'session';
class Storage {
/**
* 获取存储项数量
*/
get length(): number {
return this.storage.length;
}
private storage: globalThis.Storage;
constructor(type: StorageType = 'local') {
this.storage = type === 'local' ? localStorage : sessionStorage;
}
/**
* 清空所有存储项
*/
clear(): void {
try {
this.storage.clear();
} catch (error) {
console.error('清空存储失败:', error);
}
}
/**
* 获取存储项
*/
get<T = any>(key: string): null | T {
try {
const item = this.storage.getItem(key);
return item ? JSON.parse(item) : null;
} catch (error) {
console.error('读取数据失败:', error);
return null;
}
}
/**
* 获取带过期时间的存储项
*/
getWithExpiry<T = any>(key: string): null | T {
const item = this.get<{ expiry: number; value: T }>(key);
if (!item) {
return null;
}
const now = Date.now();
// 检查是否过期
if (now > item.expiry) {
this.remove(key);
return null;
}
return item.value;
}
/**
* 检查是否存在某个 key
*/
has(key: string): boolean {
return this.storage.getItem(key) !== null;
}
/**
* 获取所有 keys
*/
keys(): string[] {
return Object.keys(this.storage);
}
/**
* 移除存储项
*/
remove(key: string): void {
try {
this.storage.removeItem(key);
} catch (error) {
console.error('移除数据失败:', error);
}
}
/**
* 设置存储项
*/
set(key: string, value: any): void {
try {
const serializedValue = JSON.stringify(value);
this.storage.setItem(key, serializedValue);
} catch {}
}
/**
* 设置带过期时间的存储项
*/
setWithExpiry(key: string, value: any, expiryInMs: number): void {
const now = Date.now();
const item = {
value,
expiry: now + expiryInMs,
};
this.set(key, item);
}
}
// 导出实例
export const localCache = new Storage('local');
export const sessionCache = new Storage('session');
export default Storage;