-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStorage.js
69 lines (59 loc) · 1.41 KB
/
Storage.js
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
function isBaseType(val) {
return (typeof val !== 'object' && typeof val !== 'function') || val == null;
}
let _instance = null;
class LocStorage {
constructor() {
}
static getInstancce() {
if (!_instance) {
_instance = new LocStorage();
}
return _instance;
}
get(key) {
const data = localStorage.getItem(key);
if (!data) {
return data;
}
try {
const parsedData = JSON.parse(data);
if (
!parsedData.timestamp ||
parsedData.timestamp > new Date().getTime()
) {
const realStr = parsedData.data.slice(0, -1);
const type = parsedData.data.slice(-1);
return type === '0' ?
realStr :
(type === '1' ? JSON.parse(realStr) : null);
} else {
this.remove(key);
}
} catch (error) {
return null;
}
};
set(key, value, seconds) {
const data = isBaseType(value) ?
value + '0' :
JSON.stringify(value) + '1';
let realValue;
if (seconds > 0) {
const timeToOverdue = new Date().getTime() + seconds * 1000;
realValue = JSON.stringify({data, timestamp: timeToOverdue});
} else {
realValue = JSON.stringify({data});
}
localStorage.setItem(key, realValue);
};
clear() {
return localStorage.clear();
};
remove(key) {
return localStorage.removeItem(key);
};
get length() {
return localStorage.length;
}
}