import { IndexedDBError } from './IndexedDBError' import type { CoreAccessors } from './core' import { getObjectStore } from './store' export async function putValue(accessors: CoreAccessors, value: T): Promise { const {storeName} = accessors.getConfig() try { const store = await getObjectStore(accessors, 'readwrite') await wrapVoidRequest(store.put(value), 'put', storeName) } catch (error) { throw ensureIndexedDBError(error, 'put', storeName) } } export async function addValue(accessors: CoreAccessors, value: T): Promise { const {storeName} = accessors.getConfig() try { const store = await getObjectStore(accessors, 'readwrite') await wrapVoidRequest(store.add(value), 'add', storeName) } catch (error) { throw ensureIndexedDBError(error, 'add', storeName) } } export async function deleteValue(accessors: CoreAccessors, key: string | number): Promise { const {storeName} = accessors.getConfig() try { const store = await getObjectStore(accessors, 'readwrite') await wrapVoidRequest(store.delete(key), 'delete', storeName) } catch (error) { throw ensureIndexedDBError(error, 'delete', storeName) } } export async function clearStore(accessors: CoreAccessors): Promise { const {storeName} = accessors.getConfig() try { const store = await getObjectStore(accessors, 'readwrite') await wrapVoidRequest(store.clear(), 'clear', storeName) } catch (error) { throw ensureIndexedDBError(error, 'clear', storeName) } } function wrapVoidRequest(requestParam: IDBRequest, operation: string, storeName: string): Promise { return new Promise((resolve, reject) => { const request = requestParam request.onsuccess = (): void => resolve() request.onerror = (): void => reject(new IndexedDBError(`Failed to ${operation}: ${request.error}`, operation, storeName, request.error)) }) } function ensureIndexedDBError(error: unknown, operation: string, storeName: string): IndexedDBError { if (error instanceof IndexedDBError) { return error } return new IndexedDBError(error instanceof Error ? error.message : 'Unknown error', operation, storeName, error) }