jakearchibald / idb

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

Mutiple stores in Keyval Store #210

Closed puneetkverma closed 3 years ago

puneetkverma commented 3 years ago

How can we increment schema version of the database in the following multiple Keyval Store database.

const dbStores: string[] = ["store1", "store2", "store3", "store4", "store5"];

const dbPromise = openDB("sharedPreference", 1, {
  upgrade(db) {
    dbStores.map(store => db.createObjectStore(store));
  }
});

const idbKeyval = {
  async get(PREF_NAME: string, key: string) {
    return (await dbPromise).get(PREF_NAME, key);
  },
  async set(PREF_NAME: string, key: string, val: any) {
    return (await dbPromise).put(PREF_NAME, val, key);
  },
  async delete(PREF_NAME: string, key: string) {
    return (await dbPromise).delete(PREF_NAME, key);
  },
  async clear(PREF_NAME: string) {
    return (await dbPromise).clear(PREF_NAME);
  }
};

What problems could occur if I use the above code without incrementing the version ?

jakearchibald commented 3 years ago

This could happen:

  1. User loads your code for the first time, which creates the database and calls update, which creates stores 1-5.
  2. You modify your code to add "store6" to dbStores.
  3. User returns to your site, and runs your updated code. update isn't called, as the version number hasn't changed.
  4. User gets an error when your code tries to read/write from "store6".
puneetkverma commented 3 years ago

Thanks @jakearchibald, reproduced the error. Could you please help me how we can increment the db version so that every time we change the code upgrade gets called and includes new stores in the db ? Or if we have some other methods to handle the above scenario ?