-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathStorageManager.ts
57 lines (55 loc) · 1.6 KB
/
StorageManager.ts
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
import SubscriptionManager from './SubscriptionManager';
export default class StorageManager {
prefix: string;
subscriptionManager: SubscriptionManager;
constructor(prefix: string) {
this.prefix = `${prefix}-`;
this.subscriptionManager = new SubscriptionManager();
window.addEventListener('storage', this._handleNewValue);
}
private _handleNewValue = (e: StorageEvent) => {
const key = e.key;
if (key && key.startsWith(this.prefix)) {
const unPrefixedKey = key.substr(this.prefix.length);
this.subscriptionManager.notify(unPrefixedKey);
}
}
private _addPrefix(key: string): string {
return `${this.prefix}${key}`;
}
subscribe(key: string, fn: () => void): void {
this.subscriptionManager.subscribe(key, fn);
}
unsubscribe(key: string, fn: () => void): void {
this.subscriptionManager.unsubscribe(key, fn);
}
get(key: string, session = false) {
const k = this._addPrefix(key);
if (session) {
const v = sessionStorage.getItem(k);
if (v) {
return v;
}
}
return localStorage.getItem(k);
}
set(key: string, value: string, session = false) {
const k = this._addPrefix(key);
if (session) {
sessionStorage.setItem(k, value);
}
localStorage.setItem(k, value);
this.subscriptionManager.notify(key);
}
delete(key: string, session = false) {
const k = this._addPrefix(key);
if (session) {
sessionStorage.removeItem(k);
}
localStorage.removeItem(k);
this.subscriptionManager.notify(key);
}
cleanup() {
window.removeEventListener('storage', this._handleNewValue);
}
}