Skip to content

Commit

Permalink
Sync StorageProxyObjects between windows
Browse files Browse the repository at this point in the history
  • Loading branch information
smithki committed Dec 20, 2019
1 parent 0825340 commit c1e1851
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
23 changes: 17 additions & 6 deletions src/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ import onChange from 'on-change';

// --- Types & constants ---------------------------------------------------- //

/** Web storage targets: `localStorage` and `sessionStorage`. */
export enum StorageTarget {
Local = 'localStorage',
Session = 'sessionStorage',
}

const namespaceSymbol = Symbol('namespaceSymbol');
const isStorageProxy = Symbol('isStorageProxy');
const storageTargetSymbol = Symbol('storageTargetSymbol');
Expand All @@ -12,12 +18,6 @@ const storageProxyIntegrityKey = '__storageProxyIntegrity';

const isStorageAvailableCache: Map<StorageTarget, boolean> = new Map();

/** Web storage targets: `localStorage` and `sessionStorage`. */
export enum StorageTarget {
Local = 'localStorage',
Session = 'sessionStorage',
}

/** The object type created by `StorageProxy.createLocalStorage()` and `StorageProxy.createSessionStorage()`. */
export type StorageProxyObject<TStorageDefinitions> = Partial<TStorageDefinitions> & {
readonly [namespaceSymbol]: string;
Expand Down Expand Up @@ -119,6 +119,17 @@ function createProxy<TStorageDefinitions extends any>(
},
});

// Sync a `StorageProxyObject` if changes occur to its namespace in another
// window.
window.addEventListener('storage', ev => {
if (StorageProxy.isStorageAvailable(storageTarget)) {
if (ev.key === namespace && ev.storageArea === window[storageTarget]) {
const data = getDataFromStorage(namespace, storageTarget);
for (const [key, value] of Object.entries(data)) storageProxy[key] = value;
}
}
});

if (defaults) {
for (const [key, value] of Object.entries(defaults)) {
if (isUndefined(data[key])) {
Expand Down
1 change: 1 addition & 0 deletions test/src/storage-proxy.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,7 @@ export class StorageProxyTestFixture {

@Test('Clearing `StorageProxy` removes all keys from both `WebStorage` and the local object')
public clearStorageTest() {
localStorage.clear();
StorageProxy.clearStorage(this.lStore);

Expect(this.lStore.alreadySetDefault).toBeNull();
Expand Down

0 comments on commit c1e1851

Please sign in to comment.