-
Notifications
You must be signed in to change notification settings - Fork 0
/
CacheHandler.js
48 lines (37 loc) · 953 Bytes
/
CacheHandler.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
class CacheHandler {
constructor(expiresTimeInSecs = 600) {
this._expiresTimeInSecs = expiresTimeInSecs * 1000;
}
_buildKey(key) {
return `cache-${key.toLowerCase()}`;
}
_dateField() {
return "updatedAt";
}
remove(key) {
sessionStorage.removeItem(this._buildKey(key));
}
get(key) {
const cacheData = sessionStorage.getItem(this._buildKey(key));
return !cacheData ? undefined : JSON.parse(cacheData);
}
set(key, cacheJson) {
const storeCacheJson = JSON.stringify({
[this._dateField()]: new Date,
...cacheJson,
});
sessionStorage.setItem(this._buildKey(key), storeCacheJson);
}
isValid(key) {
const cacheJson = this.get(key);
if (!cacheJson) {
return false;
}
if (new Date() - new Date(cacheJson[this._dateField()]) >= this._expiresTimeInSecs) {
this.remove(key);
return false;
}
return true;
}
}
export default CacheHandler;