IndexedDB

Introduction

The IndexedDB API is mostly asynchronous. The API doesn't give you data by returning values; instead, you have to pass a callback function.

examples/web-worker/main.js
 const cb = () => { // This is a callback fucntion }

You don't "store" a value into the database, or "retrieve" a value out of the database through synchronous means.

Instead, you "request" that a database operation happens.

examples/web-worker/main.js
  let indexedDB = new IndexedDB();
  const cb = () => {
      indexedDB.get()
  };
  indexedDB.init(cb);
}

You get notified by a DOM event when the operation finishes, and the type of event you get lets you know if the operation succeeded or failed. This sounds a little complicated at first, but there are sanity measures baked in. It's not that different from the way that XMLHttpRequest works.

Behind the Scenes

Let's take a look at indexed-db.js. We have very simple IndexedDB object.

examples/web-worker/assets/js/indexed-db.js
function IndexedDB() {
    const name = 'ifc-js';
    const version = 1;
    const transactionName = 'scene';
    var database;
    return {
        // Todo
    }
}

As we discussed earlier, we "request" that a database operation happens. The initialization looks like this. Don't focus too much on the code. Simply note that we have a request, and it can either be

  • onupgradeneeded

  • onsucess

  • onerror

Our code looks like this if we have successfully initilized the IndexedDB. Notice how the callback function, cb(), is used.

Get

Notice that we have nested callback function.

We start with indexedDB.init(cb) at row 11. Then, if the databased was initlized, we call indexedDB.get(...). The second parameter is another callback function. I.e. this part:

At this point, the database might or might not exist. We need to check that.

I used a simple ternary operator to perfom this check.

Set

Let's explore single-worker.js. Please note that the single and multi web workers operates in the same way.

Before we post our structure, we save it - see line 5. Let's open save-structured.js. This snippet works like the last one. Notice how we use the callback function.

To clarify, we start by initlizing the indexedDB. Then we set (save) the structured data.

Last updated