@microsoft/windows-admin-center-sdk
Version:
Microsoft - Windows Admin Center Shell
74 lines (72 loc) • 2.38 kB
JavaScript
import { fromEvent, of } from 'rxjs';
import { filter } from 'rxjs/operators';
import { LogLevel } from '../../diagnostics/log-level';
import { CachedDataStore } from './cached-data-store';
/**
* Defines a single value data store using browser storage as the underlying storage mechanism
* This is used as a base class for LocalDataStore and SessionDataStore which use LocalStorage and SessionStorage respectively
*/
export class BrowserStorageDataStore extends CachedDataStore {
storageKey;
storage;
/**
* Initializes a new instance of DataStore<T>
*/
constructor(storageKey, storage) {
super();
this.storageKey = storageKey;
this.storage = storage;
this.listenForStorageChanges();
}
/**
* Implementation to get the stored data
*/
getData() {
return this.storage ? of(this.storage.getItem(this.storageKey)) : of('');
}
/**
* Implementation to set the stored data
*/
setData(data) {
this.storage?.setItem(this.storageKey, data);
return of(null);
}
/**
* Implementation to clear the stored data
*/
clearData() {
this.storage?.removeItem(this.storageKey);
return of(null);
}
/**
* Transforms data in preparation for storage. Default behavior is no operation
*/
transformToStore(data) {
return JSON.stringify(data);
}
/**
* Transforms data in preparation for usage. Default behavior is no operation
*/
transformFromStore(storedData) {
let data = null;
try {
data = JSON.parse(storedData);
}
catch (error) {
this.log(`Failed to parse data retrieved with storage key: ${this.storageKey}`, LogLevel.Debug);
}
return data;
}
/**
* Listens for when other windows have modified our storage key and emits when the stored data has changed.
*/
listenForStorageChanges() {
this.rxjsLifetime.addSubscriptions(fromEvent(window, 'storage').pipe(filter((event) => {
return event.storageArea === this.storage && event.key === this.storageKey;
})).subscribe((event) => {
const data = this.transformFromStore(event.newValue);
this.dataChangedSubject.next(data);
}));
}
}
//# sourceMappingURL=browser-storage-data-store.js.map