Add only one, global storage event listener for all buckets

Signed-off-by: Dawit Ameneshewa <dawitam11@gmail.com>
This commit is contained in:
Dawit Ameneshewa
2022-12-06 17:53:26 +03:00
parent e2aaa67f62
commit e5dec1b386
2 changed files with 20 additions and 8 deletions
@@ -24,6 +24,14 @@ import ObservableImpl from 'zen-observable';
const buckets = new Map<string, WebStorage>();
window.addEventListener('storage', event => {
for (const [bucketPath, webStorage] of buckets.entries()) {
if (event.key?.startsWith(bucketPath)) {
webStorage.handleStorageChange(event.key);
}
}
});
/**
* An implementation of the storage API, that uses the browser's local storage.
*
@@ -89,17 +97,13 @@ export class WebStorage implements StorageApi {
observe$<T extends JsonValue>(
key: string,
): Observable<StorageValueSnapshot<T>> {
this.addStorageEventListener();
return this.observable.filter(({ key: messageKey }) => messageKey === key);
}
private addStorageEventListener() {
window.addEventListener('storage', event => {
if (event.key?.includes(this.namespace)) {
const key = event.key.replace(`${this.namespace}/`, '');
this.notifyChanges(key);
}
});
handleStorageChange(eventKey: StorageEvent['key']) {
if (!eventKey?.startsWith(this.namespace)) return;
const key = eventKey?.replace(`${this.namespace}/`, '');
this.notifyChanges(key);
}
private getKeyName(key: string) {
@@ -85,6 +85,14 @@ export interface StorageApi {
key: string,
): Observable<StorageValueSnapshot<T>>;
/**
* Synchronizes stored data across multiple tabs or windows by using the
* browser's StorageEvent API.
*
* @param eventKey - The key of a storage event object
*/
handleStorageChange(eventKey: StorageEvent['key']): void;
/**
* Returns an immediate snapshot value for the given key, if possible.
*