简单实用浏览器indexDB

之前在做项目的过程中,偶有用到indexDB来做缓存,后面就基本上使用的localstrage,恩,其实indexDB也是挺好使用的,可以去看看张鑫旭的这几篇文章

https://www.zhangxinxu.com/wordpress/2018/06/js-localforage-localstorage-indexdb/

https://www.zhangxinxu.com/wordpress/2017/07/html5-indexeddb-js-example/

写得也都很全面,下面附上自写的部分代码

class UtilDB {
  constructor(store, ...options) {
    this.store = store;
    this.options = options;
  }
  /**
   * 打开创建数据库 返回promise
   * @param {DB名字} name
   * @param {版本号} version
   */
  openDB(name, version = 1, keypath) {
    let indexDB =
      window.indexedDB ||
      window.mozIndexedDB ||
      window.webkitIndexedDB ||
      window.msIndexedDB;
    let request = indexDB.open(name, version);
    const pormise = new Promise((resolve, reject) => {
      request.onerror = e => {
        console.log("连接indexDB数据库失败");
        console.error(e.currentTarget.error.message);
        reject(e.currentTarget.error.message);
      };
      request.onsuccess = e => {
        console.log("连接indexDB数据库成功");
        this.db = e.target.result;
        resolve(this.db);
      };
      request.onupgradeneeded = e => {
        let db = e.target.result;
        if (!db.objectStoreNames.contains(this.store)) {
          let store = db.createObjectStore(this.store, {
            keypath: keypath,
            autoIncrement: true
          });
          this.options.forEach(item => {
            if (Object.prototype.toString.call({}) == "[object Object]") {
              store.createIndex(item.name + "", item.name + "", item.options);
            } else {
              store.createIndex(item + "", item + "", {
                unique: false
              });
            }
          });
        }
      };
    });
    return pormise;
  }
  /**
   * 创建事务
   * @param {事务} way
   */
  __commonCrud(way) {
    let normal = this.store + "";
    let tx = this.db.transaction(normal, way);
    let store = tx.objectStore(normal);
    return store;
  }
  /**
   * 添加数据
   * @param {一般为string类型} val 要添加的值
   * @param {Function} callback 回调函数
   */
  addData(val, callback = () => {}) {
    let req = this.__commonCrud("readwrite");
    req = req.add(val);
    req.onsuccess = e => {
      console.info("addData", "添加数据成功");
      return callback(e.target);
    };
    req.onerror = e => {
      console.error("add Error", "添加数据失败");
      return callback(e.target);
    };
  }
  /**
   * 修改操作
   * @param {*} val 要修改的值
   * @param {*} callback 修改的回调
   */
  putData(val, callback = () => {}) {
    let req = this.__commonCrud("readwrite");

    req = req.put(val, val[Object.keys(val)[0]]);

    req.onsuccess = e => {
      console.log("修改数据成功");
      return callback(e.target);
    };

    req.onerror = e => {
      console.log("修改数据失败");

      return callback(e.target);
    };
  }
  /**
   * 获取数据
   * @param {key} val key值,一般为string
   * @param {*} callback 获取数据的回调函数
   */
  getData(val, callback = () => {}) {
    let req = this.__commonCrud("readonly");
    req = req.get(val);
    req.onsuccess = e => {
      if ("success" === e.type) {
        console.log("获取数据成功");
        return callback(e.target.result);
      }
    };
    req.onerror = e => {
      console.log("获取数据失败");
      return callback(e);
    };
  }
  /**
   * 获取所有数据
   * @param {*} callback
   */
  getAllData(callback = () => {}) {
    let req = this.__commonCrud("readwrite");
    let result = [];
    req = req.openCursor();
    req.onerror = e => {
      console.error("query error", e.error);
      return callback(e.target);
    };
    req.onsuccess = e => {
      let cursor = e.target.result;
      if (cursor) {
        result.push(cursor.value);
        cursor.continue();
      } else {
        return callback(result);
      }
    };
  }
  /**
   * 获取单条数据
   * @param {*} name
   * @param {*} callback
   */
  getSignleData(name, callback = () => {}) {
    console.log("获取单条信息");
    let req = this.__commonCrud("readonly");
    let index = req.index(this.options[0].name);
    req = index.get(name);
    req.onsuccess = e => {
      console.log("获取单条数据成功");
      return callback(e.target.result);
    };
    req.onerror = e => {
      console.log("获取单条数据成功");
      return callback(e.target.result);
    };
  }
  /**
   * 删除数据
   * @param {*} val
   * @param {*} callback
   */
  deleteData(val, callback = () => {}) {
    let req = this.__commonCrud("readwrite");
    req = req.delete(val);
    req.onerror = e => {
      console.log("系统错误");
      return callback(e.target);
    };
    req.onsuccess = e => {
      console.log("执行成功");
      return callback(e.target);
    };
  }
  /**
   * 删除单条数据
   * @param {*} userName
   * @param {*} callback
   */
  deleteSignleData(userName, callback = () => {}) {
    let req = this.__commonCrud("readwrite");
    req = req.openCursor();
    req.onerror = e => {
      console.error("query:error", "查询使用游标时出错");
      return callback(e.error.name);
    };
    req.onsuccess = e => {
      let cursor = e.target.result;
      if (cursor) {
        if (cursor.userName == userName) {
          cursor.delete();
        }
        cursor.continue();
      } else {
        return callback(cursor);
      }
    };
  }
  onError(callback) {
    return callback(event);
  }
  onSuccess(callback) {
    return callback(event);
  }
  onComplete(callback) {
    return callback(event);
  }
  /**
   * 关闭数据库
   * @param {数据库} db
   */
  closeDB(db) {
    db.close();
  }
  /**
   * 删除数据库
   * @param {数据库名称} name
   */
  deleteDB(name) {
    indexedDB.deleteDatabase(name);
  }
}
export default UtilDB;

其他更多文章,请移步www.yuduo.top

你可能感兴趣的:(笔记,indexDB,js)