Skip to content

api_reference

haiix edited this page Jan 12, 2025 · 1 revision

API Reference

Database Operations

open(name: string): Idb

Opens a connection to a database. Creates the database if it doesn't exist.

const db = idb.open('myDatabase');

version(): Promise<number>

Get the current database version.

const version = await db.version();

objectStoreNames(): Promise<DOMStringList>

Get a list of all object store names in the database.

const storeNames = await db.objectStoreNames();

deleteDatabase(): Promise<IDBDatabase>

Deletes the entire database.

await db.deleteDatabase();

Object Store Operations

Creating an Object Store

// Basic object store
const simpleStore = db.objectStore('simpleStore');

// With key path and auto-increment
const store = db.objectStore('users', {
  keyPath: 'id',
  autoIncrement: true
});

// With indexes
const storeWithIndex = db.objectStore('posts', 
  { keyPath: 'id' },
  [
    { 
      name: 'byAuthor', 
      keyPath: 'author',
      options: { unique: false }
    }
  ]
);

Data Operations

Adding Data
// With explicit key
await store.add('value', 'key');

// With keyPath
await store.add({ id: 1, name: 'John' });
Retrieving Data
// Get single item
const item = await store.get('key');

// Get all items
const allItems = await store.getAll();

// Get items with range
const range = IDBKeyRange.bound('a', 'c');
const items = await store.getAll(range);
Updating Data
await store.put({ id: 1, name: 'Updated Name' });
Deleting Data
// Delete single item
await store.delete('key');

// Clear all data
await store.clear();

Working with Cursors

The library provides async iterators for cursor operations:

// Iterate through all values
const store = db.objectStore('users');
for await (const cursor of store.openCursor()) {
  console.log(cursor.value);
  cursor.continue();
}

// Iterate through keys only
for await (const cursor of store.openKeyCursor()) {
  console.log(cursor.key);
  cursor.continue();
}

Index Operations

Creating an Index

const store = db.objectStore('users', null, [
  {
    name: 'byEmail',
    keyPath: 'email',
    options: { unique: true }
  }
]);

Using an Index

const index = store.index('byEmail');
const user = await index.get('john@example.com');

Deleting an Index

await store.deleteIndex('byEmail');