ui5_easy_use
Version:
CLI tool for SAP ui5 and SAPUI5 projects to initialize apps, generate pages, insert form and table components, manage routing, and automate i18n bindings
75 lines (59 loc) • 1.97 kB
JavaScript
sap.ui.define([], function () {
"use strict";
return class LocalStorage {
constructor(controller) {
this._controller = controller;
}
saveToLocalStorage(key, newData) {
if (!this._isValidKey(key)) {
return;
}
const storage = this._getStorage();
const existingData = this.getFromLocalStorage(key);
const updatedData = this._mergeData(existingData, newData);
storage.setItem(key, JSON.stringify(updatedData));
}
getFromLocalStorage(key) {
if (!this._isValidKey(key)) {
return null;
}
const storedData = this._getStorage().getItem(key);
if (!storedData) {
return null;
}
try {
return JSON.parse(storedData);
} catch (error) {
console.error(`Error parsing local storage value for key "${key}".`, error);
return null;
}
}
removeFromLocalStorage(key) {
if (this._isValidKey(key)) {
this._getStorage().removeItem(key);
}
}
clearLocalStorage() {
this._getStorage().clear();
}
_mergeData(existingData, newData) {
if (Array.isArray(existingData)) {
return [...existingData, newData];
}
if (existingData && typeof existingData === "object" && !Array.isArray(newData)) {
return { ...existingData, ...newData };
}
return Array.isArray(newData) ? [newData] : newData;
}
_isValidKey(key) {
if (key) {
return true;
}
console.error("LocalStorage key cannot be empty.");
return false;
}
_getStorage() {
return window.localStorage;
}
};
});