• IndexedDB 简单封装


    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();
      }
    };


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

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

  • 相关阅读:
    质量属性分析之《淘宝网》
    每日总结(3.7)
    每日总结(3.6)
    读架构漫谈有感
    每日总结(3.5)
    每日总结(3.4)
    laravel 输出时间少了8小时
    laravel 循环添加新的数据之后如何排序
    php trait使用详解
    laravel Guzzle使用
  • 原文地址:https://www.cnblogs.com/huangenai/p/9766453.html
Copyright © 2020-2023  润新知