cache【内存缓存对象】
描述
定义内存缓存对象,允许设置、获取缓存对象、过期时间 v3.0.9+
# 1.示例
import { cache } from 'sf-utils2'
// 设置值,默认永久缓存内存中
cache.setItem('xiaoming', { id: 'xxxx' })
// 设置过期时间 2s 后过期
cache.setItem('xiaoming', { id: 'xxxx' }, 2)
// 获取值
cache.getItem('xiaoming')
// 清除所有
cache.clear()
// 获取所有
cache.getItemAll()
// 内存缓存对象长度
cache.getLength()
// 设置默认缓存时间
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
:::
# 2.入参说明
| 参数 | 说明 | 类型 | 是否必填 | 默认值 |
|---|
# 3.源码
import getLength from '@/base/getLength'
import def from '@/object/def'
const getPrefixKey = (prefix, key) => {
return [prefix, key].filter(Boolean).join()
}
/**
* 内容缓存对象
* @type {{removeItem(String): void, data: {}, size(): number, clear(): void, getItem(String): *, setItem(String, *): void}}
*/
const cache = {
__config: {
// 类型 window.localStorage,window.sessionStorage,
prefix: '', // 名称前缀 建议:项目名 + 项目版本
expire: 0 //过期时间 单位:秒
},
data: {},
/**
* 设置内存缓存对象
* @param {String} key
* @param {*} value
* @param {Number} expire 过期时间 单位秒
*/
setItem(key, value, expire) {
if (isNaN(expire) || expire < 0) throw new Error('Expire must be a number')
expire = (expire ?? this.__config.expire) * 1000
key = getPrefixKey(this.prefix, key)
this.data[key] = {
value: value, // 存储值
time: Date.now(), //存值时间戳
expire: expire // 过期时间
}
},
/**
* 获取内存缓存对象
* @param {String} key
* @param {Boolean} autoRetain 是否自动延续
* @return {*}
*/
getItem(key, autoRetain = false) {
key = getPrefixKey(this.prefix, key)
const data = this.data[key]
if (!data) return undefined
const nowTime = Date.now()
if (data.expire && data.expire < nowTime - data.time) {
// 过期
this.removeItem(key)
return null
} else {
autoRetain && this.setItem(key, data.value, data.expire)
return data.value
}
},
/**
* 移除item
* @param {String} key
*/
removeItem(key) {
key = getPrefixKey(this.prefix, key)
delete this.data[key]
},
/**
* 获取总长度
* @return {number}
*/
getLength() {
return getLength(this.data)
},
/**
* 获取所有items
* @return {{}}
*/
getItemsAll() {
return Object.keys(this.data).reduce((pre, cur) => {
const key = getPrefixKey(this.prefix, cur)
const dataValue = this.getItem(key)
if (dataValue) {
pre[cur] = dataValue
}
return pre
}, {})
},
/**
* 清除缓存
*/
clear() {
this.data = {}
}
}
def(cache, '__config')
def(cache, 'data')
export default cache
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
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
上次更新: 2023/06/24, 19:35:48