class IndexedDB {
constructor(dbName, storeName, version = 1) {
this.db = undefined
this.dbName = dbName
this.storeName = storeName
this.version = version
}
open() {
return new Promise((resolve, reject) => {
// @ts-ignore
const myIndexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB
if (!myIndexedDB) {
const error = new Error('IndexedDB is not supported')
console.warn(error)
return reject(error)
}
const res = window.indexedDB.open(this.dbName, this.version)
res.onsuccess = (event) => {
this.db = event.target.result // 数据库对象
resolve(event)
}
res.onerror = function (event) {
reject(event)
console.log('数据库打开失败...')
}
res.onupgradeneeded = (event) => {
// 数据库创建或升级的时候会触发
const storeName = this.storeName
const db = event.target.result
if (!db.objectStoreNames.contains(storeName)) {
db.createObjectStore(storeName); // 创建表
}
}
})
}
store(func, options = {}, ...args) {
const {
mode = 'readwrite',
more = false
} = options
return new Promise(async (resolve, reject) => {
const objectStore = await this.getObjectStore(mode)
const storePrototype = objectStore[func]
if (func === 'help') {
console.log('reference resources:https://developer.mozilla.org/zh-CN/docs/Web/API/IDBObjectStore')
return resolve(objectStore)
}
if (!(func in objectStore)) {
console.log('reference resources:https://developer.mozilla.org/zh-CN/docs/Web/API/IDBObjectStore')
return reject(`${func} is undefined`)
}
if (typeof storePrototype == 'function') {
const res = objectStore[func](...args)
res.onsuccess = (event) => {
const result = event.target.result
resolve(
more
?
{
res,
event,
result,
objectStore,
bd: this.db,
}
:
result)
}
res.onerror = reject
} else {
resolve(storePrototype)
}
})
}
getObjectStore(mode) {
return new Promise((resolve, reject) => {
if (!this.db) {
setTimeout(async () => resolve(await this.getObjectStore(mode)))
return
}
const transaction = this.db.transaction([this.storeName], mode); // 事务
const objectStore = transaction.objectStore(this.storeName); // 仓库对象
resolve(objectStore)
})
}
}
(async () => {
var dbName = 'DicomViewDB';
var version = 1;
var storeName = 'DicomStore';
const db = new IndexedDB(dbName, storeName, version)
db.open()
// await db.create()
console.log(await db.store('put', { more: false }, '111', '11'))
console.log(await db.store('put', { more: true }, '222', '22'))
console.log(await db.store('put', undefined, '222', '22'))
console.log(await db.store('put', undefined, '333', '33'))
console.log(await db.store('put', undefined, '333', '44'))
console.log(await db.store('put', undefined, '333', '55'))
console.log(await db.store('get', undefined, '55'))
console.log(await db.store('1', undefined, 4))
})()
console