最权威的解释参见官方文档:https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore
最近要做前端数据库方面的开发,对indexdb学习做了封装示例代码如下:
/*
* @Author: chentao
* @Date: 2021-09-14 08:57:36
* @Last Modified by: chentao
* @Last Modified time: 2021-09-14 10:23:30
*/
import IndexDbParams from "../interface/IndexDbParams";
import IndexDbConstant from "../utils/IndexDbConstant";
class IndexDbUtil {
private db: IDBDatabase
public objectStore: IDBObjectStore
//IndexDb的初始化
public indexDbInit(dbParams: IndexDbParams) {
const request: IDBOpenDBRequest = window.indexedDB.open(dbParams.indexDbName, dbParams.dbVersion);
if (!window.indexedDB) {
console.log("Your browser doesn't support a stable version of IndexedDB. Such and such feature will not be available.");
return null;
}
//对 open() 函数的调用会返回一个我们可以作为事件来处理的包含 result(成功的话)或者错误值的 IDBOpenDBRequest 对象
//error事件表示打开数据库失败。
request.onerror = (event) => {
console.log("打开indexDb数据库走错误回调");
};
//success事件表示成功打开数据库。
request.onsuccess = (event) => {
console.log('连接数据库成功', event)
const { result }: any = event.target;
this.db = result
console.log('连接数据库成功db', this.db)
}
//如果指定的版本号,大于数据库的实际版本号,就会发生数据库升级事件upgradeneeded。
request.onupgradeneeded = (event) => {
const { result, transaction }: any = event.target;
this.db = result
console.log('新建数据库或者升级数据库触发')
//判断会话表是否存在
if (!this.db.objectStoreNames.contains(IndexDbConstant.IM_CHAT_OBJECT_STORE_NAME)) {
this.objectStore = this.db.createObjectStore(IndexDbConstant.IM_CHAT_OBJECT_STORE_NAME, {
keyPath: 'id',
autoIncrement: false
});
}
}
return this.db
}
public getInstanceDb() {
return this.db
}
}
export default IndexDbUtil
接下来在我的store.ts文件中调用 模拟数据的增删改查操作,示例代码如下:
import { useContext, createContext } from 'react';
import { storage, pinyin, navigate, getSensitiveMsg, getRandomKey, StringKey, IndexDbUtil } from '@utils';
import IndexDbParams from "../../../interface/IndexDbParams";
import IndexDbConstant from "../../../utils/IndexDbConstant";
export default class Store {
private dbUtil: IndexDbUtil = new IndexDbUtil()
constructor() {
this.init()
}
public async init() {
if (this.dbUtil) {
const dbParams: IndexDbParams = {
indexDbName: IndexDbConstant.DB_NAME,
dbVersion: IndexDbConstant.DB_VERSION
}
this.dbUtil.indexDbInit(dbParams)
}
}
public addData = (objectStoreName: string, bean: Object) => {
console.log('dbUtil', this.dbUtil)
const db = this.dbUtil.getInstanceDb()
if (db) {
console.log('db', db)
const transaction = db.transaction([objectStoreName], 'readwrite') //readwrite readonly
console.log('拿到开启的事物', transaction)
const objectStore = transaction.objectStore(objectStoreName)
let request: IDBRequest = objectStore.add(bean)
console.log('插入后', request)
}
}
public getSingleData = (objectStoreName: string) => {
const db = this.dbUtil.getInstanceDb()
if (db) {
//开启事务
const transaction = db.transaction([objectStoreName], "readonly")
const objectStore = transaction.objectStore(objectStoreName)
const request = objectStore.get("key");
request.onsuccess = (event) => {
const res = Object.prototype.toString.call(event.target)
console.log('res', res)
if (event.target instanceof IDBRequest) {
const target: IDBRequest = event.target
console.log('request_result', target.result)
}
}
}
}
//获取数据记录
public getAllData = (objectStoreName: string) => {
const db = this.dbUtil.getInstanceDb()
if (db) {
//开启事务
const transaction = db.transaction([objectStoreName], "readonly")
const objectStore = transaction.objectStore(objectStoreName)
const cursor = objectStore.openCursor();
cursor.onsuccess = (event) => {
if (event.target instanceof IDBRequest) {
const { result }: IDBRequest = event.target
const cursor = result;
if (cursor) {
const val = cursor.value
console.log("New value", cursor, val)
cursor.continue();
}
}
};
// this.getAllDataArray(objectStoreName)
}
}
//获取所有数据
public getAllDataArray = (objectStoreName: string) => {
console.log('======开启方法2======')
const db = this.dbUtil.getInstanceDb()
if (db) {
//开启事务
const transaction = db.transaction([objectStoreName], "readonly")
const objectStore = transaction.objectStore(objectStoreName)
const allRecords = objectStore.getAll();
const myindexNames = objectStore.indexNames;
console.log('indexNames', myindexNames)
allRecords.onsuccess = function () {
console.log("===方法2===", allRecords.result);
};
}
}
}
export const Context = createContext<Store>(null);
export const useStore = () => useContext(Context);
上面代码要用到的chatItemBean的示例代码:
/*
* @Author: chentao
* @Date: 2021-09-14 10:30:24
* @Last Modified by: chentao
* @Last Modified time: 2021-09-14 10:37:19
*/
const chatItemBean = {
id:'555',
chatId:'chatId',
lastMessage:'lastMessage',
lastMessageTime:'time',
}
export default chatItemBean
界面操作数据示例代码如下:
import React, { useCallback } from 'react';
import { observer } from 'mobx-react-lite';
import { Layout } from '@zxcomponents';
import { useStore } from '../../store';
import IndexDbParams from "../../../../interface/IndexDbParams";
import IndexDbConstant from "../../../../utils/IndexDbConstant";
import ChatItemBean from "../../../../bean/ChatItemBean";
export default observer(() => {
const store = useStore();
const addData = useCallback(async (values) => {
console.log('itemBean', ChatItemBean)
store.addData(IndexDbConstant.IM_CHAT_OBJECT_STORE_NAME, ChatItemBean)
}, []);
const getAllData = useCallback(async (values) => {
store.getAllData(IndexDbConstant.IM_CHAT_OBJECT_STORE_NAME)
}, []);
const getSingleData = useCallback(async () => {
store.getSingleData(IndexDbConstant.IM_CHAT_OBJECT_STORE_NAME)
}, [])
return (
<Layout direction="horizontal">
<Layout style={{}}>
<div>indexDb数据库测试</div>
<button onClick={addData}>添加数据到数据库</button>
<button onClick={getAllData}>获取所有数据记录</button>
<button onClick={getSingleData}>获取单条数据记录</button>
</Layout>
</Layout>
);
});