diff --git a/addons/api/addon-test-support/helpers/indexed-db.js b/addons/api/addon-test-support/helpers/indexed-db.js index 6adc6002e0..01c927cf06 100644 --- a/addons/api/addon-test-support/helpers/indexed-db.js +++ b/addons/api/addon-test-support/helpers/indexed-db.js @@ -20,9 +20,9 @@ * @param hooks */ export function setupIndexedDb(hooks) { - hooks.beforeEach(function () { + hooks.beforeEach(async function () { const indexedDb = this.owner.lookup('service:indexed-db'); - indexedDb.setup(`test-indexed-db-${Date.now()}`); + await indexedDb.setup(`test-indexed-db-${Date.now()}`); }); hooks.afterEach(async function () { diff --git a/addons/api/addon/services/indexed-db.js b/addons/api/addon/services/indexed-db.js index 18ac4f3562..8c2d9984fb 100644 --- a/addons/api/addon/services/indexed-db.js +++ b/addons/api/addon/services/indexed-db.js @@ -93,23 +93,45 @@ const unconvertFields = (result, object, schema, serializer) => { /** * Service to encapsulate the IndexedDB implementation. To use this service, call - * `setup` from the application root and + * `setup` from the application root. This will create the database and the necessary indexes. + * + * Make sure to increment the version number of the database whenever the indexes change. + * This will delete the old database and create a new one with the new indexes. */ export default class IndexedDbService extends Service { // =attributes #db; + #version = 1; + get db() { return this.#db; } - setup(dbName) { + async setup(dbName) { // Don't run setup again if we already have one or if we didn't get a name if (this.#db || !dbName) { return; } + // If the database doesn't exist, just create it and skip checking version + const doesDbExist = await Dexie.exists(dbName); + if (!doesDbExist) { + this.#db = new Dexie(dbName); + this.#db.version(this.#version).stores(modelIndexes); + return; + } + + // Open the database and check if the version is a lower version than the current one + const dbVerifier = new Dexie(dbName); + await dbVerifier.open(); + if (dbVerifier.verno < this.#version) { + await dbVerifier.delete(); + } else { + dbVerifier.close(); + } + this.#db = new Dexie(dbName); - this.#db.version(1).stores(modelIndexes); + this.#db.version(this.#version).stores(modelIndexes); } /** diff --git a/ui/admin/app/routes/application.js b/ui/admin/app/routes/application.js index 4cb0dc6ac3..7c9b8c112f 100644 --- a/ui/admin/app/routes/application.js +++ b/ui/admin/app/routes/application.js @@ -72,7 +72,7 @@ export default class ApplicationRoute extends Route { const userId = this.session.data?.authenticated?.user_id; const hostUrl = this.window.location.host; if (userId && hostUrl) { - this.indexedDb.setup(formatDbName(userId, hostUrl)); + await this.indexedDb.setup(formatDbName(userId, hostUrl)); } } }