-
Notifications
You must be signed in to change notification settings - Fork 0
api_reference
haiix edited this page Jan 12, 2025
·
1 revision
Opens a connection to a database. Creates the database if it doesn't exist.
const db = idb.open('myDatabase');
Get the current database version.
const version = await db.version();
Get a list of all object store names in the database.
const storeNames = await db.objectStoreNames();
Deletes the entire database.
await db.deleteDatabase();
// 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 }
}
]
);
// With explicit key
await store.add('value', 'key');
// With keyPath
await store.add({ id: 1, name: 'John' });
// 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);
await store.put({ id: 1, name: 'Updated Name' });
// Delete single item
await store.delete('key');
// Clear all data
await store.clear();
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();
}
const store = db.objectStore('users', null, [
{
name: 'byEmail',
keyPath: 'email',
options: { unique: true }
}
]);
const index = store.index('byEmail');
const user = await index.get('john@example.com');
await store.deleteIndex('byEmail');