Skip to content

Commit

Permalink
Merge pull request #27 from smithki/development
Browse files Browse the repository at this point in the history
v1.1.2
  • Loading branch information
smithki authored Dec 20, 2019
2 parents 192237a + 141a0fa commit 276a287
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 7 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "storage-proxy",
"version": "1.1.1",
"version": "1.1.2",
"description": "Use web storage (localStorage/sessionStorage) just like plain objects using ES6 Proxies.",
"author": "Ian K Smith <[email protected]>",
"license": "MIT",
Expand Down
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 276a287

Please sign in to comment.