IndexedDB programming with Dexie.js

IndexedDB programming with Dexie.js

In the previous blogs posts about IndexedDB we have seen that the API is not the easiest to work with. Everything is asynchronous and uses callbacks unlike the newer interfaces, like Fetch, that use Promises. And you need to write a lot of boilerplate code for transaction handling and queries.

Fortunately there are a few libraries that simplify working with IndexedDB. One is idb from Jake Archibald that I mentioned in this blogs post. It wraps the IndexedDB methods in Promises.

[…]

Compared to idb, Dexie goes further and does not just wrap the methods in Promises it also simplifies transaction handling and it adds a more convenient query support.

[…]

First you need to create an instance of the Dexie object. The argument specifies the database name.

A web application can create as many databases as it wants. Each database needs to have a unique name within the origin.

Next you specify the schema of the database. db.version() specifies the database version number and returns a Version object. This object provides the stores() method that specifies the database schema (object store, primary key, indexes) for this particular version.

[…]

The example above creates one object store with the name contacts with a primary key id and two indexes name and location.

Schema creation and upgrade only runs when the version number of the database differs from the provided parameter to the db.version call. If you want to change the schema you add another db.version call with a version number that is greater than the previous version.

For example if you want to add another index city you add this code

[…]

Before the application can work with the database it needs to open it with db.open(), but you can omit this call because Dexie automatically calls open() when it executes the first query.

There are two cases where you explicitly have to call db.open(). When you created the Dexie object with the autoOpen option set to false (new Dexie('dbname', {autoOpen: false})) or when you closed the database with db.close()

Dexie automatically creates the database when it does not exist.

[…]

All IndexedDB operations must run inside a transaction. In this blog post you see that most examples don't explicitly start a transaction and still work. This is a feature of Dexie that automatically starts and commits transactions when it runs a database operation. This is very convenient but you also need to be aware that this can lead to performance degradation.

[…]

Each time you call add() Dexie opens a transaction and commits it.

[…]