promise-idb
v1.0.3
Published
A lightweight TypeScript library that simplifies IndexedDB with async/await syntax and Promise-based API for modern browser storage
Maintainers
Keywords
Readme
promise-idb (Async IndexedDB)
A lightweight TypeScript library that provides a Promise-based wrapper around IndexedDB, making it easier to work with browser-based databases using async/await syntax.
Features
- Promise-based API: All operations return Promises, allowing you to use async/await
- Type-safe: Built with TypeScript for full type safety
- Simple API: Intuitive methods for common database operations
- Index Support: Easy creation and management of database indexes
- Error Handling: Custom error class for better error management
Installation
npm install promise-idbQuick Start
import AsyncDB from 'promise-idb';
// Initialize the database
const db = AsyncDB.init('myDatabase', 1);
// Create a store
const userStore = db.createStore<User>('users', { keyPath: 'id' });
// Add indexes
userStore.addIndex('email', 'email', { unique: true });
userStore.addIndex('age', 'age');
// Build the database
const instance = await db.build();API Reference
AsyncDB
The main class for creating and managing your IndexedDB database.
AsyncDB.init(dbName: string, version?: number)
Creates a new AsyncDB instance.
const db = AsyncDB.init('myApp', 1);createStore<T>(name: string, options?: IDBObjectStoreParameters)
Creates a new object store in the database.
interface Product {
id: number;
name: string;
price: number;
}
const productStore = db.createStore<Product>('products', {
keyPath: 'id',
autoIncrement: true
});build(): Promise<AsyncDBInstance>
Builds and opens the database connection.
const instance = await db.build();DBStore
Represents an object store in the database with methods for data operations.
add(data: T): Promise<boolean>
Adds a new record to the store.
await userStore.add({
id: 1,
name: 'John Doe',
email: '[email protected]',
age: 30
});get(query: IDBValidKey | IDBKeyRange): Promise<T>
Retrieves a single record by key.
const user = await userStore.get(1);
console.log(user.name); // 'John Doe'getAll(query?: IDBValidKey | IDBKeyRange, count?: number): Promise<T[]>
Retrieves all records matching the query.
// Get all users
const allUsers = await userStore.getAll();
// Get first 10 users
const firstTen = await userStore.getAll(null, 10);update<K = T>(value: K, key?: IDBValidKey): Promise<T>
Updates an existing record or creates a new one.
await userStore.update({
id: 1,
name: 'Jane Doe',
email: '[email protected]',
age: 28
});delete(query: IDBValidKey | IDBKeyRange): Promise<void>
Deletes a record by key.
await userStore.delete(1);addIndex(name: string, keyPath: string | string[], options?: IDBIndexParameters)
Adds an index to the store (must be called before build()).
userStore.addIndex('email', 'email', { unique: true });
userStore.addIndex('fullName', ['firstName', 'lastName']);Complete Example
import AsyncDB from 'promise-idb';
interface Todo {
id: number;
title: string;
completed: boolean;
createdAt: Date;
}
async function setupDatabase() {
// Initialize database
const db = AsyncDB.init('todoApp', 1);
// Create todos store
const todoStore = db.createStore<Todo>('todos', {
keyPath: 'id',
autoIncrement: true
});
// Add indexes
todoStore.addIndex('completed', 'completed');
todoStore.addIndex('createdAt', 'createdAt');
// Build database
await db.build();
return todoStore;
}
async function main() {
const todoStore = await setupDatabase();
// Add a new todo
await todoStore.add({
id: 1,
title: 'Learn AsyncDB',
completed: false,
createdAt: new Date()
});
// Get all todos
const todos = await todoStore.getAll();
console.log('All todos:', todos);
// Update a todo
await todoStore.update({
id: 1,
title: 'Learn AsyncDB',
completed: true,
createdAt: new Date()
});
// Delete a todo
await todoStore.delete(1);
}
main().catch(console.error);Error Handling
AsyncDB includes a custom error class for better error management:
import { DBError } from 'promise-idb';
try {
await userStore.add(duplicateUser);
} catch (error) {
if (error instanceof DBError) {
console.error('Database error:', error.message);
}
}Browser Compatibility
AsyncDB works in all browsers that support IndexedDB:
- Chrome 24+
- Firefox 16+
- Safari 10+
- Edge 12+
- Opera 15+
License
MIT
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
