2026-01-13 14:49:19 +01:00

98 lines
3.0 KiB
TypeScript

import type { IndexedDBConfig } from './types'
import { IndexedDBError } from './IndexedDBError'
import { initDatabase, type CoreAccessors } from './core'
import { getObjectStore } from './store'
import { getAll, getAllByIndex, getByIndex, getValue } from './read'
import { addValue, clearStore, deleteValue, putValue } from './write'
import { count, countByIndex, openCursor, openCursorOnIndex } from './cursor'
export class IndexedDBHelper {
private db: IDBDatabase | null = null
private initPromise: Promise<void> | null = null
private readonly config: IndexedDBConfig
constructor(config: IndexedDBConfig) {
this.config = config
}
private accessors(): CoreAccessors {
return {
getDb: () => this.db,
setDb: (db) => {
this.db = db
},
getInitPromise: () => this.initPromise,
setInitPromise: (promise) => {
this.initPromise = promise
},
getConfig: () => this.config,
}
}
async init(): Promise<IDBDatabase> {
return initDatabase(this.accessors())
}
async getStore(mode: 'readonly'): Promise<IDBObjectStore> {
return getObjectStore(this.accessors(), mode)
}
async getStoreWrite(mode: 'readwrite'): Promise<IDBObjectStore> {
return getObjectStore(this.accessors(), mode)
}
async get<T = unknown>(key: string | number): Promise<T | null> {
return getValue<T>(this.accessors(), key)
}
async getByIndex<T = unknown>(indexName: string, key: string | number): Promise<T | null> {
return getByIndex<T>(this.accessors(), indexName, key)
}
async getAllByIndex<T = unknown>(indexName: string, key?: IDBValidKey | IDBKeyRange): Promise<T[]> {
return getAllByIndex<T>(this.accessors(), indexName, key)
}
async put<T = unknown>(value: T): Promise<void> {
return putValue<T>(this.accessors(), value)
}
async add<T = unknown>(value: T): Promise<void> {
return addValue<T>(this.accessors(), value)
}
async delete(key: string | number): Promise<void> {
return deleteValue(this.accessors(), key)
}
async clear(): Promise<void> {
return clearStore(this.accessors())
}
async openCursor(direction?: IDBCursorDirection, range?: IDBKeyRange): Promise<IDBCursorWithValue | null> {
return openCursor(this.accessors(), direction, range)
}
async openCursorOnIndex(indexName: string, direction?: IDBCursorDirection, range?: IDBKeyRange): Promise<IDBCursorWithValue | null> {
return openCursorOnIndex(this.accessors(), indexName, direction, range)
}
async count(range?: IDBKeyRange): Promise<number> {
return count(this.accessors(), range)
}
async countByIndex(indexName: string, range?: IDBKeyRange): Promise<number> {
return countByIndex(this.accessors(), indexName, range)
}
async getAll<T = unknown>(range?: IDBKeyRange, countParam?: number): Promise<T[]> {
return getAll<T>(this.accessors(), range, countParam)
}
}
export function assertIsIndexedDBError(error: unknown): asserts error is IndexedDBError {
if (!(error instanceof IndexedDBError)) {
throw error
}
}