欢迎访问我的博客,目前从事Machine Learning,欢迎交流

使用ES6 Class封装的IndexDB 操作类,并实现模糊搜索

 封装如下:

indexDBOperate.js
export class IndexDBOperate {

    db = null // 数据库实例

    databaseName = null // 数据库名称

    version = null // 数据库版本

    objStoName = null // 表或对象仓库名称

    constructor(databaseName, version, objStoName, indexObj, successFunc) {

        this.databaseName = databaseName
        this.version = version
        this.objStoName = objStoName

        // 若无此数据库则会创建
        const request = window.indexedDB.open(databaseName, version)
        request.onerror = e => {
            console.log('数据库打开报错')
        }

        request.onsuccess = e => {
            this.db = request.result
            const db = request.result

            console.log('数据库打开成功')
            // 建表或对象仓库,id作为主键

            successFunc(db)
        }

        // 如果指定的版本号,大于数据库的实际版本号,就会发生数据库升级事件
        // 第一次打开数据库时,会先触发upgradeneeded事件,然后触发success事件
        request.onupgradeneeded = e => {
            // console.log('数据库打开/创建报错')
            // this.db = e.target.result
            const db = e.target.result

            if (!db.objectStoreNames.contains(objStoName)) {
                // 建表
                const objectStore = db.createObjectStore(objStoName, { keyPath: 'id' });

                // 新建索引(索引名称、索引所在的属性、配置对象(说明该属性是否包含重复的值))
                objectStore.createIndex(indexObj.indexName, indexObj.IndexAattrOf, indexObj.config)
            }

        }

        request.blocked = e => {
            // console.log('上一次的数据库连接还未关闭')
        }
    }

    // 创建
    createData = data => {
        const request = this.db.transaction([`${this.objStoName}`], 'readwrite')
            .objectStore(`${this.objStoName}`)
            .add(data)

        request.onsuccess = e => {
            console.log('数据写入成功')
        }

        request.onerror = e => {
            console.log('数据写入失败', e.target.error)
        }
    }

    // 更新
    updateData = data => {
        const request = this.db.transaction([`${this.objStoName}`], 'readwrite').objectStore(`${this.objStoName}`)
            .put(data)

        request.onsuccess = e => {
            // console.log('数据更新成功')
        };

        request.onerror = e => {
            // console.log('数据更新失败')
        }
    }

    //
    retrieveData = (id, successFunc) => {
        const transaction = this.db.transaction([`${this.objStoName}`])
        const objectStore = transaction.objectStore(`${this.objStoName}`)
        const request = objectStore.get(id)

        request.onerror = e => {
            // console.log('事务失败')
        };

        request.onsuccess = e => {
            if (request.result) {
                successFunc(request.result)
                //  console.log('Name: ' + request.result.name)
                //  console.log('Age: ' + request.result.age)
                //  console.log('Email: ' + request.result.email)
            } else {
                //  console.log('未获得数据记录')
            }
        };
    }

    // 遍历
    readAllData = successFunc => {
        const objectStore = this.db.transaction([`${this.objStoName}`], 'readwrite')
            .objectStore(`${this.objStoName}`)

        objectStore.openCursor().onsuccess = e => {
            const cursor = e.target.result

            if (cursor) {
                successFunc(cursor)
                cursor.continue()
                // console.log('Id: ' + cursor.key)
                // console.log('Name: ' + cursor.value.name)
                // console.log('Age: ' + cursor.value.age)
                // console.log('Email: ' + cursor.value.email)
            } else {
                // console.log('没有更多数据了!')
            }
        };
    }

    // 遍历(加入模糊搜索)
    fuzzySearchData = (field, keyWord, successFunc) => {
        const objectStore = this.db.transaction([`${this.objStoName}`], 'readwrite')
            .objectStore(`${this.objStoName}`)
        const data = []

        objectStore.openCursor().onsuccess = e => {
            const cursor = e.target.result

            if (cursor) {
                if (cursor.value[`${field}`].indexOf(keyWord) >= 0) {
                    data.push(cursor.value)
                }
                cursor.continue()

                // console.log('Id: ' + cursor.key)
                // console.log('Name: ' + cursor.value.name)
                // console.log('Age: ' + cursor.value.age)
                // console.log('Email: ' + cursor.value.email)
            } else {
                // console.log('没有更多数据了!')
                successFunc(data)
            }
        };
    }

    deleteData = id => {
        const request = this.db.transaction([`${this.objStoName}`], 'readwrite')
            .objectStore(`${this.objStoName}`)
            .delete(id)

        request.onsuccess = e => {
            // console.log('数据删除成功')
        };
    }

    // 通过索引获取数据
    retrieveByIndex = (indexName, searchTerm, successFunc) => {
        const transaction = this.db.transaction([`${this.objStoName}`], 'readonly')
        const store = transaction.objectStore(`${this.objStoName}`)
        const index = store.index(`${indexName}`)
        const request = index.get(`${searchTerm}`)

        request.onsuccess = e => {
            const { result } = e.target
            console.log(e.target)
            if (result) {
                // ...
                successFunc(result)
            } else {
                // ...
            }
        }
    }
}// 封装by 有蚊子 @2019.11.20 

 

使用示例:

  // indexDB调用示例
  handleDB = () => {
    const indexDB = new IndexDBOperate('chat_help_db', 1, 'chat_help', {
      indexName: 'name',
      IndexAattrOf: 'name',
      config: {
        unique: false,
      },
    }, db => {

      indexDB.fuzzySearchData('name', 'a', result => {
        console.log(result)
      })
      indexDB.createData({ id: 7, name: 'aaa' })
      indexDB.updateData({ id: 3, name: 'a2' })
      indexDB.retrieveByIndex('name', 'a', result => {
         console.log(result)
      }) 
      indexDB.deleteData(7)
      indexDB.retrieveData(1, result => {
         console.log(result)
      })
      indexDB.readAllData(result => {
         console.log(result)
      })
    })
  }

 

 参考资料:

1. http://www.ruanyifeng.com/blog/2018/07/indexeddb.html 阮一峰indexdb使用

2.https://wangdoc.com/javascript/bom/indexeddb.html#idbindex-%E5%AF%B9%E8%B1%A1 indexdb api文档

posted @ 2019-11-21 16:55  有蚊子  阅读(1218)  评论(0编辑  收藏  举报