storage.js
1.47 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
/*
* @Author: limin
* @Date: 2018-06-23 11:13:44
* @Last Modified by: limin
* @Last Modified time: 2018-08-31 18:28:26
*/
const aseKey = 'UkRPT0pp' //秘钥必须为:8/16/32位
const isPro = process.env.NODE_ENV !== 'production'
const TYPE = {
LOCAL: 'localStorage',
SESSION: 'sessionStorage'
}
function isObject(val) {
return val !== null && typeof val === 'object'
}
function encrypt(val) {
if (!val) return val
return val
}
function decrypt(val) {
if (!val) return val
return val
}
function set(key, val, type = TYPE.LOCAL) {
if (isObject(val)) window[type].setItem(key, JSON.stringify(val))
else window[type].setItem(key, encrypt(val))
}
function get(key, type = TYPE.LOCAL) {
var val = window[type].getItem(key)
try {
if (val && val.startsWith('#')) {
return val
}
const value = JSON.parse(decrypt(val))
return value
} catch (e) {
throw e
}
}
function remove(key, type = TYPE.LOCAL) {
window[type].removeItem(key)
}
function setSession(key, val, ex = 20) {
set(key, val, TYPE.SESSION)
}
function getSession(key) {
return get(key, TYPE.SESSION)
}
function removeSession(key) {
remove(key, TYPE.SESSION)
}
// 默认30minute
function setExpire(key, val, ex = 1.8e6) {
set(key, { v: val, t: Date.now() + ex })
}
function getExpire(key) {
var obj = get(key)
if (obj.t > Date.now()) return obj.v
else return null
}
export default {
set,
get,
remove,
setSession,
getSession,
removeSession,
setExpire,
getExpire
}