2021-05-27 19:23:19 +02:00
|
|
|
class IDB{
|
2022-02-11 15:28:22 +01:00
|
|
|
constructor(...args){
|
|
|
|
this.init(...args)
|
|
|
|
}
|
|
|
|
init(name, store){
|
2021-05-27 19:23:19 +02:00
|
|
|
this.name = name
|
|
|
|
this.store = store
|
|
|
|
}
|
2022-02-11 15:28:22 +01:00
|
|
|
start(){
|
2021-05-27 19:23:19 +02:00
|
|
|
if(this.db){
|
|
|
|
return Promise.resolve(this.db)
|
|
|
|
}
|
|
|
|
var request = indexedDB.open(this.name)
|
|
|
|
request.onupgradeneeded = event => {
|
|
|
|
var db = event.target.result
|
|
|
|
db.createObjectStore(this.store)
|
|
|
|
}
|
|
|
|
return this.promise(request).then(result => {
|
|
|
|
this.db = result
|
|
|
|
return this.db
|
|
|
|
}, target =>
|
|
|
|
console.warn("DB error", target)
|
|
|
|
)
|
|
|
|
}
|
|
|
|
promise(request){
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
return pageEvents.race(request, "success", "error").then(response => {
|
|
|
|
if(response.type === "success"){
|
|
|
|
return resolve(event.target.result)
|
|
|
|
}else{
|
|
|
|
return reject(event.target)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
transaction(method, ...args){
|
2022-02-11 15:28:22 +01:00
|
|
|
return this.start().then(db =>
|
2021-05-27 19:23:19 +02:00
|
|
|
db.transaction(this.store, "readwrite").objectStore(this.store)[method](...args)
|
|
|
|
).then(this.promise.bind(this))
|
|
|
|
}
|
|
|
|
getItem(name){
|
|
|
|
return this.transaction("get", name)
|
|
|
|
}
|
|
|
|
setItem(name, value){
|
|
|
|
return this.transaction("put", value, name)
|
|
|
|
}
|
|
|
|
removeItem(name){
|
|
|
|
return this.transaction("delete", name)
|
|
|
|
}
|
|
|
|
removeDB(){
|
|
|
|
delete this.db
|
|
|
|
return indexedDB.deleteDatabase(this.name)
|
|
|
|
}
|
|
|
|
}
|