dexie 前端数据库封装

复制代码
import Dexie from "dexie";

/**
 *
 * @param dbName 数据库名称
 * @param storeName 对象存储区域
 * @param keyPath 主键
 * @param indexConfig 索引配置
 * @returns {Dexie}
 */
export function createDB(dbName, storeName, keyPath, indexConfig) {
  const db = new Dexie(dbName)
  // 定义对象存储区域
  db.version(1).stores({
    [storeName]: keyPath
  })
  // 添加索引或其他配置
  if (indexConfig) {
    Object.keys(indexConfig).forEach(indexName => {
      const indexProperties = indexConfig[indexName];
      db[storeName].createIndex(indexName, indexProperties.keyPath, {unique: indexProperties.unique});
    })
  }
  return db
}

/**
 * 添加数据
 * @param db 数据库实例
 * @param storeName 对象存储区域
 * @param data 添加的数据
 */
export function addData(db, storeName, data) {
  db.open().then(() => {
    db.transaction('rw', db[storeName], async () => {
      await db[storeName].add(data);
    }).then(() => {
      console.log('Data added successfully.');
    }).catch(error => {
      console.error('Error adding data:', error)
    })
  }).catch(error => {
    console.error('Error opening database:', error)
  })
}

/**
 * 获取数据
 * @param db 数据库
 * @param storeName 对象存储区对象
 * @param keyValue 主键值
 */
export function getData(db, storeName, keyValue) {
  return new Promise((resolve, reject) => {
    db.open().then(() => {
      db.transaction('rw', db[storeName], async () => {
        const matched = await db[storeName].get(keyValue)
        resolve(matched)
      }).catch(error => {
        console.error('Error getting data:', error)
      })
    }).catch(error => {
      console.error('Error opening database:', error)
    })
  })
}

/**
 * 更新数据
 * @param db 数据库
 * @param storeName 对象存储区对象
 * @param keyValue 主键值
 * @param data 更新值
 */
export function updateData(db, storeName, keyValue, data) {
  db.open().then(() => {
    db[storeName].get(keyValue).then(matched => {
      if (matched) {
        db.transaction('rw', db[storeName], async () => {
          await db[storeName].update(keyValue, data)
        }).then(() => {
          console.log('Data updated successfully.');
        }).catch(error => {
          console.error('Error updating data:', error)
        })
      } else {
        addData(db, storeName, data)
      }
    }).catch(error => {
      console.error('Error getting data:', error)
    })
  }).catch(error => {
    console.error('Error opening database:', error)
  })
}

/**
 * 删除数据
 * @param db
 * @param storeName
 * @param keyValue
 */
export function deleteData(db, storeName, keyValue) {
  db.open().then(() => {
    db.transaction('rw', db[storeName], async () => {
      await db[storeName].delete(keyValue)
    }).then(() => {
      console.log('Data deleted successfully.');
    }).catch(error => {
      console.error('Error deleting data:', error)
    })
  }).catch(error => {
    console.error('Error opening database:', error)
  })
}

/**
 * 删除数据库
 * @param dbName
 */
export function deleteDb(dbName) {
  Dexie.exists(dbName).then(exists => {
    // console.log(exists)
    if (exists) {
      Dexie.delete(dbName).then(() => {
        console.log('Database deleted successfully.')
      }).catch(error => {
        console.error('Error deleting database', error)
      })
    } else {
      console.log(`Database 【${dbName}】 not exist.`)
    }
  }).catch(error => {
    console.error('Error checking database', error)
  })
}
相关推荐
ClouGence4 小时前
Oracle 数据同步为什么会出现数据不一致?长事务是常被忽略的原因
数据库·后端·oracle
飞将7 小时前
从零实现数据库(2)——HashIndex + IndexManager
数据库
Nturmoils1 天前
订单列表慢查询,先看 WHERE、ORDER BY 和 LIMIT
数据库
渣波1 天前
拒绝 SQL 焦虑!手把手带你用 NestJS + Prisma + DTO 写出“防弹”级后端代码
javascript·数据库·后端
倔强的石头_2 天前
KingbaseES 新版MySQL 兼容版体验:旧版迁移 + 功能实测
数据库
倔强的石头_5 天前
《Kingbase护城河》——数据库存储空间全景探测与精细化瘦身实战
数据库
冬奇Lab6 天前
每日一个开源项目(第134篇):Zvec - 阿里开源的嵌入式向量数据库,向量搜索界的 SQLite
数据库·人工智能·llm
ClouGence6 天前
Oracle CDC 架构优化:从主库直连到 DataGuard 备库同步
数据库·后端·oracle
无响应de神6 天前
三、用户与权限管理
数据库·mysql
麦聪聊数据7 天前
数据服务化时代:企业数据能力输出的核心路径
数据库