SimpleChatTC:IDBHelper: Move core indexedDB helper as a module

ie opening db as well as a transaction to access a store within
the db.
This commit is contained in:
hanishkvc 2025-11-11 20:00:06 +05:30
parent f8c0fe6845
commit 52cce3e5f7
2 changed files with 50 additions and 28 deletions

View File

@ -0,0 +1,45 @@
//@ts-check
// Helpers to handle indexedDB provided by browsers
// by Humans for All
//
/**
* Allows the db connection to be openned.
* @param {string} dbName
* @param {string} storeName
* @param {string} callerTag
*/
export function db_open(dbName, storeName, callerTag="") {
let tag = `iDB:${callerTag}`
return new Promise((resolve, reject) => {
const dbConn = indexedDB.open(dbName, 1);
dbConn.onupgradeneeded = (ev) => {
console.debug(`DBUG:${tag}:Conn:Upgrade needed...`)
dbConn.result.createObjectStore(storeName);
dbConn.result.onerror = (ev) => {
console.info(`ERRR:${tag}:Db:Op failed [${ev}]...`)
}
};
dbConn.onsuccess = (ev) => {
console.debug(`INFO:${tag}:Conn:Opened...`)
resolve(dbConn.result);
}
dbConn.onerror = (ev) => {
console.info(`ERRR:${tag}:Conn:Failed [${ev}]...`)
reject(ev);
}
});
}
/**
* Get hold of a transaction wrt a specified store in the db
* @param {IDBDatabase} db
* @param {string} storeName
* @param {IDBTransactionMode} opMode
*/
export function db_trans_store(db, storeName, opMode) {
let dbTrans = db.transaction(storeName, opMode);
let dbOS = dbTrans.objectStore(storeName);
return dbOS
}

View File

@ -4,44 +4,21 @@
// by Humans for All
//
import * as mIdb from './idb.mjs'
/**
* Expects to get a message with cid, tcid, (f)name and args
* Posts message with cid, tcid, (f)name and data if any
*/
/**
* Allows the db connection to be openned.
*/
function db_open() {
return new Promise((resolve, reject) => {
const dbConn = indexedDB.open('TCDB', 1);
dbConn.onupgradeneeded = (ev) => {
console.debug("DBUG:WWDb:Conn:Upgrade needed...")
dbConn.result.createObjectStore('theDB');
dbConn.result.onerror = (ev) => {
console.info(`ERRR:WWDb:Db:Op failed [${ev}]...`)
}
};
dbConn.onsuccess = (ev) => {
console.debug("INFO:WWDb:Conn:Opened...")
resolve(dbConn.result);
}
dbConn.onerror = (ev) => {
console.info(`ERRR:WWDb:Conn:Failed [${ev}]...`)
reject(ev);
}
});
}
self.onmessage = async function (ev) {
try {
console.info(`DBUG:WWDb:${ev.data.name}:OnMessage started...`)
/** @type {IDBDatabase} */
let db = await db_open();
let dbTrans = db.transaction('theDB', 'readwrite');
let dbOS = dbTrans.objectStore('theDB');
let db = await mIdb.db_open("TCDB", "theDB", "WWDb");
let dbOS = mIdb.db_trans_store(db, "theDB", 'readwrite');
let args = ev.data.args;
switch (ev.data.name) {