jakearchibald / idb

IndexedDB, but with promises
https://www.npmjs.com/package/idb
ISC License
6.22k stars 348 forks source link

How to access new version before upgrade #219

Closed ivanjeremic closed 3 years ago

ivanjeremic commented 3 years ago

To add more collections to my database I need to get the current version of the database and then increment it + 1, I know I can open the db 2 times first to get the version, and the second time I open it to create the new document but this seems wrong to me and is also very slow, so how would I access the current version in openDB(mydb, hereIneedTheVersion + 1) I get the new and old version in the upgrade but this doesn't help me at all because it is inside the openDB and cannot be accessed one level above.

const createCollection = async (database: string, collectionName: string) => {
    await openDB(database, undefined, {
      upgrade(db, oldVersion, newVersion, transaction) {
        db.createObjectStore(collectionName, { keyPath: 'id' });
      },
    })
      .then((db) => {
        db.close();
      })
      .catch((error) => {
        console.log(error);
      });
  };

This is how I currently do it and it seems wrong and slow

async function incrVersion(database: any) {
    const db = await openDB(database);
    return db.version + 1;
  }

  const createCollection = async (database: string, collectionName: string) => {
    const version = await incrVersion(database);
    await openDB(database, version, {
      upgrade(db, oldVersion, newVersion, transaction) {
        db.createObjectStore(collectionName, { keyPath: 'id' });
      },
    })
      .then((db) => {
        db.close();
      })
      .catch((error) => {
        console.log(error);
      });
  };
jakearchibald commented 3 years ago

There's https://developer.mozilla.org/en-US/docs/Web/API/IDBFactory/databases, but it isn't supported by Firefox (https://bugzilla.mozilla.org/show_bug.cgi?id=934640).

In the meantime, what you're doing it ok, assuming you need to dynamically add stores.