最新公告
  • 欢迎您光临起源地模板网,本站秉承服务宗旨 履行“站长”责任,销售只是起点 服务永无止境!立即加入钻石VIP
  • indexedDb的Promise封装

    正文概述 掘金(Codist65638)   2021-01-03   973

    前言

    indexedDb是一种非关系型数据库,跟以往用到的数据库结构还是有蛮大差距的。结合实际的应用场景,我对indexedDb做了Promise二次封装。不多说,直接上代码。

    代码

    let idxDb = {
      dbName: "indexedDb",
      dbVersion: 20191216,
      db: {},
      initDb(cbk_rslt) {
        let dbVersion = 20191216;
        let request = window.indexedDB.open("example", dbVersion);
    
        request.onerror = (event) => {
          console.log('数据库打开报错');
          cbk_rslt({
            event: 'onerror'
          });
        };
        request.onsuccess = (event) => {
          this.db = event.target.result;
          console.log('数据库打开成功');
          cbk_rslt({
            event: 'onsuccess'
          });
        };
        request.onupgradeneeded = (event) => {
          console.log('数据库打开成功2');
          this.db = event.target.result;
          let objectStore;
          if (!this.db.objectStoreNames.contains('student')) {
            objectStore = this.db.createObjectStore('student', {
              keyPath: 'kjh'
            });
            objectStore.createIndex('name', 'name', {
              unique: false
            });
            objectStore.createIndex('xm', 'xm', {
              unique: true
            });
          }
          cbk_rslt({
            event: 'onupgradeneeded'
          });
        }
      },
      openDB() {
        return new Promise((resolve, reject) => {
          let request = window.indexedDB.open(this.dbName, this.dbVersion);
    
          request.onerror = (event) => {
            reject("IndexedDB数据库打开错误," + event);
          };
          request.onsuccess = (event) => {
            resolve(event.target.result);
          };
        });
      },
      closeDb() {
        this.db.close();
      },
      deleteDb(dbname) {
        this.db.deleteDatabase(dbname);
      },
      addData(table, value) {
        try {
          let p = this.openDB();
          p.then(data => {
            this.db = data;
          }).catch(error => {
            return console.log(error);
          });
    
          let request = this.db.transaction([table], 'readwrite')
            .objectStore(table)
            .add(value);
    
          return new Promise(resolve => {
            request.onsuccess = () => {
              resolve({
                flag: true
              });
            };
            request.onerror = () => {
              resolve({
                flag: false
              });
            };
          });
        } catch (error) {
          return Promise.resolve({
            flag: false
          });
        }
      },
      getData(table, key) {
        try {
          let transaction = this.db.transaction([table], 'readonly');
          let store = transaction.objectStore(table);
          let request = store.get(key);
    
          // let request = this.db.transaction([table], 'read')
          //   .objectStore(table)
          //   .get(key);
    
          return new Promise(resolve => {
            request.onsuccess = () => {
              resolve({
                flag: true,
                result: request.result
              });
            };
            request.onerror = () => {
              resolve({
                flag: false
              });
            };
          });
    
    
        } catch (error) {
          return Promise.resolve({
            flag: false
          });
        }
    
      },
      putData(table, value) {
        try {
          let p = this.openDB();
          p.then(data => {
            this.db = data;
          }).catch(error => {
            return console.log(error);
          });
    
          let request = this.db.transaction([table], 'readwrite')
            .objectStore(table)
            .put(value);
    
          return new Promise(resolve => {
            request.onsuccess = () => {
              resolve({
                flag: true
              });
            };
            request.onerror = () => {
              resolve({
                flag: false
              });
            };
          });
        } catch (error) {
          return Promise.resolve({
            result: false
          });
        }
    
      },
      selectData(table, index, value) {
        try {
          let p = this.openDB();
          p.then(data => {
            this.db = data;
          }).catch(error => {
            return console.log(error);
          });
    
          let selectQuene = new Array(0);
    
          let request = this.db.transaction([table], 'readwrite')
            .objectStore(table).index(index)
            .openCursor(IDBKeyRange.only(value));
    
          return new Promise(resolve => {
            request.onsuccess = (e) => {
              let cursor = e.target.result;
              if (cursor) {
                selectQuene.push(request.result.value);
                // resolve({
                //   flag: true,
                //   result: request.result
                // });
                // console.log(cursor);
                cursor.continue();
              } else {
    
                resolve({
                  flag: true,
                  result: selectQuene
                });
              }
            };
            request.onerror = () => {
              resolve({
                flag: false
              });
            };
          });
        } catch (error) {
          return Promise.resolve({
            flag: false
          });
        }
      },
      selectDataBound(table, index, valueX, valueY) {
        try {
          let p = this.openDB();
          p.then(data => {
            this.db = data;
          }).catch(error => {
            return console.log(error);
          });
    
          let selectQuene = new Array(0);
    
          let request = this.db.transaction([table], 'readwrite')
            .objectStore(table).index(index)
            .openCursor(IDBKeyRange.bound(valueX, valueY));
    
          return new Promise(resolve => {
            request.onsuccess = (e) => {
              let cursor = e.target.result;
              if (cursor) {
                selectQuene.push(request.result.value);
                // resolve({
                //   flag: true,
                //   result: request.result
                // });
                // console.log(cursor);
                cursor.continue();
              } else {
    
                resolve({
                  flag: true,
                  result: selectQuene
                });
              }
            };
            request.onerror = () => {
              resolve({
                flag: false
              });
            };
          });
        } catch (error) {
          return Promise.resolve({
            flag: false
          });
        }
      },
      countData(table, index, value) {
        try {
          let p = this.openDB();
          p.then(data => {
            this.db = data;
          }).catch(error => {
            return console.log(error);
          });
          console.log(index);
          let request = this.db.transaction([table], 'readonly')
            .objectStore(table).count();
    
          return new Promise(resolve => {
            request.onsuccess = () => {
              resolve({
                flag: true,
                result: request.result
              });
            };
            request.onerror = () => {
              resolve({
                flag: false
              });
            };
          });
        } catch (error) {
          return Promise.resolve({
            result: false
          });
        }
      },
      countData2(table, index, value) {
        try {
          let p = this.openDB();
          p.then(data => {
            this.db = data;
          }).catch(error => {
            return console.log(error);
          });
          console.log(1)
          let nCount = 0;
    
          let request = this.db.transaction([table], 'readonly')
            .objectStore(table).index(index)
            .openCursor(IDBKeyRange.only(value));
    
          return new Promise(resolve => {
            request.onsuccess = (e) => {
              let cursor = e.target.result;
              if (cursor) {
                nCount++;
                cursor.continue();
              } else {
    
                resolve({
                  flag: true,
                  result: nCount
                });
              }
            };
            request.onerror = () => {
              resolve({
                flag: false
              });
            };
          });
        } catch (error) {
          return Promise.resolve({
            flag: false
          });
        }
      },
      cleaerObjectstore(table) {
        try {
          let p = this.openDB();
          p.then(data => {
            this.db = data;
          }).catch(error => {
            return console.log(error);
          });
    
          let request = this.db.transaction([table], 'readwrite')
            .objectStore(table).clear();
    
          return new Promise(resolve => {
            request.onsuccess = () => {
              resolve({
                flag: true
              });
            };
            request.onerror = () => {
              resolve({
                flag: false
              });
            };
          });
        } catch (error) {
          return Promise.resolve({
            result: false
          });
        }
    
      }
    }
    
    export default idxDb;
    

    分析

    initDb()openDB() 分别用来创建数据库和打开数据库

    addData() 用来添加新的数据,等同于insert

    putData() 用来修改数据,等同于update

    selectData 用来选择指定数据,等同于select

    selectDataBound 用来选择指定数据并添加条件筛选,等同于select+where

    countData 用来统计数据

    总结

    对indexedDb的接口进行这样的封装后,能够基本完成常规数据库的增删改查的操作。当然如果有其他的应用也可以进一步的去实现。


    起源地下载网 » indexedDb的Promise封装

    常见问题FAQ

    免费下载或者VIP会员专享资源能否直接商用?
    本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
    提示下载完但解压或打开不了?
    最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,若小于网盘提示的容量则是这个原因。这是浏览器下载的bug,建议用百度网盘软件或迅雷下载。若排除这种情况,可在对应资源底部留言,或 联络我们.。
    找不到素材资源介绍文章里的示例图片?
    对于PPT,KEY,Mockups,APP,网页模版等类型的素材,文章内用于介绍的图片通常并不包含在对应可供下载素材包内。这些相关商业图片需另外购买,且本站不负责(也没有办法)找到出处。 同样地一些字体文件也是这种情况,但部分素材会在素材包内有一份字体下载链接清单。
    模板不会安装或需要功能定制以及二次开发?
    请QQ联系我们

    发表评论

    还没有评论,快来抢沙发吧!

    如需帝国cms功能定制以及二次开发请联系我们

    联系作者

    请选择支付方式

    ×
    迅虎支付宝
    迅虎微信
    支付宝当面付
    余额支付
    ×
    微信扫码支付 0 元