记录封装的一个indexedDB便捷增、删、改、查轮子

如果觉得好用请留言交流你的使用体会,或者其他技术交流。点赞,关注

import { message } from 'antd';
class IndexDB {
  /**
   * 通过索引和游标删除指定的数据
   * @param {object} request  IDBDatabase 实例
   * @param {string} storeName 仓库名称
   * @param {string} version 版本   */
  constructor(storeName, objectStoreName, version) {
    this.storeName = storeName;
    this.objectStoreName = objectStoreName;
    this.version = version;
    this.request = window.indexedDB.open(storeName, version);
    this.request.onsuccess = this.onsuccess;
    this.request.onerror = this.onerror;
    this.request.onupgradeneeded = this.onupgradeneeded;
  }
  onsuccess = event => {
    console.log('onsuccess');
    this.db = event.target.result;
    console.log('连接成功', this.db);
  };
  onerror = event => {
    console.log('onerror');
    let msg = '';
    if (!window.indexedDB) {
      msg = '您的浏览器不支持稳定版本的IndexedDB。全局cookie设置功能将不可用。';
    } else {
      msg = '请使用谷歌较新版本浏览器重试或联系管理员';
    }
    message.error(`Database error ${event?.target?.errorCode}: 连接失败,${msg}`);
  };
  onupgradeneeded = event => {
    console.log('onupgradeneeded');
    const db = event.target.result;
    let objectStore;
    if (!db.objectStoreNames.contains(this.storeName)) {
      objectStore = db.createObjectStore(this.objectStoreName, {
        autoIncrement: true,
      });
      objectStore.createIndex('type', 'type', { unique: false });
      objectStore.createIndex('address', 'address', { unique: false });
      objectStore.createIndex('agentId', 'agentId', { unique: false });
      objectStore.createIndex('agentName', 'agentName', { unique: false });
      objectStore.createIndex('name', 'name', { unique: false });
      objectStore.createIndex('default', 'default', { unique: false });
    }
  };
  //   list
  list() {
    let list = [];
    let objectStoreName = this.objectStoreName;
    const transaction = this.db.transaction(objectStoreName, 'readwrite'); // 事务
    let store = transaction.objectStore(objectStoreName); // 仓库对象
    let request = store.openCursor(); // 指针对象
    return new Promise((resolve, reject) => {
      request.onsuccess = function (e) {
        let cursor = e.target.result;
        if (cursor) {
          // 必须要检查
          list.push({ ...cursor.value, id: cursor.primaryKey });
          cursor.continue(); // 遍历了存储对象中的所有内容
        } else {
          resolve(list);
        }
      };
      request.onerror = function (e) {
        reject(e);
      };
    });
  }
  /**增加 */
  add = (params, callback) => {
    const { type, address = '', name, default: value, agentId = '', agentName = '' } = params;
    try {
      const next = this.db
        .transaction(this.objectStoreName, 'readwrite')
        .objectStore(this.objectStoreName)
        .add({
          type,
          address,
          name,
          agentId,
          agentName,
          default: value,
        });
      next.onsuccess = () => {
        this.addOnSuccess(callback);
      };
      next.onerror = () => {
        this.addOnError(callback);
      };
    } catch (err) {
      console.log(err);
    }
  };
  addOnSuccess = callback => {
    message.success('数据添加成功');
    callback && callback();
  };
  addOnError = callback => {
    message.error('浏览器IndexedDB错误,数据添加失败,请使用谷歌较新版本浏览器重试或联系管理员');
    callback && callback();
  };
  /**查询 */
  read = async (key, val) => {
    return new Promise(resolve => {
      if (!this.db?.transaction) {
        return resolve([]);
      }
      const next = this.db.transaction(this.objectStoreName, 'readwrite');
      const objectStore = next.objectStore(this.objectStoreName);
      const request = objectStore.index(key).openCursor(IDBKeyRange.only(val));
      request.onerror = this.readOnError;
      let list = [];
      request.onsuccess = function (e) {
        let cursor = e.target.result;
        if (cursor) {
          // 必须要检查
          list.push({ ...cursor.value, id: cursor.primaryKey });
          cursor.continue(); // 遍历了存储对象中的所有内容
        } else {
          resolve(list);
        }
      };
      request.onerror = function (event) {
        console.log(event.target);
        resolve(list);
      };
    });
  };
  deleteDB(id) {
    let request = this.db
      .transaction(this.objectStoreName, 'readwrite')
      .objectStore(this.objectStoreName)
      .delete(id);

    return new Promise((resolve, reject) => {
      request.onsuccess = function (ev) {
        resolve(ev);
      };

      request.onerror = function (ev) {
        resolve(ev);
      };
    });
  }
  /**清除全部 */
  clearAllData = callback => {
    if (!this.db?.transaction) return;
    const request = this.db
      .transaction(this.objectStoreName, 'readwrite')
      .objectStore(this.objectStoreName)
      .clear();

    request.onerror = function (event) {
      callback && callback(false);
    };
    request.onsuccess = function (event) {
      callback && callback(true);
    };
  };
  /**修改 */
  put = (params, id, callback) => {
    try {
      const next = this.db
        .transaction(this.objectStoreName, 'readwrite')
        .objectStore(this.objectStoreName)
        .put({ ...params }, id);
      next.onsuccess = function (event) {
        callback && callback(true);
      };
      next.onerror = function (event) {
        callback && callback(false);
      };
    } catch (err) {
      console.log(err);
    }
  };
}

const IndexDBService = new IndexDB('service', 'service', 1);
const IndexDBCatalog = new IndexDB('catalog', 'catalog', 1);
export { IndexDBService, IndexDBCatalog };

最后

相信看了上面的方法你已经掌握了所有的db操作方法,欢迎你的四连,记得点赞,评论,收藏,关注,嗷呜

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值