浏览器也支持数据库,目前有IndexDB 和 WebSql(仅Chrome支持)可以选择,相比localStrorage ,IndexDB 可以存的数据更多,而且支持索引,能存对象。
综合考虑我在electron 中选择 IndexDB 做为配置存储方案。
let DB;
let dbName = "upper_ebike";
let version = "1";
let OBJECT_STORE_CONFIG = "_OBJECT_STORE_CONFIG"
function createDb() {
let request = window.indexedDB.open(dbName, version);
request.onerror = function (event) { console.error(event) }
request.onsuccess = (event) => {
DB = request.result//可以拿到数据库对象
}
//如果指定的版本号,大于数据库的实际版本号,就会发生数据库升级事件upgradeneeded
request.onupgradeneeded = function (event) {
DB = event.target.result;
//判断是否存在
if (!DB.objectStoreNames.contains(OBJECT_STORE_CONFIG)) {
let objectStore = DB.createObjectStore(OBJECT_STORE_CONFIG, { keyPath: 'name' });
}
}
}
async function add(objectStoreName, data) {
return new Promise((resolve, reject) => {
var request = DB.transaction([objectStoreName], 'readwrite')
.objectStore(objectStoreName)
.add(data);
request.onsuccess = function (event) {
console.log('数据写入成功');
resolve();
};
request.onerror = function (event) {
console.log('数据写入失败');
reject(event);
}
})
}
async function getOne(objectStoreName, key) {
return new Promise((resolve, reject) => {
let objectStore = DB.transaction([objectStoreName], 'readwrite')
.objectStore(objectStoreName)
let request = objectStore.get(key)
request.onsuccess = function (event) {
// console.log(request.result)
resolve(request.result);
};
request.onerror = function (event) {
reject(event);
}
})
}
async function getAll(objectStoreName) {
return new Promise((resolve, reject) => {
let objectStore = DB.transaction([objectStoreName], 'readwrite')
.objectStore(objectStoreName);
let request = objectStore.getAll();
request.onsuccess = () => {
resolve(request.result)
}
request.onerror = (err) => {
reject(err)
}
})
}
/**
* 可以更新的保存
*/
async function put(objectStoreName, data) {
return new Promise((resolve, reject) => {
let objectStore = DB.transaction([objectStoreName], 'readwrite')
.objectStore(objectStoreName);
let request = objectStore.put(data);
request.onsuccess = function (event) {
console.log('数据写入成功');
resolve();
};
request.onerror = function (event) {
console.log('数据写入失败');
reject(event);
}
})
}
createDb();
export { add, getOne, getAll, put, OBJECT_STORE_CONFIG }