// indexDB.ts
// 索引和游标分页查询数据类型
type SearchParamsType = {
storeName: string,
indexName: string,
indexValue?: string | number | null,
page: number,
pageSize: number
}
// 仓库索引对象类型
type StoreListItem = {
name: string,
params: unknown
}
// 插入数据类型
type DataType = {
[key: string]: unknown;
}
// 创建数据表参数类型
export interface StoreType {
storeName: string,
optionalParameters: {
keyPath: string[] | string,
autoIncrement?: boolean
},
storeIndexList?: StoreListItem[] // 假设 storeList 是一个数组,可以根据实际情况更改类型
}
export default class IndexDB<T extends (StoreType[] | StoreType)> {
private dbName: string;
private version: number;
private IndexDB: IDBDatabase | undefined;
isReady: boolean;
constructor(dbName:string, version:number = 1) {
this.IndexDB = void 0; // Initialize IndexDB
this.dbName = dbName
this.version = version
this.isReady = false
}
// 打开数据库
/**
*
* @param store 初始化数据库表结构
* @returns db
*/
openDB(store: T){
return new Promise((resolve, reject) => {
// this.store = store
// 兼容浏览器
const dbObj = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB
// 打开数据库,若没有则会创建
const request = dbObj.open(this.dbName, this.version)
// 数据库打开成功回调
request.onsuccess = (event) => {
this.IndexDB = (event.target as IDBOpenDBRequest).result
console.log("数据库打开成功",this.IndexDB)
resolve(true) // 数据库对象
}
// 数据库打开失败的回调
request.onerror = (event) => {
console.log("数据库打开失败",event)
reject(null)
}
// 数据库有更新时候的回调
request.onupgradeneeded = (event) => {
console.log("数据库有更新")
const db = (event.target as IDBOpenDBRequest).result
let objectStore: IDBObjectStore
// 初始化存储库
if(this.version === 1){
// 如果多表格
if(Array.isArray(store)){
store.forEach(storeItem => {
const { storeName, optionalParameters, storeIndexList } = storeItem
objectStore = db.createObjectStore(storeName, optionalParameters)
// 创建索引,在后面查询数据的时候可以根据索引查
storeIndexList?.forEach(item => {
objectStore.createIndex(`${item.name}Index`, item.name, item.params)
})
})
return
}
// 单表格
const { storeName, optionalParameters, storeIndexList } = store
objectStore = db.createObjectStore(storeName, optionalParameters)
// 创建索引,在后面查询数据的时候可以根据索引查
storeIndexList?.forEach(item => {
objectStore.createIndex(`${item.name}Index`, item.name, item.params)
})
}
}
})
}
/**
* 数据库创建完成
*/
setReadyState(){
this.isReady = true
}
/**
* 关闭数据库
*/
closeDB(){
this.IndexDB?.close()
console.log("数据库已关闭")
}
/**
* 获取当前实例数据库
* @returns
*/
// getIndexDB(){
// return this.IndexDB
// }
/**
* 数据插入
* @param storeName 仓库名
* @param data 插入数据
* @returns
*/
inert(storeName: string, data: DataType): Promise<boolean> {
return new Promise((resolve, reject) => {
const request = this.IndexDB?.transaction([storeName], "readwrite") // 事务对象 指定表格名称和操作模式("只读"或"读写")
.objectStore(storeName) // 指定表格
.add(data) // 插入数据
if(request){
// 插入数据成功的回调
request.onsuccess = () => {
// console.log("数据插入成功")
resolve(true)
}
// 插入数据失败的回调
request.onerror = (event) => {
console.log("数据插入失败", event)
reject(false)
}
}else resolve(false)
})
}
/**
* 数据根据主键查询
* @param storeName 仓库名
* @param key 主键值
*/
queryByKeyr<U>(storeName: string, key: string | number): Promise<U | null> {
return new Promise((resolve, reject) => {
const request = this.IndexDB?.transaction([storeName]) // 事务对象 指定表格名称和操作模式("只读"或"读写")
.objectStore(storeName) // 指定表格
.get(key) // 插入数据
if(request){
// 查询数据成功的回调
request.onsuccess = () => {
// console.log("数据查询成功")
resolve(request.result as U)
}
// 查询数据失败的回调
request.onerror = (event) => {
console.log("queryByKey 查询失败", event)
reject(null)
}
}else resolve(null)
})
}
/**
* 通过游标读取所有数据
* @param storeName 仓库名
*/
queryByCursor<U>(storeName: string): Promise<U[] | null> {
return new Promise((resolve, reject) => {
try{
const list: U[] = []
const request = this.IndexDB?.transaction([storeName], "readwrite") // 事务对象 指定表格名称和操作模式("只读"或"读写")
.objectStore(storeName) // 指定表格
.openCursor() // 指针对象
if(request){
request.onsuccess = (event: Event) => {
// 游标开启成功,逐行读数据
const cursor = (event.target as IDBRequest).result
if(cursor){
list.push(cursor.value)
cursor.continue()
}else resolve(list)
}
}else resolve(null)
}catch(err){
console.log("queryByCursor error", err)
reject(null)
}
})
}
/**
* 通过游标读取最新数据
* @param storeName 仓库名
*/
queryLatestByCursor<U>(storeName: string): Promise<U | null>{
return new Promise((resolve, reject) => {
try{
const list: Record<string, U>[] = []
const request = this.IndexDB?.transaction([storeName], "readwrite") // 事务对象 指定表格名称和操作模式("只读"或"读写")
.objectStore(storeName) // 指定表格
.openCursor() // 指针对象
if(request){
request.onsuccess = (event: Event) => {
// 游标开启成功,逐行读数据
const cursor = (event.target as IDBRequest).result
if(cursor){
list.push(cursor.value)
cursor.continue()
}else resolve(list.at(-1) as U)
}
}else resolve(null)
}catch(err){
console.log("queryLatestByCursor error",err)
reject(null)
}
})
}
/**
* 通过索引读取所有数据
* @param storeName
* @param indexName
* @param indexValue
*/
queryByIndex<U>(storeName: string, indexName: string, indexValue: string | number): Promise<U[] | null> {
return new Promise((resolve, reject) => {
const request = this.IndexDB?.transaction([storeName]) // 事务对象 指定表格名称和操作模式("只读"或"读写")
.objectStore(storeName) // 指定表格
.index(indexName).get(indexValue) // 根据索引和索引值查询
if(request){
// 查询数据成功的回调
request.onsuccess = (event) => {
// console.log("数据查询成功")
resolve((event.target as IDBRequest).result as U[])
}
// 查询数据失败的回调
request.onerror = (event) => {
console.log("queryByIndex 查询失败", event)
reject(null)
}
}else resolve(null)
})
}
/**
* 通过索引和游标分页查询数据
* @param storeName
* @param indexName
* @param indexValue
* @param page,
* @param pageSize
* @returns
*/
queryByIndexCursor<U>({
storeName,
indexName,
indexValue,
page,
pageSize
}: SearchParamsType): Promise<U[] | null> {
return new Promise((resolve, reject) => {
try{
const list: U[] = []
let counter = 0 // 计数器
let advanced = true // 是否跳过多少条查询
const request = this.IndexDB?.transaction([storeName], "readonly") // 事务对象 指定表格名称和操作模式("只读")
.objectStore(storeName) // 指定表格
.index(indexName) // 索引对象
.openCursor(indexValue ? IDBKeyRange.only(indexValue) : null) // 指针对象
if(request){
request.onsuccess = (event: Event) => {
// 游标开启成功,逐行读数据
const cursor = (event.target as IDBRequest).result
// 查询分页逻辑
if(page > 1 && advanced) {
advanced = false
cursor.advance((page - 1) * pageSize)
return
}
if(cursor) {
list.push(cursor.value)
counter++
if(counter < pageSize) {
cursor.continue() // 遍历了存储对象中的所有内容
}else{
resolve(list)
}
}
}
}else resolve(null)
}catch(err){
console.log("queryByIndexCursor error", err)
reject(null)
}
})
}
/**
* 更新数据
* @param storeName
* @param data
*/
updated(storeName: string, data: DataType): Promise<boolean> {
return new Promise((resolve, reject) => {
const request = this.IndexDB?.transaction([storeName], "readwrite") // 事务对象 指定表格名称和操作模式("只读"或"读写")
.objectStore(storeName) // 指定表格
.put(data)
if(request){
// 查询数据成功的回调
request.onsuccess = () => {
// console.log("数据更新成功")
resolve(true)
}
// 查询数据失败的回调
request.onerror = (event) => {
console.log("updated 更新失败",event)
reject(event)
}
}else resolve(false)
})
}
/**
* 更新数据 不存在创建
* @param storeName
* @param data
* data: Record<string, T>
*/
async upsert(storeName: string, data?: DataType): Promise<boolean> {
try{
const list = await this.queryByCursor(storeName)
// 新建
if(Array.isArray(list) && !list.length && data){
if(await this.inert(storeName, data)){
return true
}
}
const res = Array.isArray(list) && list.at(-1)
if(res && data){
await this.inert(storeName, data)
return true
}
return false
}catch(err){
console.log("upsert error", err)
return false
}
}
/**
* 删除数据
* @param storeName
* @param key
*/
delete(storeName: string, key: string | number): Promise<boolean> {
return new Promise((resolve, reject) => {
const request = this.IndexDB?.transaction([storeName], "readwrite") // 事务对象 指定表格名称和操作模式("只读"或"读写")
.objectStore(storeName) // 指定表格
.delete(key)
if(request){
// 查询数据成功的回调
request.onsuccess = () => {
// console.log("数据删除成功")
resolve(true)
}
// 查询数据失败的回调
request.onerror = (event) => {
console.log("delete 删除失败",event)
reject(event)
}
}else resolve(false)
})
}
}使用
import IndexDB,{ StoreType } from '@/utils/indexDB'
async function createDB(): Promise<IndexDB<StoreType | StoreType[]> | null> {
return new Promise(reslove => {
const indexDB = new IndexDB('cache', 1)
indexDB.openDB([
{
storeName: 'cacheMicro', // 仓库名
optionalParameters: { keyPath: 'id', autoIncrement: true }, // 主键 keyPath可穿数组
storeIndexList:[ // 索引字段配置
{
name: 'cacheMicroAppList',
params:{
unique: false
}
}
]
},
{
storeName: 'cacheMicroNum', // 多个仓库创建
optionalParameters: { keyPath: 'id', autoIncrement: true },
},
]).then(() => {
if (indexDB) {
reslove(indexDB)
} else {
throw new Error("Failed to get IndexDB instance");
}
})
})
}
await createDB()