UNPKG

@tanstack/db

Version:

A reactive client store for building super fast apps on sync

214 lines (213 loc) • 8.65 kB
/** * Opens an IndexedDB database with the specified name and version. * A blocked request stays pending until native success or error. The caller * owns the returned connection and must close it when no longer needed. * * @param name - The name of the database to open * @param version - The version number of the database schema * @param onUpgrade - Optional callback that runs during the onupgradeneeded event. * Use this to create object stores and indexes. * @param idbFactory - Optional IDBFactory for testing/mocking (defaults to window.indexedDB or globalThis.indexedDB) * @param onBlocked - Optional diagnostic callback for native blocked events. The request stays pending. * @returns A promise that resolves to the IDBDatabase instance * * @example * ```typescript * const db = await openDatabase('myApp', 1, (db, oldVersion, newVersion, transaction) => { * if (oldVersion < 1) { * db.createObjectStore('todos', { keyPath: 'id' }) * } * }) * ``` */ export declare function openDatabase(name: string, version: number, onUpgrade?: (db: IDBDatabase, oldVersion: number, newVersion: number, transaction: IDBTransaction) => void, idbFactory?: IDBFactory, onBlocked?: (event: IDBVersionChangeEvent) => void): Promise<IDBDatabase>; /** * Creates an object store during a database upgrade. * * This function must be called within an onupgradeneeded callback * (i.e., within a versionchange transaction). Calling it outside of * an upgrade context will throw an error. * * @param db - The IDBDatabase instance * @param storeName - The name of the object store to create * @param options - Optional configuration for the object store (keyPath, autoIncrement) * @returns The created IDBObjectStore * @throws Error if not called during a version change transaction * * @example * ```typescript * const db = await openDatabase('myApp', 1, (db) => { * createObjectStore(db, 'todos', { keyPath: 'id' }) * createObjectStore(db, 'users', { keyPath: 'id', autoIncrement: true }) * }) * ``` */ export declare function createObjectStore(db: IDBDatabase, storeName: string, options?: IDBObjectStoreParameters): IDBObjectStore; /** * Executes a callback within an IndexedDB transaction. * * This function handles transaction lifecycle automatically: * - Creates the transaction with the specified mode * - Provides the transaction and object stores to the callback * - Waits for both the callback and the transaction to complete (or abort) * - Returns the callback's result or rejects with an error * * IndexedDB can commit while an async callback is still pending. If that callback * later rejects, this function rejects but cannot undo the committed writes. * * @template T - The return type of the callback * @param db - The IDBDatabase instance * @param storeNames - A single store name or array of store names to include in the transaction * @param mode - The transaction mode ('readonly', 'readwrite', or 'readwriteflush') * @param callback - A function that performs operations within the transaction. * Receives the transaction and a record of object stores keyed by name. * Can be sync or async. * @returns A promise that resolves to the callback's return value when the transaction completes * * @example * ```typescript * // Single store * const result = await executeTransaction(db, 'todos', 'readwrite', (tx, stores) => { * stores.todos.put({ id: 1, text: 'Buy milk' }) * return 'done' * }) * * // Multiple stores * await executeTransaction(db, ['todos', 'users'], 'readwrite', (tx, stores) => { * stores.todos.put({ id: 1, text: 'Task' }) * stores.users.put({ id: 1, name: 'Alice' }) * }) * ``` */ export declare function executeTransaction<T>(db: IDBDatabase, storeNames: string | Array<string>, mode: IDBTransactionMode, callback: (transaction: IDBTransaction, stores: Record<string, IDBObjectStore>) => T | Promise<T>): Promise<T>; /** * Retrieves all items from an object store. * * Uses the native `getAll()` method for efficient bulk retrieval. * * @template T - The type of items in the object store * @param objectStore - The IDBObjectStore to read from * @returns A promise that resolves to an array of all items in the store * * @example * ```typescript * await executeTransaction(db, 'todos', 'readonly', async (tx, stores) => { * const allTodos = await getAll<Todo>(stores.todos) * console.log('All todos:', allTodos) * }) * ``` */ export declare function getAll<T>(objectStore: IDBObjectStore): Promise<Array<T>>; /** * Retrieves all keys from an object store. * * Uses the native `getAllKeys()` method for efficient bulk key retrieval. * * @param objectStore - The IDBObjectStore to read keys from * @returns A promise that resolves to an array of all keys in the store * * @example * ```typescript * await executeTransaction(db, 'todos', 'readonly', async (tx, stores) => { * const allKeys = await getAllKeys(stores.todos) * console.log('All keys:', allKeys) * }) * ``` */ export declare function getAllKeys(objectStore: IDBObjectStore): Promise<Array<IDBValidKey>>; /** * Retrieves a single item by its key from an object store. * * @template T - The type of the item * @param objectStore - The IDBObjectStore to read from * @param key - The key of the item to retrieve * @returns A promise that resolves to the item, or undefined if not found * * @example * ```typescript * await executeTransaction(db, 'todos', 'readonly', async (tx, stores) => { * const todo = await getByKey<Todo>(stores.todos, 1) * if (todo) { * console.log('Found todo:', todo) * } * }) * ``` */ export declare function getByKey<T>(objectStore: IDBObjectStore, key: IDBValidKey): Promise<T | undefined>; /** * Writes an item to an object store using upsert semantics. * * If an item with the same key exists, it will be replaced. * If no item with the key exists, a new one will be created. * * @template T - The type of the item * @param objectStore - The IDBObjectStore to write to * @param value - The item to write * @param key - Optional key for the item. Required if the object store doesn't have a keyPath. * @returns A promise that resolves to the key of the written item * * @example * ```typescript * // With keyPath (key extracted from value) * await executeTransaction(db, 'todos', 'readwrite', async (tx, stores) => { * const key = await put(stores.todos, { id: 1, text: 'Buy milk' }) * console.log('Wrote item with key:', key) * }) * * // Without keyPath (explicit key) * await executeTransaction(db, 'items', 'readwrite', async (tx, stores) => { * const key = await put(stores.items, { text: 'Some data' }, 'myKey') * console.log('Wrote item with key:', key) * }) * ``` */ export declare function put<T>(objectStore: IDBObjectStore, value: T, key?: IDBValidKey): Promise<IDBValidKey>; /** * Deletes an item by its key from an object store. * * @param objectStore - The IDBObjectStore to delete from * @param key - The key of the item to delete * @returns A promise that resolves when the item is deleted * * @example * ```typescript * await executeTransaction(db, 'todos', 'readwrite', async (tx, stores) => { * await deleteByKey(stores.todos, 1) * console.log('Todo deleted') * }) * ``` */ export declare function deleteByKey(objectStore: IDBObjectStore, key: IDBValidKey): Promise<void>; /** * Removes all items from an object store. * * @param objectStore - The IDBObjectStore to clear * @returns A promise that resolves when all items are removed * * @example * ```typescript * await executeTransaction(db, 'todos', 'readwrite', async (tx, stores) => { * await clear(stores.todos) * console.log('All todos cleared') * }) * ``` */ export declare function clear(objectStore: IDBObjectStore): Promise<void>; /** * Deletes an entire IndexedDB database. * A blocked request stays pending until native success or error. * * Use with caution - this removes the database and all of its object stores and data. * * @param name - The name of the database to delete * @param idbFactory - Optional IDBFactory for testing/mocking * @param onBlocked - Optional diagnostic callback for native blocked events. The request stays pending. * @returns A promise that resolves when the database is deleted * * @example * ```typescript * await deleteDatabase('myApp') * console.log('Database deleted') * ``` */ export declare function deleteDatabase(name: string, idbFactory?: IDBFactory, onBlocked?: (event: IDBVersionChangeEvent) => void): Promise<void>;