更新代码

master
yutent 2023-04-11 18:01:35 +08:00
parent 66e10c2886
commit dcc9edf859
4 changed files with 136 additions and 0 deletions

19
src/api.js Normal file
View File

@ -0,0 +1,19 @@
/**
* indexdb API
* @author yutent<yutent.io@gmail.com>
* @date 2020/08/31 15:46:20
*/
import Method from './method.js'
export default class Api {
constructor(db) {
this.db = db
}
table(name) {
var ta = this.db.transaction(name, 'readwrite')
var table = ta.objectStore(name)
return new Method(table)
}
}

14
src/helper.js Normal file
View File

@ -0,0 +1,14 @@
/**
* indexdb辅助方法
* @author yutent<yutent.io@gmail.com>
* @date 2020/08/31 15:20:56
*/
export function defer() {
let obj = {}
obj.promise = new Promise((resolve, reject) => {
obj.resolve = resolve
obj.reject = reject
})
return obj
}

View File

@ -0,0 +1,66 @@
/**
* {}
* @author yutent<yutent.io@gmail.com>
* @date 2023/04/11 15:10:04
*/
import { defer, createTable } from './helper.js'
import Api from './api.js'
export function createStore(name, version = 1) {
let req = window.indexedDB.open(name, version)
let _ = defer()
req.addEventListener('upgradeneeded', ev => {
_.resolve(ev.target.result)
})
req.addEventListener('error', ev => {
_.reject(ev.target.result.error)
})
return _.promise
}
export function deleteStore(name) {
let req = window.indexedDB.deleteDatabase(name)
let _ = defer()
req.addEventListener('success', ev => {
_.resolve()
})
req.addEventListener('error', ev => {
_.reject(ev.target.result.error)
})
return _.promise
}
export function createTable(db, { name, config }) {
var opt = {}
var table
if (config.primaryKey) {
opt.keyPath = config.primaryKey
}
if (config.autoIncrement) {
opt.autoIncrement = config.autoIncrement
}
table = db.createObjectStore(name, opt)
if (config.indexes && config.indexes.length) {
for (let it of config.indexes) {
table.createIndex(it + '_idx', it)
}
}
}
export function getStore(name) {
let req = window.indexedDB.open(name)
let _ = defer()
req.addEventListener('success', ev => {
_.resolve(ev.target.result)
})
req.addEventListener('error', ev => {
_.reject(ev.target.result.error)
})
return _.promise
}

37
src/method.js Normal file
View File

@ -0,0 +1,37 @@
/**
* {}
* @author yutent<yutent.io@gmail.com>
* @date 2023/04/11 15:11:31
*/
export default class Method {
constructor(table) {
this.table = table
}
put(obj) {
this.table.put(obj)
}
get(id) {
var res = this.table.get(id)
return new Promise(resolve => {
res.onsuccess = function (ev) {
resolve(this.result)
}
})
}
getAll() {
var res = this.table.getAll()
return new Promise(resolve => {
res.onsuccess = function (ev) {
resolve(this.result)
}
})
}
delete(id) {
this.table.delete(id)
}
}