Erlo

IndexedDB 简单封装

时间:2018-10-11 09:58   阅读:7次   来源:博客园页面报错

IndexedDB 浏览器数据库,是一个非关系型数据库,数据形式使用的是json,IndexedDB适合存储大量数据,它的API是异步调用的,当然他的api 也相对复杂。

当然浏览器数据存储 还有LocalStorage,Cookies,web SQL等 为什么还再来一个indexedDB。

之前我在开发过程中使用的是web sql,可以直接写sql查询数据。

LocalStorage,用key-value键值模式存储数据,而且Localstorage就是专门为小数量数据设计的。

Cookies只能是字符串 而且空间有限。

如果你在实际应用中希望存储大量数据时,IndexedDB会明显的更适合,IndexedDB也能提供你更为复杂的查询数据的方式,还能建立索引,他的索引还是挺666的。

下面是自己看了阮一峰的 文章 http://www.ruanyifeng.com/blog/2018/07/indexeddb.html

简单的学习了下 IndexedDB 对这个浏览器数据库有个大概的了解,下面是个人对IndexedDB 简单的封装。

 

const dbName = "test";
const dbVersion = 1;

export default {
  // indexedDB兼容
  indexedDB:
    window.indexedDB ||
    window.webkitindexedDB ||
    window.msIndexedDB ||
    window.mozIndexedDB,
  //name:表名  key:主键 ,cursorIndex 索引
  store: {
    teacher: {
      name: "teacher",
      key: "id",
      cursorIndex: [{ name: "teachNum", unique: false }]
    },
    student: {
      name: "student",
      key: "id",
      cursorIndex: [{ name: "stuNum", unique: false }]
    }
  },
  async initDB() {
    let that = this;
    let request = this.indexedDB.open(dbName, dbVersion);
    request.onerror = function() {
      console.log("打开数据库失败");
    };

    request.onsuccess = function() {
      console.log("打开数据库成功");
    };
    request.onupgradeneeded = function(event) {
      let db = event.target.result;
      for (var t in that.store) {
        if (!db.objectStoreNames.contains(that.store[t].name)) {
          var objectStore = db.createObjectStore(that.store[t].name, {
            keyPath: that.store[t].key,
            autoIncrement: true
          });
          for (let i = 0; i < that.store[t].cursorIndex.length; i++) {
            const element = that.store[t].cursorIndex[i];
            objectStore.createIndex(element.name, element.name, {
              unique: element.unique
            });
          }
        }
      }
    };
  },
  // 打开数据库
  openDB: function() {
    return new Promise((resolve, reject) => {
      let request = this.indexedDB.open(dbName, dbVersion);

      request.onerror = function(event) {
        reject("IndexedDB数据库打开错误," + event);
      };
      request.onsuccess = function(event) {
        resolve(event.target.result);
      };
    });
  },
  // 删除表
  deleteDB: function(table) {
    let deleteQuest = this.indexedDB.deleteDatabase(table);
    deleteQuest.onerror = function() {
      return Promise.resolve(false);
    };
    deleteQuest.onsuccess = function() {
      return Promise.resolve(true);
    };
  },
  // 关闭数据库
  closeDB: async function(db) {
    try {
      let d;
      if (!db) {
        d = await this.openDB();
      }
      let closeQuest = d.closeDB();
      return new Promise(resolve => {
        closeQuest.onerror = function() {
          resolve(false);
        };
        closeQuest.onsuccess = function() {
          resolve(true);
        };
      });
    } catch (error) {
      return Promise.resolve(false);
    }
  },
  // 添加数据,add添加新值
  insert: async function(table, data) {
    try {
      let db = await this.openDB();
      let request = db
        .transaction(table.name, "readwrite")
        .objectStore(table.name)
        .add(data);

      return new Promise((resolve, reject) => {
        request.onerror = function() {
          reject("添加数据出错");
        };
        request.onsuccess = function() {
          resolve(true);
        };
      });
    } catch (error) {
      console.log(error);
      return Promise.resolve(false);
    }
  },
  // 更新
  update: async function(table, data) {
    try {
      let db = await this.openDB();
      let request = db
        .transaction(table.name, "readwrite")
        .objectStore(table.name)
        .put(data);
      return new Promise(resolve => {
        request.onerror = function() {
          resolve(false);
        };
        request.onsuccess = function() {
          resolve(true);
        };
      });
    } catch (error) {
      return Promise.resolve(false);
    }
  },
  // 删除数据
  delete: async function(table, keyValue) {
    try {
      let db = await this.openDB();
      let request = db
        .transaction(table.name, "readwrite")
        .objectStore(table.name)
        .delete(keyValue);
      return new Promise(resolve => {
        request.onerror = function() {
          resolve(false);
        };
        request.onsuccess = function() {
          resolve(true);
        };
      });
    } catch (error) {
      return Promise.resolve(false);
    }
  },
  // 清空数据
  clear: async function(table) {
    let db = await this.openDB();
    let store = db.transaction(table.name, "readwrite").objectStore(table.name);
    store.clear();
  },
  // 查询数据 表名 索引值 索引 key  没有value key为key 而不是索引
  get: async function(table, keyValue, indexCursor) {
    try {
      let db = await this.openDB();
      let store = db
        .transaction(table.name, "readonly")
        .objectStore(table.name);
      let request;
      request = !keyValue
        ? store.openCursor()
        : indexCursor
          ? store.index(indexCursor).get(keyValue)
          : store.get(keyValue);
      let data = [];
      return new Promise(resolve => {
        request.onerror = function() {
          resolve("查询数据失败");
        };
        request.onsuccess = function(event) {
          if (!keyValue && !indexCursor) {
            if (event.target.result) {
              data.push(event.target.result.value);
              event.target.result.continue();
            } else {
              resolve(data);
            }
          } else {
            resolve([event.target.result]);
          }
        };
      });
    } catch (error) {
      return Promise.reject(error);
    }
  },
  //   通过游标操作数据, callback中要有游标移动方式
  handleDataByCursor: async function(table, keyRange) {
    try {
      let kRange = keyRange || "";
      let db = await this.openDB();
      let store = db.transaction(table, "readwrite").objectStore(table),
        request;
      request = store.openCursor(kRange);
      return new Promise(resolve => {
        request.onerror = function() {
          resolve("通过游标获取数据报错");
        };
        request.onsuccess = function(event) {
          let cursor = event.target.result;
          resolve(cursor);
        };
      });
    } catch (error) {
      return Promise.reject(error);
    }
  },
  // 通过索引游标操作数据, callback中要有游标移动方式
  handleDataByIndex: async function(table, keyRange, sursorIndex) {
    try {
      let kRange = keyRange || "";
      let db = await this.openDB();
      let store = db.transaction(table, "readwrite").objectStore(table),
        request;
      request = store.index(sursorIndex).openCursor(kRange);
      return new Promise(resolve => {
        request.onerror = function() {
          resolve("通过索引游标获取数据报错");
        };
        request.onsuccess = function(event) {
          let cursor = event.target.result;
          if (cursor) {
            resolve(cursor);
          }
        };
      });
    } catch (error) {
      return Promise.reject(error);
    }
  },
  // 创建游标索引
  createCursorIndex: async function(table, cursorIndex, unique) {
    var db = await this.openDB();
    let store = db.transaction(table, "readwrite").objectStore(table);
    store.createIndex(cursorIndex, cursorIndex, {
      unique: unique
    });
    return Promise.resolve();
  }
};

 


此随笔乃本人学习工作记录,如有疑问欢迎在下面评论,转载请标明出处。

如果对您有帮助请动动鼠标右下方给我来个赞,您的支持是我最大的动力。

下一篇:CSS3实现的几个小loading效果

评论留言

还没有评论留言,赶紧来抢楼吧~~

Erlo大厅()

* 这里是“Erlo大厅”,在这发言所有人都可以看到。只保留当天信息

  • Erlo.vip2018-10-22 06:14:04Hello、欢迎使用Erlo大厅,这里是个吐槽的地方。
  • 首页 源码分享 新闻资讯 ERLO 搜索
    鼠标试试
    返回顶部