-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLocalStorageManager.js
56 lines (47 loc) · 1.34 KB
/
LocalStorageManager.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
import { GlobalUI } from './UiGlobal.js';
import { W } from './wget.js';
const MAX_CACHE_AGE_SECS = 60 * 60 * 24 * 3;
export class LocalStorageManager {
constructor() {
this.max_cache_age_secs = MAX_CACHE_AGE_SECS;
this.cache_idx = this.get('cache_idx', {});
if (typeof(this.cache_idx) != typeof({})) {
GlobalUI.showErrorUi("Can't read local storage, will clear cache");
this.cache_idx = {};
this.save('cache_idx', this.cache_idx);
localStorage.clear();
}
}
get(key, default_val) {
try {
const v = JSON.parse(localStorage.getItem(key));
return v? v : default_val;
} catch (e) {
return default_val;
}
}
save(key, val) {
localStorage.setItem(key, JSON.stringify(val));
}
_cacheGet(key, ignoreExpireDate=false) {
const last_update = this.cache_idx[key] || 0;
const age = Date.now() - last_update;
const cache_is_old = (age > 1000 * this.max_cache_age_secs);
if (cache_is_old && !ignoreExpireDate) {
localStorage.removeItem(key);
return null;
}
return this.get(key, null);
}
cacheGet(key) {
return this._cacheGet(key);
}
cacheGet_ignoreExpire(key) {
return this._cacheGet(key, true);
}
cacheSave(key, val) {
this.cache_idx[key] = Date.now();
this.save('cache_idx', this.cache_idx);
this.save(key, val);
}
};