-
Notifications
You must be signed in to change notification settings - Fork 75
/
Copy pathWebStorage.js
67 lines (57 loc) · 2.54 KB
/
WebStorage.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
/**
* This file is here to wrap LocalForage with a layer that provides data-changed events like the ones that exist
* when using LocalStorage APIs in the browser. These events are great because multiple tabs can listen for when
* data changes and then stay up-to-date with everything happening in Onyx.
*/
import _ from 'underscore';
import Storage from './providers/LocalForage';
const SYNC_ONYX = 'SYNC_ONYX';
/**
* Raise an event thorough `localStorage` to let other tabs know a value changed
* @param {String} onyxKey
*/
function raiseStorageSyncEvent(onyxKey) {
global.localStorage.setItem(SYNC_ONYX, onyxKey);
global.localStorage.removeItem(SYNC_ONYX, onyxKey);
}
const webStorage = {
...Storage,
/**
* @param {Function} onStorageKeyChanged Storage synchronization mechanism keeping all opened tabs in sync
*/
keepInstancesSync(onStorageKeyChanged) {
// Override set, remove and clear to raise storage events that we intercept in other tabs
this.setItem = (key, value) => Storage.setItem(key, value)
.then(() => raiseStorageSyncEvent(key));
this.removeItem = key => Storage.removeItem(key)
.then(() => raiseStorageSyncEvent(key));
// If we just call Storage.clear other tabs will have no idea which keys were available previously
// so that they can call keysChanged for them. That's why we iterate over every key and raise a storage sync
// event for each one
this.clear = () => {
let allKeys;
// They keys must be retreived before storage is cleared or else the list of keys would be empty
return Storage.getAllKeys()
.then((keys) => {
allKeys = keys;
})
.then(() => Storage.clear())
.then(() => {
// Now that storage is cleared, the storage sync event can happen so that it is more of an atomic
// action
_.each(allKeys, raiseStorageSyncEvent);
});
};
// This listener will only be triggered by events coming from other tabs
global.addEventListener('storage', (event) => {
// Ignore events that don't originate from the SYNC_ONYX logic
if (event.key !== SYNC_ONYX || !event.newValue) {
return;
}
const onyxKey = event.newValue;
Storage.getItem(onyxKey)
.then(value => onStorageKeyChanged(onyxKey, value));
});
},
};
export default webStorage;