@nent/core
Version:
84 lines (80 loc) • 2.92 kB
JavaScript
/*!
* NENT 2022
*/
import { r as registerInstance, a as getElement } from './index-916ca544.js';
import { a as actionBus, e as eventBus } from './index-f7016b94.js';
import { a as addDataProvider, r as removeDataProvider } from './factory-acbf0d3d.js';
import { D as DATA_COMMANDS } from './interfaces-4b724211.js';
import { D as DATA_EVENTS } from './interfaces-8c5cd1b8.js';
import './index-4bfabbbd.js';
import './values-ddfac998.js';
import './promises-584c4ece.js';
import './logging-5a93c8af.js';
/* It's a wrapper around the localStorage API that emits an event when the data changes */
class StorageService {
/**
* `constructor` is a function that is called when a new instance of the class is created
* @param {Window} win - Window - the window object
* @param {IEventEmitter} eventBus - This is the event bus that we created in the previous step.
* @param {string} name - The name of the provider. This is used to identify the provider when
* emitting events.
* @param {string} [prefix] - This is the prefix that will be used for all keys in the local storage.
*/
constructor(win, eventBus, name, prefix = '') {
this.eventBus = eventBus;
this.name = name;
this.prefix = prefix;
this.localStorage = win.localStorage;
window === null || window === void 0 ? void 0 : window.addEventListener('storage', () => {
this.eventBus.emit(DATA_EVENTS.DataChanged, {
provider: this.name,
});
}, { passive: true });
}
async get(key) {
var _a;
return ((_a = this.localStorage) === null || _a === void 0 ? void 0 : _a.getItem(this.prefix + key)) || null;
}
async set(key, value) {
var _a;
const existing = await this.get(key);
if (existing == value)
return;
(_a = this.localStorage) === null || _a === void 0 ? void 0 : _a.setItem(this.prefix + key, value);
this.eventBus.emit(DATA_EVENTS.DataChanged, {
provider: this.name,
});
}
}
const DataStorage = class {
constructor(hostRef) {
registerInstance(this, hostRef);
/**
* Provider name to use in nent expressions.
*/
this.name = 'storage';
}
registerProvider() {
addDataProvider(this.name, this.provider);
this.actionSubscription = actionBus.on(this.name, async (action) => {
if (action.command == DATA_COMMANDS.SetData) {
const { data } = action;
await Promise.all(Object.keys(action.data).map(key => this.provider.set(key, data[key])));
}
});
}
componentWillLoad() {
this.provider = new StorageService(window, eventBus, this.name, this.keyPrefix);
this.registerProvider();
}
disconnectedCallback() {
var _a;
removeDataProvider(this.name);
(_a = this.actionSubscription) === null || _a === void 0 ? void 0 : _a.call(this);
}
render() {
return null;
}
get el() { return getElement(this); }
};
export { DataStorage as n_data_storage };