我有一个函数,基本上从远程数据库抓取一堆交付作业,并将它们保存到indexeddb中进行离线备份。每次下载作业后,它都会调用addToDatabase()函数。
如果该日期的作业已经在数据库中,我想用最新的作业覆盖现有的作业,以防在下载数据和交付作业之间的详细信息有任何更新。
在函数的开头我有下面的代码:
let unixTimestamp = parseInt(Math.round(+new Date()/1000));
console.log('Database version '+unixTimestamp+' loading.');
// open our database with the unix timestamp as a version to force onupgradeneeded
let DBOpenRequest = window.indexedDB.open(storeName,unixTimestamp);
如果我第二次调用它,数据库版本保持不变。
完整功能如下...
function addToDatabase(storeName,date,jobs)
{
let unixTimestamp = parseInt(Math.round(+new Date()/1000));
console.log('Database version '+unixTimestamp+' loading.');
// open our database with the unix timestamp as a version to force onupgradeneeded
let DBOpenRequest = window.indexedDB.open(storeName,unixTimestamp);
DBOpenRequest.onerror = function(event) {
console.log('Error loading database.');
};
DBOpenRequest.onupgradeneeded = function(event)
{
console.log('Database version '+unixTimestamp+' initialised.');
db = event.target.result;
let transaction = event.target.transaction;
if(!db.objectStoreNames.contains(date))
{
//objectStore does not exist so create it...
console.log('block 1');
let store = db.createObjectStore(date,{keyPath: 'id', autoIncrement:true});
store.transaction.oncomplete =
function(evt) {
// Store values in the newly created objectStore.
let jobObjectStore = db.transaction(date, "readwrite").objectStore(date);
Object.entries(jobs).forEach((entry) => {
const [key, value] = entry;
jobObjectStore.put({
id:key,
contract:value.contract,
runContract:value.runContract,
items:value.items,
});
});
}
}
else
{
console.log('block 2');
let jobObjectStore = db.transaction(date, "readwrite").objectStore(date);
// Store values in the existing objectStore.
Object.entries(jobs).forEach((entry) => {
const [key, value] = entry;
jobObjectStore.put({
id:key,
contract:value.contract,
runContract:value.runContract,
items:value.items,
});
});
}
}
}
因此,当我第一次调用此函数时,会得到以下控制台输出。
Database version 1650561313 loading.
Database version 1650561313 initialised.
block 1
这和预期的一样,数据库版本是1650561313。但是,当我第二次调用该函数时,我得到了以下控制台输出。我打开的数据库版本号更高,但所需的onupgrade没有被触发,数据库仍然是版本1650561313。
Database version 1650561338 loading.
任何帮助,为什么它不是触发onupgradeneded将不胜感激!
1条答案
按热度按时间wgx48brx1#
这确实是因为之前的连接没有在第一次运行该功能时关闭。我也意识到最好是删除日期条目并从服务器重新下载。工作功能如下,以防有人尝试类似的事情...