IndexedDB 的工具函数集合,主要包括以下功能:
-
openStore
: 打开指定名称的 IndexedDB 数据库,并创建或更新指定名称的对象存储空间。接受一个包含数据库名称、存储空间名称、键路径和可选索引数组的参数对象,并返回一个 Promise,该 Promise 在成功时解析为打开的 IDBDatabase 实例,或在失败时解析为 null。 -
updateStore
: 向指定的对象存储空间中添加或修改数据。接受一个已打开的 IDBDatabase 实例、存储空间名称和要添加或修改的数据对象作为参数,并返回一个 Promise,在成功时解析为 true,或在失败时解析为 false。 -
deleteStore
: 根据键值从指定的对象存储空间中删除数据。接受一个已打开的 IDBDatabase 实例、存储空间名称和要删除的键值作为参数,并返回一个 Promise,在成功时解析为 true,或在失败时解析为 false。 -
find
: 获取指定对象存储空间中的所有数据。接受一个已打开的 IDBDatabase 实例和存储空间名称作为参数,并返回一个 Promise,在成功时解析为包含所有数据的数组,或在失败时解析为空数组。 -
findOne
: 根据键值获取指定对象存储空间中的一条数据。接受一个已打开的 IDBDatabase 实例、存储空间名称和要获取的键值作为参数,并返回一个 Promise,在成功时解析为对应的数据对象,或在失败时解析为空数组。 -
clearAll
: 清空指定对象存储空间中的所有数据。接受一个已打开的 IDBDatabase 实例和存储空间名称作为参数,并返回一个 Promise,在成功时解析为 true,或在失败时解析为 false。
interface openStoreType {databaseName: string,storeName: string,keyPath: string,indexes?: Array<string>
}export const openStore = ({ databaseName, storeName, keyPath, indexes = [] }: openStoreType): Promise<IDBDatabase | null> => {return new Promise((resolve, reject) => {// 打开indexedDBlet request = window.indexedDB.open(databaseName, 1);request.onsuccess = (evt: Event) => {console.log('indexedDB open success!', evt);resolve((evt.target as IDBOpenDBRequest).result);}request.onerror = (evt: Event) => {console.log('indexedDb open fial!', evt);reject(null);}request.onupgradeneeded = (evt: IDBVersionChangeEvent) => {if ((evt?.target as IDBOpenDBRequest)?.result) {const { result } = evt.target as IDBOpenDBRequest;// 创建数据对象const store = result.createObjectStore(storeName, { autoIncrement: true, keyPath });// 创建索引for (let i in indexes) {store.createIndex(indexes[i], indexes[i], { unique: true });}// 创建数据对象成功store.transaction.oncomplete = (evt: any) => {console.log('object store create success!', evt);}console.log('indexedDb upgrade success!', evt);} else {console.log('indexedDb upgrade fail!', evt);}}});
}// 新增(add),修改(put)
export const updateStore = async (db: IDBDatabase, storeName: string, data: any): Promise<boolean> => {return new Promise((resolve, reject) => {// 获取store对象let store = db.transaction([storeName], 'readwrite').objectStore(storeName);// 添加或修改数据const request = store.put({ ...data, updateAt: new Date() });request.onsuccess = (evt: Event) => {console.log('update success!', evt);resolve(true);}request.onerror = (evt: Event) => {console.log('update fail!', evt);reject(false);}});
}// 根据key删除对应数据
export const deleteStore = async (db: IDBDatabase, storeName: string, key: string | number): Promise<boolean> => {return new Promise((resolve, reject) => {// 获取store对象let store = db.transaction([storeName], 'readwrite').objectStore(storeName);// 根据key删除数据const request = store.delete(key);request.onsuccess = (evt: Event) => {console.log('delete success!', evt);resolve(true);}request.onerror = (evt: Event) => {console.log('delete fail!', evt);reject(false);}});
}// 获取所有数据
export const find = (db: IDBDatabase, storeName: string): Promise<any[]> => {return new Promise((resolve, reject) => {// 获取store对象let store = db.transaction([storeName], 'readwrite').objectStore(storeName);const request = store.getAll();request.onsuccess = (evt: Event) => {console.log('get all data success!', evt);resolve((evt.target as any).result);}request.onerror = (evt: Event) => {console.log('get all data fail!', evt);reject([]);}});
}// 获取一条数据
export const findOne = (db: IDBDatabase, storeName: string, key: number | string): Promise<any> => {return new Promise((resolve, reject) => {let store = db.transaction([storeName], 'readwrite').objectStore(storeName);const request = store.get(key);request.onsuccess = (evt: Event) => {console.log('get data success!', evt);resolve((evt.target as any).result);}request.onerror = (evt: Event) => {console.log('get data fail!', evt);reject([]);}});
}// 清空所有数据
export const clearAll = (db: IDBDatabase, storeName: string): Promise<boolean> => {return new Promise((resolve, reject) => {let store = db.transaction([storeName], 'readwrite').objectStore(storeName);const request = store.clear();request.onsuccess = (evt: Event) => {console.log('clear data success!', evt);resolve(true);}request.onerror = (evt: Event) => {console.log('clear data fail!', evt);reject(false);}});
}
方法调用
// 创建
let indexedDB= await openStore({databaseName: "test",storeName: "room",keyPath: "id",indexes: ["width", "height", "length"],
});// 添加
await updateStore(indexed, "room", { width: 50, height: 20, length: 60 });// 修改
await updateStore(indexed, "room", {id: 1,width: Math.floor(Math.random() * 100),height: Math.floor(Math.random() * 100),length: Math.floor(Math.random() * 100),
});// 删除
await deleteStore(indexed, "room", 1);// 获取所有数据
let res = await find(indexed, "room");// 根据key查询数据
let res = await findOne(indexed, "room", 2);