service-utilities
Version:
Utility Package for FIORI UI5
77 lines (66 loc) • 2.17 kB
JavaScript
/**
* @module ServiceIndexedDB
* @description Utility Class to use the Persistent Local Database in the browser called IndexedDB
* @author jpanti
* @version 1.0.0
* @created 2025-08-01
* @lastModified 2025-08-01
* @license ISC
*/
sap.ui.define([], () => {
"use strict";
class ServiceIndexedDB {
#DB_NAME;
#STORE_NAME;
#DB_VERSION = 1;
getStoreName = () => this.#STORE_NAME;
constructor(storeName = "csvData", dbName = "FioriAppDB") {
return this.init(storeName, dbName);
}
init(storeName, dbName = "FioriAppDB") {
this.#DB_NAME = dbName;
this.#STORE_NAME = storeName;
return this;
}
async openDB() {
return new Promise((resolve, reject) => {
const request = indexedDB.open(this.#DB_NAME, this.#DB_VERSION);
request.onupgradeneeded = (event) => {
const db = event.target.result;
if (!db.objectStoreNames.contains(this.getStoreName())) {
db.createObjectStore(this.getStoreName(), { keyPath: "id" });
}
};
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
async save(id, content) {
const db = await this.openDB();
const tx = db.transaction(this.getStoreName(), "readwrite");
const store = tx.objectStore(this.getStoreName());
store.put({ id, content });
return tx.complete;
}
async load(id) {
const db = await this.openDB();
return new Promise((resolve, reject) => {
const tx = db.transaction(this.getStoreName(), "readonly");
const store = tx.objectStore(this.getStoreName());
const request = store.get(id);
request.onsuccess = () => {
return resolve(request.result?.content || null);
};
request.onerror = () => reject(request.error);
});
}
async delete(id) {
const db = await this.openDB();
const tx = db.transaction(this.getStoreName(), "readwrite");
const store = tx.objectStore(this.getStoreName());
store.delete(id);
return tx.complete;
}
}
return ServiceIndexedDB;
});