### IDB Setup, Data Add, and Index Query Example Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/idbpindex.md Demonstrates setting up an IndexedDB database with multiple indexes, adding records, and performing various index-based queries like get, getAll, iteration, and count. ```typescript import { openDB, DBSchema } from 'idb'; interface BookDB extends DBSchema { books: { key: number; value: { id: number; title: string; author: string; year: number; isbn: string; }; indexes: { 'by-author': string; 'by-year': number; 'by-isbn': string; }; }; } const db = await openDB('bookstore', 1, { upgrade(db) { const store = db.createObjectStore('books', { keyPath: 'id' }); store.createIndex('by-author', 'author'); store.createIndex('by-year', 'year'); store.createIndex('by-isbn', 'isbn', { unique: true }); }, }); // Add books const tx = db.transaction('books', 'readwrite'); await tx.store.add({ id: 1, title: 'Dune', author: 'Frank Herbert', year: 1965, isbn: '0441172717' }); await tx.store.add({ id: 2, title: 'Foundation', author: 'Isaac Asimov', year: 1951, isbn: '0553293369' }); await tx.done; // Query by author const tx2 = db.transaction('books', 'readonly'); const authorIndex = tx2.store.index('by-author'); // Get one book by author const asimovBook = await authorIndex.get('Isaac Asimov'); // Get all books by author const herbertBooks = await authorIndex.getAll('Frank Herbert'); // Iterate books in a year range for await (const cursor of authorIndex.iterate('Isaac Asimov')) { console.log(`${cursor.value.title} (${cursor.value.year})`); } // Count books by author const count = await authorIndex.count('Frank Herbert'); ``` -------------------------------- ### Run Development Server Source: https://github.com/jakearchibald/idb/blob/main/README.md Execute this command to start the development server and perform type testing. Ensure you have pnpm installed. ```sh pnpm run dev ``` -------------------------------- ### IDB Object Store Example Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/idbpobjectstore.md A comprehensive example demonstrating the setup of an IDB database with an object store, adding items, and then querying and iterating over the data. ```APIDOC ## Example ```typescript import { openDB, DBSchema } from 'idb'; interface AppDB extends DBSchema { products: { key: number; value: { id: number; name: string; price: number; category: string; }; indexes: { 'by-price': number; 'by-category': string; }; }; } const db = await openDB('store', 1, { upgrade(db) { const store = db.createObjectStore('products', { keyPath: 'id' }); store.createIndex('by-price', 'price'); store.createIndex('by-category', 'category'); }, }); // Add items const tx = db.transaction('products', 'readwrite'); const store = tx.store; await store.add({ id: 1, name: 'Widget', price: 9.99, category: 'gadgets' }); await store.add({ id: 2, name: 'Gizmo', price: 19.99, category: 'gadgets' }); await tx.done; // Query and iterate const tx2 = db.transaction('products', 'readonly'); const store2 = tx2.store; for await (const cursor of store2.iterate()) { console.log(cursor.key, cursor.value.name); } const expensive = await store2.index('by-price').getAll(IDBKeyRange.lowerBound(15)); ``` ``` -------------------------------- ### Install idb via npm Source: https://github.com/jakearchibald/idb/blob/main/README.md Use this command to install the idb library using npm. This is the recommended method for module-compatible build systems. ```sh npm install idb ``` -------------------------------- ### ProductStore Schema Example Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/types.md An example interface defining a product store schema, including its key, value, and the types for its indexes. ```typescript interface ProductStore extends DBSchemaValue { key: number; value: { id: number; name: string; price: number; category: string }; indexes: { 'by-price': number; // Price index keys are numbers 'by-category': string; // Category index keys are strings 'by-sku': string; // SKU index keys are strings }; } ``` -------------------------------- ### Shortcut Methods (CRUD Operations) Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/idbpdatabase.md Provides examples of using shortcut methods for common CRUD operations on object stores, such as `put`, `get`, and `getFromIndex`. ```APIDOC ## Shortcut Methods ### Description Shortcut methods provide a concise way to perform single operations on an object store. These methods implicitly create a transaction. ### Methods - **`db.put(storeName, value, key?)`**: Adds or updates a record in the specified object store. - **`db.get(storeName, key)`**: Retrieves a record from the specified object store by its key. - **`db.getFromIndex(storeName, indexName, key)`**: Retrieves a record from an index by its key. ### Parameters - **`storeName`** (string) - The name of the object store. - **`key`** - The key of the record to retrieve or the key for the value being put. - **`value`** - The value to add or update. - **`indexName`** (string) - The name of the index to query. ### Request Example ```typescript // Shortcut methods await db.put('users', { id: 1, name: 'Alice', email: 'alice@example.com' }); const user = await db.get('users', 1); const byEmail = await db.getFromIndex('users', 'by-email', 'alice@example.com'); ``` ``` -------------------------------- ### IDB Index Operations Example Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/idbpindex.md An example demonstrating how to open a database, define indexes, add data, and then query, iterate, and count records using these indexes. ```APIDOC ## Example Usage ```typescript import { openDB, DBSchema } from 'idb'; interface BookDB extends DBSchema { books: { key: number; value: { id: number; title: string; author: string; year: number; isbn: string; }; indexes: { 'by-author': string; 'by-year': number; 'by-isbn': string; }; }; } const db = await openDB('bookstore', 1, { upgrade(db) { const store = db.createObjectStore('books', { keyPath: 'id' }); store.createIndex('by-author', 'author'); store.createIndex('by-year', 'year'); store.createIndex('by-isbn', 'isbn', { unique: true }); }, }); // Add books const tx = db.transaction('books', 'readwrite'); await tx.store.add({ id: 1, title: 'Dune', author: 'Frank Herbert', year: 1965, isbn: '0441172717' }); await tx.store.add({ id: 2, title: 'Foundation', author: 'Isaac Asimov', year: 1951, isbn: '0553293369' }); await tx.done; // Query by author const tx2 = db.transaction('books', 'readonly'); const authorIndex = tx2.store.index('by-author'); // Get one book by author const asimovBook = await authorIndex.get('Isaac Asimov'); // Get all books by author const herbertBooks = await authorIndex.getAll('Frank Herbert'); // Iterate books in a year range for await (const cursor of authorIndex.iterate('Isaac Asimov')) { console.log(`${cursor.value.title} (${cursor.value.year})`); } // Count books by author const count = await authorIndex.count('Frank Herbert'); ``` ``` -------------------------------- ### Get User by Email using Index Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/idbpobjectstore.md An example demonstrating how to retrieve a user record by querying an index named 'by-email' with a specific email address. ```typescript const emailIndex = store.index('by-email'); const user = await emailIndex.get('alice@example.com'); ``` -------------------------------- ### Basic Database Creation and Operations Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/opendb.md Demonstrates opening a database, defining a simple object store during upgrade, and performing basic put and get operations. ```typescript import { openDB } from 'idb'; const db = await openDB('my-db', 1, { upgrade(db, oldVersion, newVersion, transaction) { if (oldVersion < 1) { db.createObjectStore('items', { keyPath: 'id' }); }, }, }); await db.put('items', { id: 1, name: 'Widget' }); const item = await db.get('items', 1); ``` -------------------------------- ### Full IDB Database Setup and Operations Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/idbpobjectstore.md Demonstrates opening a database, defining its schema, creating an object store and indexes, adding data, and performing read operations. ```typescript import { openDB, DBSchema } from 'idb'; interface AppDB extends DBSchema { products: { key: number; value: { id: number; name: string; price: number; category: string; }; indexes: { 'by-price': number; 'by-category': string; }; }; } const db = await openDB('store', 1, { upgrade(db) { const store = db.createObjectStore('products', { keyPath: 'id' }); store.createIndex('by-price', 'price'); store.createIndex('by-category', 'category'); }, }); // Add items const tx = db.transaction('products', 'readwrite'); const store = tx.store; await store.add({ id: 1, name: 'Widget', price: 9.99, category: 'gadgets' }); await store.add({ id: 2, name: 'Gizmo', price: 19.99, category: 'gadgets' }); await tx.done; // Query and iterate const tx2 = db.transaction('products', 'readonly'); const store2 = tx2.store; for await (const cursor of store2.iterate()) { console.log(cursor.key, cursor.value.name); } const expensive = await store2.index('by-price').getAll(IDBKeyRange.lowerBound(15)); ``` -------------------------------- ### Put Example Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/idbpobjectstore.md An example of using the `put` method to add or update a record with an ID and name. If a record with `id: 1` already exists, it will be replaced. ```typescript const newId = await store.put({ id: 1, name: 'Alice' }); // Replaces if id=1 exists ``` -------------------------------- ### Article store setup and operations Source: https://github.com/jakearchibald/idb/blob/main/README.md Demonstrates setting up an 'articles' object store with a key path and an index on 'date'. Includes adding articles, retrieving them by date, and updating existing ones. ```javascript import { openDB } from 'idb/with-async-ittr.js'; async function demo() { const db = await openDB('Articles', 1, { upgrade(db) { // Create a store of objects const store = db.createObjectStore('articles', { // The 'id' property of the object will be the key. keyPath: 'id', // If it isn't explicitly set, create a value by auto incrementing. autoIncrement: true, }); // Create an index on the 'date' property of the objects. store.createIndex('date', 'date'); }, }); // Add an article: await db.add('articles', { title: 'Article 1', date: new Date('2019-01-01'), body: '…', }); // Add multiple articles in one transaction: { const tx = db.transaction('articles', 'readwrite'); await Promise.all([ tx.store.add({ title: 'Article 2', date: new Date('2019-01-01'), body: '…', }), tx.store.add({ title: 'Article 3', date: new Date('2019-01-02'), body: '…', }), tx.done, ]); } // Get all the articles in date order: console.log(await db.getAllFromIndex('articles', 'date')); // Add 'And, happy new year!' to all articles on 2019-01-01: { const tx = db.transaction('articles', 'readwrite'); const index = tx.store.index('date'); for await (const cursor of index.iterate(new Date('2019-01-01'))) { const article = { ...cursor.value }; article.body += ' And, happy new year!'; cursor.update(article); } await tx.done; } } ``` -------------------------------- ### Key-only Cursor Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/idbpcursor.md Example of opening a key-only cursor for efficiency when only keys are needed, demonstrating access to `key` and `primaryKey`. ```APIDOC ### Key-only cursor (for efficiency) ```typescript const tx = db.transaction('products', 'readonly'); let cursor = await tx.store.openKeyCursor(); while (cursor) { console.log('Key:', cursor.key); console.log('Primary Key:', cursor.primaryKey); // No .value property cursor = await cursor.continue(); } ``` ``` -------------------------------- ### Example Usage of StoreKey Type Utility Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/types.md Demonstrates how to use the StoreKey type utility to infer the type of the key for a 'users' object store. ```typescript type UserKey = StoreKey; // number ``` -------------------------------- ### Data Migration During Upgrade Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/idbptransaction.md Provides an example of performing data migration tasks within the `upgrade` callback of `openDB`. ```APIDOC ## Data migration during upgrade ```typescript const db = await openDB('mydb', 2, { async upgrade(db, oldVersion, newVersion, transaction) { if (oldVersion < 1) { db.createObjectStore('v1Store'); } if (oldVersion < 2) { // transaction provides access to all stores for migration const v1Store = transaction.objectStore('v1Store'); const items = await v1Store.getAll(); // Create new store const v2Store = db.createObjectStore('v2Store', { keyPath: 'id' }); // Migrate data for (const item of items) { await v2Store.put({ id: item.key, data: item.value, migratedAt: Date.now(), }); } } }, }); ``` ``` -------------------------------- ### StoreNames Type Utility Example Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/types.md Demonstrates how the StoreNames utility type infers a union of store names from a given database schema. ```typescript interface MyDB extends DBSchema { users: { /* ... */ }; posts: { /* ... */ }; tags: { /* ... */ }; } type Stores = StoreNames; // 'users' | 'posts' | 'tags' ``` -------------------------------- ### get Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/idbpobjectstore.md Retrieves the first value matching a query. Available in all modes. ```APIDOC ## get ### Description Retrieves the first value matching a query. ### Method Signature ```typescript get( query: StoreKey | IDBKeyRange ): Promise | undefined> ``` ### Returns Promise resolving to the value, or `undefined` if not found. ### Available in modes All ### Example ```typescript const user = await store.get(1); const result = await store.get(IDBKeyRange.bound(1, 100)); ``` ``` -------------------------------- ### Example Usage of IndexKey Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/types.md Demonstrates how to use the IndexKey utility to infer the type of a specific index. This helps in understanding the expected data types for index lookups. ```typescript type EmailKey = IndexKey; // string ``` -------------------------------- ### Example of IDBTransactionOptions Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/types.md Demonstrates how to create a transaction with a 'relaxed' durability setting for potentially faster, though less durable, operations. ```typescript const tx = db.transaction('store', 'readwrite', { durability: 'relaxed' // Faster, but less durable }); ``` -------------------------------- ### Example Usage of StoreValue Type Utility Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/types.md Demonstrates how to use the StoreValue type utility to infer the type of data stored in a 'users' object store. ```typescript type UserValue = StoreValue; // { id: number; name: string; ... } ``` -------------------------------- ### IDBValidKey Usage Examples Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/types.md Demonstrates how to use various types of IDBValidKey values when putting data into an IndexedDB database. ```typescript // Simple string key db.put('users', user, 'alice@example.com'); ``` ```typescript // Numeric key db.put('items', item, 123); ``` ```typescript // Date key db.put('events', event, new Date('2024-01-01')); ``` ```typescript // Compound key (object) db.put('transactions', tx, { date: new Date(), accountId: 5 }); ``` ```typescript // Array key db.put('sequences', data, [1, 2, 3]); ``` -------------------------------- ### Get All Records Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/README.md Retrieves all records from an object store. ```APIDOC ## Get All Records ### Description Retrieves all records from a specified object store. ### Method `db.getAll(storeName)` or `store.getAll()` ### Parameters - **storeName** (string) - The name of the object store. ### Request Example ```javascript const allUsers = await db.getAll('users'); ``` ``` -------------------------------- ### Start IDBP Transaction Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/idbpdatabase.md Initiate a transaction for reading or writing to one or more object stores. Use 'readwrite' mode for modifications and await tx.done for completion. ```typescript const tx = db.transaction(['users', 'posts'], 'readwrite'); await tx.objectStore('users').put(user); await tx.objectStore('posts').put(post); await tx.done; ``` -------------------------------- ### get Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/idbpindex.md Retrieves the first value matching a query in the index. It requires a query to specify the search criteria. ```APIDOC ## get ### Description Retrieves the first value matching a query in the index. ### Method ```typescript get( query: IndexKey | IDBKeyRange, ): Promise | undefined> ``` ### Parameters #### Query Parameters - **query** (Index key or `IDBKeyRange`) - Required - The index key or range to search ### Returns Promise resolving to the first matching value, or `undefined` if not found. ### Example ```typescript const userIndex = store.index('by-email'); const user = await userIndex.get('alice@example.com'); ``` ``` -------------------------------- ### Complete Chat Database Schema Example Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/types.md Illustrates a complete and realistic schema for a chat application database using idb. This includes defining object stores, their key paths, values, and indexes, along with the upgrade function to create these structures. It also shows type-safe queries for retrieving data. ```typescript import { openDB, DBSchema } from 'idb'; interface ChatDatabase extends DBSchema { conversations: { key: string; value: { id: string; participants: string[]; createdAt: Date; updatedAt: Date; archived: boolean; }; indexes: { 'by-updated': number; }; }; messages: { key: number; value: { id: number; conversationId: string; senderId: string; text: string; sentAt: Date; edited: boolean; }; indexes: { 'by-conversation': string; 'by-sender': string; 'by-date': number; }; }; users: { key: string; value: { id: string; username: string; email: string; avatar: Blob; status: 'online' | 'offline' | 'away'; lastSeen: Date; }; indexes: { 'by-email': string; 'by-status': string; }; }; } const db = await openDB('chat', 1, { upgrade(db) { const convStore = db.createObjectStore('conversations', { keyPath: 'id' }); convStore.createIndex('by-updated', 'updatedAt'); const msgStore = db.createObjectStore('messages', { keyPath: 'id', autoIncrement: true }); msgStore.createIndex('by-conversation', 'conversationId'); msgStore.createIndex('by-sender', 'senderId'); msgStore.createIndex('by-date', 'sentAt'); const userStore = db.createObjectStore('users', { keyPath: 'id' }); userStore.createIndex('by-email', 'email', { unique: true }); userStore.createIndex('by-status', 'status'); }, }); // Type-safe queries const user = await db.get('users', 'alice'); const msgsByConv = await db.getAllFromIndex('messages', 'by-conversation', 'conv123'); const onlineUsers = await db.getAllFromIndex('users', 'by-status', 'online'); ``` -------------------------------- ### Example Usage of IndexNames Type Utility Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/types.md Demonstrates how to use the IndexNames type utility to infer the union type of index names for a 'users' object store. ```typescript type UserIndexes = IndexNames; // 'by-email' | 'by-created' ``` -------------------------------- ### Async Iteration over Object Store Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/README.md Provides an example of asynchronously iterating over records in an object store using `for await...of`. ```typescript for await (const cursor of store) { console.log(cursor.key, cursor.value); } ``` -------------------------------- ### Import and use idb in JavaScript modules Source: https://github.com/jakearchibald/idb/blob/main/README.md Import necessary functions from the idb library for use in your JavaScript module system. This example shows how to open a database. ```js import { openDB, deleteDB, wrap, unwrap } from 'idb'; async function doDatabaseStuff() { const db = await openDB(…); } ``` -------------------------------- ### Key-Value Store Implementation Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/README.md Provides functions to get and set key-value pairs, acting as an alternative to localStorage. Requires opening a database with an 'keyval' object store. ```typescript const db = await openDB('keyval', 1, { upgrade(db) { db.createObjectStore('keyval'); }, }); export async function get(key) { return await db.get('keyval', key); } export async function set(key, val) { return await db.put('keyval', val, key); } ``` -------------------------------- ### Create Key Ranges for Cursor Filtering Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/idbpcursor.md These examples show how to create different types of IDBKeyRange objects to filter records when opening a cursor. This allows for precise selection of data based on key values. ```typescript const range = IDBKeyRange.bound(10, 100); ``` ```typescript const range = IDBKeyRange.lowerBound(10); ``` ```typescript const range = IDBKeyRange.upperBound(100); ``` ```typescript const range = IDBKeyRange.only(50); ``` ```typescript // Iterate let cursor = await store.openCursor(range); ``` -------------------------------- ### Accessing Data with Promises Source: https://github.com/jakearchibald/idb/blob/main/README.md Methods that typically return `IDBRequest` objects now return promises, simplifying asynchronous data retrieval. This example shows fetching a value from an object store. ```javascript const store = db.transaction(storeName).objectStore(storeName); const value = await store.get(key); ``` -------------------------------- ### IDB Schema Version 1: Initial Schema Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/configuration.md Example of opening a database with version 1 and creating an initial object store named 'users'. This is used for the first time the database is created or when migrating from a version prior to 1. ```typescript // Version 1: Initial schema await openDB('mydb', 1, { upgrade(db, oldVersion) { if (oldVersion < 1) { db.createObjectStore('users'); } } }); ``` -------------------------------- ### IDB Schema Version 2: Add New Store Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/configuration.md Example of upgrading a database to version 2. It includes the logic for version 1 and adds a new object store named 'posts'. This ensures that if the database is at version 1, the 'posts' store is created. ```typescript // Later: Version 2: Add new store await openDB('mydb', 2, { upgrade(db, oldVersion) { if (oldVersion < 1) { db.createObjectStore('users'); } if (oldVersion < 2) { db.createObjectStore('posts'); } } }); ``` -------------------------------- ### Get Value from Object Store Source: https://github.com/jakearchibald/idb/blob/main/README.md Use this shortcut to retrieve a value from a specified object store within a database. It simplifies the process by handling transaction creation internally. ```javascript const value = await db.get(storeName, key); ``` -------------------------------- ### Keyval store basic operations Source: https://github.com/jakearchibald/idb/blob/main/README.md Provides basic asynchronous functions (get, set, delete, clear, keys) for a key-value store using IDB. This is similar to localStorage but asynchronous. ```javascript import { openDB } from 'idb'; const dbPromise = openDB('keyval-store', 1, { upgrade(db) { db.createObjectStore('keyval'); }, }); export async function get(key) { return (await dbPromise).get('keyval', key); } export async function set(key, val) { return (await dbPromise).put('keyval', val, key); } export async function del(key) { return (await dbPromise).delete('keyval', key); } export async function clear() { return (await dbPromise).clear('keyval'); } export async function keys() { return (await dbPromise).getAllKeys('keyval'); } ``` -------------------------------- ### Handling Blocked Deletion with Callbacks Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/deletedb.md This example shows how to handle cases where an IndexedDB database cannot be deleted immediately due to open connections. A callback is provided to log a warning when the deletion is blocked. ```typescript await deleteDB('my-db', { blocked(currentVersion, event) { console.warn( `Cannot delete database: v${currentVersion} still open` ); // Optionally notify user: "Close other tabs with this site" }, }); ``` -------------------------------- ### IDB Schema Version 3: Modify Existing Store Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/configuration.md Example of upgrading a database to version 3. It includes the logic for versions 1 and 2, and then modifies the 'users' object store by creating an index named 'by-email'. This demonstrates how to access and modify existing stores during an upgrade. ```typescript // Even later: Version 3: Modify existing store await openDB('mydb', 3, { upgrade(db, oldVersion) { if (oldVersion < 1) { db.createObjectStore('users'); } if (oldVersion < 2) { db.createObjectStore('posts'); } if (oldVersion < 3) { const users = db.objectStore('users'); // Access existing store users.createIndex('by-email', 'email'); } } }); ``` -------------------------------- ### Basic Database Creation with Schema Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/opendb.md Demonstrates how to open an IndexedDB database and create an object store with a specified key path. It also shows how to add and retrieve data. ```APIDOC ## Basic database creation with schema ### Description Opens an IndexedDB database named 'my-db' with version 1. If the database is new or the version is less than 1, it creates an object store named 'items' with 'id' as the key path. It then demonstrates adding an item to the 'items' store and retrieving it. ### Method `openDB` ### Parameters - `name` (string): 'my-db' - `version` (number): 1 - `options` (object): - `upgrade` (function): Callback function for database upgrades. - `db` (IDBDatabase): The database instance. - `oldVersion` (number): The previous version of the database. - `newVersion` (number): The new version of the database. - `transaction` (IDBTransaction): The transaction object for the upgrade. ### Request Example ```typescript import { openDB } from 'idb'; const db = await openDB('my-db', 1, { upgrade(db, oldVersion, newVersion, transaction) { if (oldVersion < 1) { db.createObjectStore('items', { keyPath: 'id' }); } }, }); await db.put('items', { id: 1, name: 'Widget' }); const item = await db.get('items', 1); ``` ### Response #### Success Response (IDBDatabase) Returns a promise that resolves to an `IDBDatabase` instance. #### Response Example ```json { "example": "IDBDatabase instance" } ``` ``` -------------------------------- ### Valid Transaction Lifetime Management Source: https://github.com/jakearchibald/idb/blob/main/README.md This example demonstrates a correct transaction flow where asynchronous operations like fetching data do not occur between the start and end of the transaction. Ensure all database operations within a transaction complete before awaiting external operations. ```javascript const tx = db.transaction('keyval', 'readwrite'); const store = tx.objectStore('keyval'); const val = (await store.get('counter')) || 0; await store.put(val + 1, 'counter'); await tx.done; ``` -------------------------------- ### Get all keys matching a query Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/idbpdatabase.md Use `getAllKeys` to retrieve all keys from an object store that match a given query. Similar to `getAll`, it accepts an optional count parameter. This is useful for retrieving identifiers without fetching the full data. ```typescript getAllKeys>( storeName: Name, query?: StoreKey | IDBKeyRange | null, count?: number, ): Promise[]> ``` ```typescript const userIds = await db.getAllKeys('users'); ``` -------------------------------- ### Opening and Upgrading a Database Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/idbpdatabase.md Demonstrates how to open an IndexedDB database using `openDB` and define its schema using the `upgrade` callback. This includes creating object stores and indexes. ```APIDOC ## openDB(dbName: string, version: number, upgradeCallback: { upgrade: (db: IDBPDatabase) => void }) ### Description Opens an IndexedDB database with the specified name and version. If the database does not exist or the version is higher than the current one, the `upgrade` callback is executed to define or modify the schema. ### Parameters - **dbName** (string) - The name of the database. - **version** (number) - The version of the database. - **upgradeCallback** (object) - An object containing the `upgrade` function. - **upgrade** (function) - A callback function that receives the database instance and is responsible for creating object stores and indexes. ### Example ```typescript import { openDB, DBSchema } from 'idb'; interface AppDB extends DBSchema { users: { key: number; value: { id: number; name: string; email: string }; indexes: { 'by-email': string }; }; posts: { key: number; value: { id: number; userId: number; title: string; content: string }; indexes: { 'by-userId': number }; }; } async function main() { const db = await openDB('app', 1, { upgrade(db) { const userStore = db.createObjectStore('users', { keyPath: 'id' }); userStore.createIndex('by-email', 'email', { unique: true }); const postStore = db.createObjectStore('posts', { keyPath: 'id', autoIncrement: true }); postStore.createIndex('by-userId', 'userId'); }, }); } ``` ``` -------------------------------- ### Database Opening with Event Callbacks Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/opendb.md Illustrates how to handle database opening events, including upgrade logic for multiple versions, and callbacks for blocked, blocking, and terminated connections. ```typescript const db = await openDB('my-db', 2, { upgrade(db, oldVersion) { if (oldVersion < 1) { db.createObjectStore('v1-store'); } if (oldVersion < 2) { db.createObjectStore('v2-store'); } }, blocked(currentVersion, blockedVersion) { console.warn( `Database open blocked: v${blockedVersion} blocked by v${currentVersion}` ); // Maybe prompt user: "Please close other tabs with this site open" }, blocking(currentVersion, blockedVersion) { console.log(`This connection (v${currentVersion}) is blocking v${blockedVersion}`); // Maybe: this.close(); // Allow the new version to open }, terminated() { console.error('Database connection terminated by browser'); }, }); ``` -------------------------------- ### Get a single value by key Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/idbpdatabase.md Use `get` to retrieve a single value from an object store using its key. It returns `undefined` if the value is not found. Supports key ranges for more flexible queries. ```typescript get>( storeName: Name, query: StoreKey | IDBKeyRange, ): Promise | undefined> ``` ```typescript const user = await db.get('users', 1); const user2 = await db.get('users', IDBKeyRange.bound(1, 10)); ``` -------------------------------- ### Get the first value matching a query in an index Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/idbpindex.md Use `get()` to retrieve the first record's value that matches a given index key or range. Returns `undefined` if no match is found. ```typescript const userIndex = store.index('by-email'); const user = await userIndex.get('alice@example.com'); ``` -------------------------------- ### Opening a Database Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/README.md Demonstrates how to open or create an IndexedDB database using the `openDB` function. It includes setting up an upgrade function to create object stores. ```APIDOC ## Opening a Database ### Description Opens or creates an IndexedDB database. The `upgrade` callback is used to define the database schema, including creating object stores. ### Method `openDB(name: string, version: number, { upgrade: function }): Promise ` ### Parameters - **name** (string) - The name of the database. - **version** (number) - The version of the database. - **upgrade** (function) - A callback function that is executed when the database is opened for the first time or when the version increases. It receives the database instance and should be used to create or modify object stores. ### Request Example ```typescript import { openDB } from 'idb'; const db = await openDB('my-db', 1, { upgrade(db) { db.createObjectStore('users', { keyPath: 'id' }); }, }); ``` ``` -------------------------------- ### Invalid Transaction Lifetime Example Source: https://github.com/jakearchibald/idb/blob/main/README.md This example illustrates a common pitfall where awaiting an external operation (like `fetch`) between database operations causes the transaction to close prematurely. This leads to errors when subsequent database operations are attempted. ```javascript const tx = db.transaction('keyval', 'readwrite'); const store = tx.objectStore('keyval'); const val = (await store.get('counter')) || 0; // This is where things go wrong: const newVal = await fetch('/increment?val=' + val); // And this throws an error: await store.put(newVal, 'counter'); await tx.done; ``` -------------------------------- ### Database Opening with Event Callbacks Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/opendb.md Shows how to open an IndexedDB database and handle various connection events like `blocked`, `blocking`, and `terminated`. ```APIDOC ## With event callbacks ### Description Opens an IndexedDB database named 'my-db' with version 2, including callbacks for managing database connection events. The `upgrade` callback handles schema changes for versions less than 1 and 2. The `blocked`, `blocking`, and `terminated` callbacks provide hooks for handling connection-related events. ### Method `openDB` ### Parameters - `name` (string): 'my-db' - `version` (number): 2 - `options` (object): - `upgrade` (function): Callback for database upgrades. - `db` (IDBDatabase): The database instance. - `oldVersion` (number): The previous version of the database. - `blocked` (function): Callback when the database open is blocked. - `currentVersion` (number): The current version of the database. - `blockedVersion` (number): The version that is blocked. - `blocking` (function): Callback when this connection is blocking a new version. - `currentVersion` (number): The current version of this connection. - `blockedVersion` (number): The version that is being blocked. - `terminated` (function): Callback when the database connection is terminated. ### Request Example ```typescript const db = await openDB('my-db', 2, { upgrade(db, oldVersion) { if (oldVersion < 1) { db.createObjectStore('v1-store'); } if (oldVersion < 2) { db.createObjectStore('v2-store'); } }, blocked(currentVersion, blockedVersion) { console.warn( `Database open blocked: v${blockedVersion} blocked by v${currentVersion}` ); // Maybe prompt user: "Please close other tabs with this site open" }, blocking(currentVersion, blockedVersion) { console.log(`This connection (v${currentVersion}) is blocking v${blockedVersion}`); // Maybe: this.close(); // Allow the new version to open }, terminated() { console.error('Database connection terminated by browser'); }, }); ``` ### Response #### Success Response (IDBDatabase) Returns a promise that resolves to an `IDBDatabase` instance. #### Response Example ```json { "example": "IDBDatabase instance with event handlers" } ``` ``` -------------------------------- ### Get Record by Index Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/README.md Retrieves a record from an object store using an index. ```APIDOC ## Get Record by Index ### Description Retrieves a single record from an object store using a specific index. ### Method `db.getFromIndex(storeName, indexName, key)` or `index.get(key)` ### Parameters - **storeName** (string) - The name of the object store. - **indexName** (string) - The name of the index to use. - **key** (any) - The key to search for in the index. ### Request Example ```javascript const user = await db.getFromIndex('users', 'by-email', 'a@b.com'); ``` ``` -------------------------------- ### opendb Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/README.md Opens or creates a database with optional schema upgrade callbacks. Use this to create or open a database with version management. ```APIDOC ## opendb ### Description Opens or creates a database with optional schema upgrade callbacks. ### Method [Method not specified in source] ### Endpoint [Endpoint not specified in source] ### Parameters [Parameters not specified in source] ### Request Example [Request example not specified in source] ### Response [Response not specified in source] ``` -------------------------------- ### Creating and Querying Indexes in IDB Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/README.md Demonstrates how to create indexes with unique or multi-entry constraints and query data using these indexes. ```typescript // Create index during upgrade store.createIndex('by-email', 'email', { unique: true }); store.createIndex('by-tags', 'tags', { multiEntry: true }); // Query by index const user = await db.getFromIndex('users', 'by-email', 'alice@example.com'); // Multi-entry: each array element is indexed separately const tagged = await db.getAllFromIndex('posts', 'by-tags', 'react'); ``` -------------------------------- ### Get Record by Key Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/README.md Retrieves a record from an object store using its primary key. ```APIDOC ## Get Record by Key ### Description Retrieves a single record from an object store using its primary key. ### Method `db.get(storeName, key)` or `store.get(key)` ### Parameters - **storeName** (string) - The name of the object store. - **key** (any) - The key of the record to retrieve. ### Request Example ```javascript const user = await db.get('users', 1); ``` ``` -------------------------------- ### get Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/idbpdatabase.md Retrieves a single value from an object store by its key. If the key is not found, it returns undefined. ```APIDOC ## get ### Description Retrieves a single value from a store by key. ### Method Signature ```typescript get>( storeName: Name, query: StoreKey | IDBKeyRange, ): Promise | undefined> ``` ### Parameters #### Path Parameters * **storeName** (`StoreNames`) - Name of the object store * **query** (`StoreKey | IDBKeyRange`) - The key to look up or a key range ### Returns Promise resolving to the value, or `undefined` if not found. ### Example ```typescript const user = await db.get('users', 1); const user2 = await db.get('users', IDBKeyRange.bound(1, 10)); ``` ``` -------------------------------- ### Selective Deletion with Cursor Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/idbpcursor.md Example of using a cursor to selectively delete records based on a condition, such as expiration. ```APIDOC ### Selective deletion ```typescript const tx = db.transaction('cache', 'readwrite'); for await (const cursor of tx.store) { const now = Date.now(); if (cursor.value.expiresAt < now) { await cursor.delete(); } } await tx.done; ``` ``` -------------------------------- ### Basic Async Iteration Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/idbpcursor.md Demonstrates how to iterate over a cursor using async for...of loop to access key and value. ```APIDOC ## Basic Async Iteration Cursors support async iteration through Symbol.asyncIterator. ```typescript for await (const cursor of store.openCursor()) { console.log(cursor.key, cursor.value); } ``` ``` -------------------------------- ### transaction Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/idbpdatabase.md Starts a new transaction that can cover one or more object stores, allowing for read or read/write operations. ```APIDOC ## transaction ### Description Starts a new transaction covering one or more object stores. ### Method Signature ```typescript transaction, Mode extends IDBTransactionMode = 'readonly'>(storeNames: Name, mode?: Mode, options?: IDBTransactionOptions): IDBPTransaction transaction>, Mode extends IDBTransactionMode = 'readonly'>(storeNames: Names, mode?: Mode, options?: IDBTransactionOptions): IDBPTransaction ``` ### Parameters #### Path Parameters - **storeNames** (StoreNames or string[]) - Required - Single store name or array of store names - **mode** ('readonly' | 'readwrite') - Optional - Transaction mode (default: 'readonly') - **options** ({ durability?: 'default' | 'strict' | 'relaxed' }) - Optional - Optional durability setting ### Returns An enhanced `IDBPTransaction` scoped to the specified stores. ### Example ```typescript const tx = db.transaction(['users', 'posts'], 'readwrite'); await tx.objectStore('users').put(user); await tx.objectStore('posts').put(post); await tx.done; ``` ``` -------------------------------- ### getAllKeysFromIndex Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/idbpdatabase.md Fetches all primary keys from an index that match a query. This is efficient for getting identifiers without the full data. ```APIDOC ## getAllKeysFromIndex Gets all primary keys from an index matching a query. ### Method Signature ```typescript getAllKeysFromIndex, IndexName extends IndexNames>( storeName: Name, indexName: IndexName, query?: IndexKey | IDBKeyRange | null, count?: number, ): Promise[]> ``` ``` -------------------------------- ### Create Database Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/README.md Opens or creates a new IndexedDB database. It takes the database name, version, and an upgrade callback function. ```APIDOC ## openDB() ### Description Opens or creates a new IndexedDB database. This function is used to initialize the database connection and handle schema upgrades. ### Method `openDB(name, version, callbacks)` ### Parameters - **name** (string) - The name of the database. - **version** (number) - The version of the database. - **callbacks** (object) - An object containing callbacks, primarily `upgrade`. - **upgrade** (function) - A callback function that is executed when the database is created or its version is changed. ### Request Example ```javascript await openDB('myDatabase', 1, { upgrade(db) { db.createObjectStore('users', { keyPath: 'id' }); }, }); ``` ``` -------------------------------- ### getFromIndex Source: https://github.com/jakearchibald/idb/blob/main/_autodocs/api-reference/idbpdatabase.md Gets a single value from an index by its key. This is useful for retrieving a specific record when you know its indexed value. ```APIDOC ## getFromIndex Gets a value from an index by key. ### Method Signature ```typescript getFromIndex, IndexName extends IndexNames>( storeName: Name, indexName: IndexName, query: IndexKey | IDBKeyRange, ): Promise | undefined> ``` ### Example ```typescript const user = await db.getFromIndex('users', 'by-email', 'alice@example.com'); ``` ```