使用索引数据库在现有数据库中动态创建对象存储
dynamically create object stores in existing databases with indexed db
我正在使用 idb 执行索引数据库操作。
我们正在实施缓存系统。
我需要动态创建对象存储。
如何在不知道版本的情况下在现有数据库中添加对象存储?
因为显然只有在版本增加的情况下才能在升级回调中创建对象存储。所以我们事先不知道将要创建多少个对象存储。
获取数据库的版本而不增加它,就像这样,我忘记了具体的语法:
function getDatabaseVersion(name) {
return new Promise((resolve, reject) => {
const request = indexedDB.open(name);
request.onsuccess = event => {
const database = event.target.result;
database.close();
resolve(event.version);
};
request.onerror = event => reject(event.target.error);
request.onblocked = event => reject(new BlockedIndefinitelyError());
});
}
class BlockedIndefinitelyError extends Error {
constructor(message = 'Database open was blocked') {
super(message);
}
}
// version is optional, leave as undefined if not upgrading
function open(name, version, upgradeneeded) {
return new Promise((resolve, reject) => {
const request = indexedDB.open(name, version);
request.onupgradeneeded = upgradeneeded;
request.onerror = event => reject(event.target.error);
request.onsuccess = event => resolve(event.target.result);
request.onblocked = event => reject(new BlockedIndefinitelyError());
});
}
async function dothings() {
const name = 'mydb';
const version = await getDatabaseVersion(name);
if(conditionDecidingWhetherToCreateNewTablesIsTrue) {
const database = await open(name, version + 1, event => {
const database = event.target.result;
for (const store of storesToCreate) {
database.createObjectStore(store, store.options);
}
});
database.close();
}
}
我正在使用 idb 执行索引数据库操作。 我们正在实施缓存系统。 我需要动态创建对象存储。 如何在不知道版本的情况下在现有数据库中添加对象存储? 因为显然只有在版本增加的情况下才能在升级回调中创建对象存储。所以我们事先不知道将要创建多少个对象存储。
获取数据库的版本而不增加它,就像这样,我忘记了具体的语法:
function getDatabaseVersion(name) {
return new Promise((resolve, reject) => {
const request = indexedDB.open(name);
request.onsuccess = event => {
const database = event.target.result;
database.close();
resolve(event.version);
};
request.onerror = event => reject(event.target.error);
request.onblocked = event => reject(new BlockedIndefinitelyError());
});
}
class BlockedIndefinitelyError extends Error {
constructor(message = 'Database open was blocked') {
super(message);
}
}
// version is optional, leave as undefined if not upgrading
function open(name, version, upgradeneeded) {
return new Promise((resolve, reject) => {
const request = indexedDB.open(name, version);
request.onupgradeneeded = upgradeneeded;
request.onerror = event => reject(event.target.error);
request.onsuccess = event => resolve(event.target.result);
request.onblocked = event => reject(new BlockedIndefinitelyError());
});
}
async function dothings() {
const name = 'mydb';
const version = await getDatabaseVersion(name);
if(conditionDecidingWhetherToCreateNewTablesIsTrue) {
const database = await open(name, version + 1, event => {
const database = event.target.result;
for (const store of storesToCreate) {
database.createObjectStore(store, store.options);
}
});
database.close();
}
}