dxie使用

51 阅读1分钟

import Dexie from 'dexie';

class DBWrapper { /**

  • 创建数据库实例
  • @param {string} dbName 数据库名称
  • @param {number} version 数据库版本
  • @param {Array} tables 表配置数组 */ constructor(dbName, version, tables) { this.db = new Dexie(dbName); this.initializeDB(version, tables); }

/**

  • 初始化数据库结构
  • @param {number} version
  • @param {Array} tables */ initializeDB(version, tables) { const schema = tables.reduce((acc, table) => { acc[table.name] = this.generateTableSchema(table); return acc; }, {});
this.db.version(version).stores(schema);

}

/**

  • 生成Dexie表结构
  • @param {Object} tableConfig
  • @returns {string} */ generateTableSchema({ primaryKey, indexes }) { return [primaryKey].concat(indexes || []).join(', '); }

// 基础CRUD操作 async add(tableName, data) { return this.db[tableName].add(data); }

async bulkAdd(tableName, items) { return this.db[tableName].bulkAdd(items); }

async get(tableName, id) { return this.db[tableName].get(id); }

async getAll(tableName) { return this.db[tableName].toArray(); }

async update(tableName, id, changes) { return this.db[tableName].update(id, changes); }

async put(tableName, data) { return this.db[tableName].put(data); }

async delete(tableName, id) { return this.db[tableName].delete(id); }

// 高级操作 async clearTable(tableName) { return this.db[tableName].clear(); }

async transaction(mode, tables, transactionCallback) { return this.db.transaction(mode, tables, transactionCallback); }

// 查询构建器 query(tableName) { return this.db[tableName].toCollection(); }

// 原生表访问 getTable(tableName) { return this.db[tableName]; } }

// 使用示例 const myDB = new DBWrapper('MyDatabase', 2, [ { name: 'users', primaryKey: 'id', indexes: ['name', 'age'] }, { name: 'products', primaryKey: 'sku', indexes: ['category', 'price'] } ]);

// 基础使用示例 async function demo() { // 添加用户 await myDB.add('users', { id: 1, name: 'Alice', age: 30, email: 'alice@example.com' });

// 批量添加产品 await myDB.bulkAdd('products', [ { sku: 'P100', name: 'Laptop', price: 999, category: 'Electronics' }, { sku: 'P200', name: 'Mouse', price: 25, category: 'Accessories' } ]);

// 事务操作 await myDB.transaction('rw', ['users', 'products'], async () => { await myDB.update('users', 1, { age: 31 }); await myDB.put('products', { sku: 'P100', name: 'Pro Laptop', price: 1299, category: 'Premium' }); });

// 复杂查询 const electronics = await myDB.query('products') .where('category') .equals('Electronics') .toArray(); }

// 错误处理示例 async function safeOperation() { try { await myDB.add('users', { id: 1 }); // 重复ID会抛出错误 } catch (error) { console.error('Operation failed:', error); } }