Skip to content

Commit

Permalink
feat: 🎸 Add migration check to delete index DB when updating
Browse files Browse the repository at this point in the history
  • Loading branch information
ZedLi committed Sep 25, 2024
1 parent ace65ea commit af77cc4
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 6 deletions.
4 changes: 2 additions & 2 deletions addons/api/addon-test-support/helpers/indexed-db.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 () {
Expand Down
28 changes: 25 additions & 3 deletions addons/api/addon/services/indexed-db.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion ui/admin/app/routes/application.js
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
}
}
Expand Down

0 comments on commit af77cc4

Please sign in to comment.