indexedDB使用封装

indexedDB的简单使用封装

const noop = (...args: any) => undefined;

type mode = "readonly" | "readwrite";

interface Obj {
  [propName: string]: any;
}

const menuList: any = {
  /** 获取表
   * @param {string} store_name
   * @param {string} mode either "readonly" or "readwrite"
   */
  getObjectStore(store_name: string, mode: mode): object {
    const tx = this.transaction(store_name, mode);
    return tx.objectStore(store_name);
  },

  /**
   * 添加记录
   * @param {*} store_name
   * @param {*} jsonObj
   * @param {*} success
   * @param {*} fail
   */
  addStore(store_name: string, jsonObj: Obj, success = noop, fail = noop) {
    // console.log("addStore arguments:", arguments);

    const store = this.getObjectStore(store_name, "readwrite");
    let req;
    try {
      req = store.add(jsonObj);
    } catch (e) {
      if (e.name == "DataCloneError") throw e;
    }
    req.onsuccess = function () {
      //   console.log("addStore successful");
      success();
    };
    req.onerror = function () {
      console.error("addStore error", this.error);
      fail(this.error);
    };
  },

  /**
   * 更新记录
   */
  updateStore(store_name: string, jsonObj: Obj, success = noop, fail = noop) {
    if (!jsonObj.id) {
      fail("未找到id索引");
      return;
    }
    const store = this.getObjectStore(store_name, "readwrite");
    let req;
    try {
      req = store.put(jsonObj);
    } catch (e) {
      if (e.name == "DataCloneError") throw e;
    }
    req.onsuccess = function () {
      console.log("addStore successful");
      success();
    };
    req.onerror = function () {
      console.error("addStore error", this.error);
      fail(this.error);
    };
  },

  /**
   *  清除表
   * @param {*} store_name  表名
   */
  clearObjectStore(store_name: string, success = noop, fail = noop) {
    const store = this.getObjectStore(store_name, "readwrite");
    const req = store.clear();
    req.onsuccess = function () {
      success();
    };
    req.onerror = function (evt: Obj) {
      fail(evt.target.errorCode);
    };
  },
  getValueByKey(
    store_name: string,
    key: string,
    value: string,
    success = noop,
    fail = noop
  ) {
    const store = this.getObjectStore(store_name, "readwrite");
    let req = store.index(key);
    req = req.get(value);
    req.onsuccess = function (evt: Obj) {
      const record = evt.target.result;
      //   console.log("record:", record);
      success(record);
    };
    req.onerror = function (evt: Obj) {
      console.error("deleteStore:", evt.target.errorCode);
      fail(evt.target.errorCode);
    };
  },
  /**
   *  通过查找id删除目标项
   * @param {*} store
   * @param {*} key
   */
  deleteStoreById(
    store_name: string,
    key: string,
    success = noop,
    fail = noop
  ) {
    const store = this.getObjectStore(store_name, "readwrite");
    let req = store.get(key);
    req.onsuccess = function (evt: Obj) {
      const record = evt.target.result;
      console.log("record:", record);
      if (typeof record == "undefined") {
        fail("No matching record found");
        return;
      }
      // Warning: The exact same key used for creation needs to be passed for
      // the deletion. If the key was a Number for creation, then it needs to
      // be a Number for deletion.
      req = store.delete(key);
      req.onsuccess = function () {
        console.log("delete successful");
        success();
      };
      req.onerror = function (evt: Obj) {
        console.error("deleteStore:", evt.target.errorCode);
        fail(evt.target.errorCode);
      };
    };
    req.onerror = function (evt: Obj) {
      console.error("deleteStore:", evt.target.errorCode);
      fail(evt.target.errorCode);
    };
  },

  /**
   * 删除数据通过 唯一key
   * @param {*} store_name
   * @param {*} name
   * @param {*} success
   * @param {*} fail
   */
  deleteStoreFromName(
    store_name: string,
    key: string,
    value: string,
    success = noop,
    fail = noop
  ) {
    const store = this.getObjectStore(store_name, "readwrite");
    const req = store.index(key);
    let that = this;
    req.get(value).onsuccess = function (evt: Obj) {
      if (typeof evt.target.result == "undefined") {
        fail("No matching record found");
        return;
      }
      that.deleteStoreById(evt.target.result.id, store_name, success, fail);
    };
    req.onerror = function (evt: Obj) {
      fail(evt.target.errorCode);
    };
  },

  getListByStore(store_name: string, success = noop, fail = noop) {
    const objectStore = this.getObjectStore(store_name, "readwrite");
    const open = objectStore.openCursor();
    const arr: any[] = [];
    open.onsuccess = function (event: Obj) {
      const cursor = event.target.result;
      if (cursor) {
        // console.log(cursor);
        arr.push(cursor.value);
        cursor.continue();
      } else {
        // console.log("没有更多数据了!");
        success(arr);
        // console.log(arr)
      }
    };
    open.onerror = function (err: Obj) {
      fail(err);
    };
  },
};

/**
 *
 * @param {*} res
 * @param {*} DB_STORE_NAME  表名称
 * @param {*} STORE_ARR 表头字段列表 第一个默认  unique: true
 */
function createStore(
  res: Obj,
  DB_STORE_NAME: string = "",
  STORE_ARR: any[] = []
) {
  const store = res.createObjectStore(DB_STORE_NAME, {
    keyPath: "id",
    autoIncrement: true,
  });

  STORE_ARR.forEach((key, index) => {
    if (index === 0) {
      store.createIndex(key, key, { unique: true });
    } else {
      store.createIndex(key, key, { unique: false });
    }
  });
  return store;
}

/**
 * 打开/创建数据库
 * @param {*} DB_NAME  数据库名称
 * @param {*} DB_VERSION  数据库版本号
 * @param {*} DB_STORE_NAME 表名称
 * @param {*} STORE_ARR 表头字段 默认第一个 unique: true
 */
export async function createIndexedDB(
  DB_NAME: string,
  DB_VERSION: number,
  DB_STORE_NAME: string,
  STORE_ARR: any[]
) {
  const indexedDB =
    window.indexedDB ||
    window.webkitIndexedDB ||
    window.mozIndexedDB ||
    window.msIndexedDB;
  if (!indexedDB) {
    throw "你的浏览器不支持indexedDB";
  }
  return new Promise((resolve, reject) => {
    const IDB = window.indexedDB.open(DB_NAME, DB_VERSION);
    IDB.onsuccess = function (evt) {
      console.log("openDb DONE");
      const result = Object.assign(this.result, menuList);
      resolve(result);
    };
    IDB.onerror = function (evt: Obj) {
      console.error("openDb:", evt.target.errorCode);
      reject(evt.target.errorCode);
    };

    IDB.onupgradeneeded = function (evt: Obj) {
      console.log("openDb.onupgradeneeded");
      const res = evt.currentTarget.result;
      createStore(res, DB_STORE_NAME, STORE_ARR);
    };
  });
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值