使用索引数据库在现有数据库中动态创建对象存储

时间:2019-11-22 20:17:18

标签: indexeddb

我正在使用idb来执行索引数据库操作。 我们正在实现一个缓存系统。 我需要动态创建对象存储。 如何在不知道版本的情况下将对象存储添加到existinin数据库中? 因为显然,如果版本增加,则只能在升级回调中创建对象存储。因此,我们事先不知道将要创建多少个对象存储。

1 个答案:

答案 0 :(得分:1)

获取数据库版本而不增加它,就像这样,我忘记了确切的语法:

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();
  }
}