Skip to content

What is indexed pdb?

prasenjeet-symon edited this page Sep 9, 2020 · 1 revision

indexed-PDB is a lightweight promised based wrapper around the indexedDB.

As we already know that indexedDB is an event-driven system. Everything in indexedDB is an event that makes it very difficult to work with as well as very difficult to write production-ready code using native indexedDB because the event-driven system is very error-prone.

On the other side, indexed-PDB makes it very easy to use the indexedDB as it wraps the native code to promise. Which makes it very easy to use and understand and also ready to use in the larger codebase.


Comparing the code of indexedDB and indexed-PDB

Below is the indexedDB code of reading all rows from the objectStore using the cursor.

var db;
var request = indexedDB.open("MyTestDatabase");

request.onerror = function (event) {
    console.log("Why didn't you allow my web app to use IndexedDB?!");
};

request.onsuccess = function (event) {
    db = event.target.result;
    // Handling Errors
    db.onerror = function (event) {
        // Generic error handler for all errors targeted at this database's
        // requests!
        console.error("Database error: " + event.target.errorCode);
    };

    // open the transaction
    var transaction = db.transaction(["customers"], "readwrite");
    // Do something when all the data is added to the database.
    transaction.oncomplete = function (event) {
        console.log("All done!");
    };

    transaction.onerror = function (event) {
        // Don't forget to handle errors!
    };

    var objectStore = transaction.objectStore("customers");

    var customers = [];

    objectStore.openCursor().onsuccess = function (event) {
        var cursor = event.target.result;
        if (cursor) {
            customers.push(cursor.value);
            cursor.continue();
        }
        else {
            console.log("Got all customers: " + customers);
        }
    };
};

And below is the indexed-PDB code of reading all rows from the objectStore using the cursor.

import { openDB } from 'indexed-pdb'

(async () => {
    try {
        const db = await openDB('MyTestDatabase')
        var objectStore = db.transaction(["customers"], "readwrite").objectStore("customers");
        var customers = [];

        await objectStore.openCursor().then(function push_item(cursor) {
            if (!cursor) {
                return
            }
            customers.push(cursor.value)
            return cursor.continue().then(push_item)
        })

        console.log("Got all customers: " + customers);
        
    } catch (error) {
        console.log(error, 'any error during the process');
    }

})()

As you can see indexed-PDB is easy to understand and also there are very few lines of code.

Clone this wiki locally