@apicart/core-sdk
Version:
Apicart Core dependency for all SDKs
96 lines (75 loc) • 1.97 kB
text/typescript
import Utils from '@apicart/js-utils';
import Configurator from './Configurator';
class Storage
{
private readonly STORAGE_KEY = 'apicart-__APICART_PACKAGES_VERSION__';
private _cacheKey = null;
private _storage: Record<string, any> = {};
constructor()
{
this.init();
Utils.EventDispatcher.addListener('apicart-storage', 'apicart:configure', () => {
this.init();
});
}
public init(): void
{
this._cacheKey = Configurator.getParameter('storage.cacheKey');
const storage = Utils.LocalStorage.getItem(this.STORAGE_KEY);
if (storage && (!this._cacheKey || this._cacheKey === storage._cacheKey)) {
this._storage[this.STORAGE_KEY] = storage;
} else {
this.clearStorage();
}
}
public clearStorage(): void
{
this._storage = {};
this._storage[this.STORAGE_KEY] = {
_cacheKey: Configurator.getParameter('storage.cacheKey') || null
};
this.saveStorage();
}
public saveStorage(): void
{
Utils.LocalStorage.setItem(this.STORAGE_KEY, this.getStorage());
}
public find(keyPath: string): any | null
{
return Utils.Objects.find(this.getStorage(), keyPath);
}
public getStorage(): any
{
return this._storage[this.STORAGE_KEY];
}
public getItem(keyPath: string): any
{
const storage = Utils.LocalStorage.getItem(this.STORAGE_KEY);
return Utils.Objects.find(storage, keyPath);
}
public setItem(keyPath: string, value: any): void
{
Utils.Objects.assign(this.getStorage(), keyPath, value);
this.saveStorage();
}
public updateItem(keyPath: string, value: any): void
{
const item = this.getItem(keyPath);
if (!item) {
this.setItem(keyPath, value);
return;
}
Utils.Objects.merge(item, value);
this.setItem(keyPath, item);
}
public hasItem(keyPath: string): boolean
{
return this.getItem(keyPath) !== null;
}
public removeItem(keyPath: string): void
{
Utils.Objects.delete(this._storage[this.STORAGE_KEY], keyPath);
this.saveStorage();
}
}
export default new Storage();