Search code examples
typescriptdexie

Dexie's Version.upgrade() using typescript


I am having a typescript application using Dexie. I would like to create a new version where I also want to populate the the table using Version.upgrade().

I extended the sample https://github.com/dfahlander/Dexie.js/tree/master/samples/typescript as following:

export interface ICity {
    id?: number;
    name: string;
}

export class AppDatabase extends Dexie {

    contacts: Dexie.Table<Contact, number>;
    emails: Dexie.Table<IEmailAddress, number>;
    phones: Dexie.Table<IPhoneNumber, number>;
    cities: Dexie.Table<ICity, number>;

    constructor() {

        super("ContactsDatabase");

        var db = this;

        //
        // Define tables and indexes
        //
        db.version(1).stores({
            contacts: '++id, firstName, lastName',
            emails: '++id, contactId, type, email',
            phones: '++id, contactId, type, phone',
        });

        db.version(2).stores({
            cities: '++id, name'
        }).upgrade((tx: Dexie.Transaction) => {
            tx.table("cities").bulkAdd([
                { name: "London" },
                { name: "Berlin" },
                { name: "Paris" }
            ]);
        });

        // Let's physically map Contact class to contacts table.
        // This will make it possible to call loadEmailsAndPhones()
        // directly on retrieved database objects.
        db.contacts.mapToClass(Contact);
    }
}

But it did not work as intended.

Has someone a hint, please?


Solution

  • The upgrade function will only run for clients having version 1 installed. A clean browser will go directly to version 2 without upgrade function.

    Solution : add a populate function that inits the cities table.

        db.on('populate', () => db.cities.bulkAdd([
          { name: "London" },
          { name: "Berlin" },
          { name: "Paris" }
        ]));
    

    Keep your upgrade function as well if your users may be on version 1 still.