diff --git a/src/utils/StorageAccess.ts b/src/utils/StorageAccess.ts index dc7eedb0d0b..90bf5e74a50 100644 --- a/src/utils/StorageAccess.ts +++ b/src/utils/StorageAccess.ts @@ -44,6 +44,27 @@ async function idbInit(): Promise { }); } +async function idbTransaction( + table: string, + mode: IDBTransactionMode, + fn: (objectStore: IDBObjectStore) => IDBRequest, +): Promise { + if (!idb) { + await idbInit(); + } + return new Promise((resolve, reject) => { + const txn = idb!.transaction([table], mode); + txn.onerror = reject; + + const objectStore = txn.objectStore(table); + const request = fn(objectStore); + request.onerror = reject; + request.onsuccess = (): void => { + resolve(request.result); + }; + }); +} + /** * Loads an item from an IndexedDB table within the underlying `matrix-react-sdk` database. * @@ -57,17 +78,7 @@ export async function idbLoad(table: string, key: string | string[]): Promise { - const txn = idb!.transaction([table], "readonly"); - txn.onerror = reject; - - const objectStore = txn.objectStore(table); - const request = objectStore.get(key); - request.onerror = reject; - request.onsuccess = (event): void => { - resolve(request.result); - }; - }); + return idbTransaction(table, "readonly", (objectStore) => objectStore.get(key)); } /** @@ -84,17 +95,7 @@ export async function idbSave(table: string, key: string | string[], data: any): if (!idb) { await idbInit(); } - return new Promise((resolve, reject) => { - const txn = idb!.transaction([table], "readwrite"); - txn.onerror = reject; - - const objectStore = txn.objectStore(table); - const request = objectStore.put(data, key); - request.onerror = reject; - request.onsuccess = (event): void => { - resolve(); - }; - }); + return idbTransaction(table, "readwrite", (objectStore) => objectStore.put(data, key)); } /** @@ -110,17 +111,7 @@ export async function idbDelete(table: string, key: string | string[]): Promise< if (!idb) { await idbInit(); } - return new Promise((resolve, reject) => { - const txn = idb!.transaction([table], "readwrite"); - txn.onerror = reject; - - const objectStore = txn.objectStore(table); - const request = objectStore.delete(key); - request.onerror = reject; - request.onsuccess = (): void => { - resolve(); - }; - }); + return idbTransaction(table, "readwrite", (objectStore) => objectStore.delete(key)); } /** @@ -135,15 +126,5 @@ export async function idbClear(table: string): Promise { if (!idb) { await idbInit(); } - return new Promise((resolve, reject) => { - const txn = idb!.transaction([table], "readwrite"); - txn.onerror = reject; - - const objectStore = txn.objectStore(table); - const request = objectStore.clear(); - request.onerror = reject; - request.onsuccess = (): void => { - resolve(); - }; - }); + return idbTransaction(table, "readwrite", (objectStore) => objectStore.clear()); }