欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

IndexedDB 简单封装

程序员文章站 2022-07-10 22:15:55
IndexedDB 浏览器数据库,是一个非关系型数据库,数据形式使用的是json,IndexedDB适合存储大量数据,它的API是异步调用的,当然他的api 也相对复杂。 当然浏览器数据存储 还有LocalStorage,Cookies,web SQL等 为什么还再来一个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();
  }
};

 


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

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