Sunday, 18 June 2017

Data Persistence in Browser with JavaScript Part-1



IndexedDB:

Unlike SQL databases that use columns to represent different attributes of schema IndexedDB uses JavaScript objects to represent data. Also indexedDB is very fast due to the indexing feature. The indexing feature allows developers to do high performance searches where the objects are indexed with a key. More over it has asynchronous APIs and is able to store much larger data compared to 'Web Storage'. The storage limit is calculated at 50% of the available memory on the hard drive. So in the case if the available memory on the hard drive is 100 GB then the limit for indexedDB would be 50 GB.

Opening an IndexedDB database:

var request = window.indexedDB.open("test-database", 1);Arial

The 'window.indexedDB.open("test-database", 1)' function call opens a database with its name set to 'test-database' and version number to '1'. This means that the schema structure will be specific to the version number and if the schema structure needs to be updated then version number will also be updated.

The code below shows sample usage for indexedDB:

let indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;

var dbOpen = indexedDB.open("SampleDataBase", 1);

dbOpen.onupgradeneeded = function() {
    var db = dbOpen.result;
    var store = db.createObjectStore("SampleObjectStore", {keyPath: "id"});
    var index = store.createIndex("NameIndex", ["name.last", "name.first"]);
};

dbOpen.onsuccess = function() {

    var db = dbOpen.result;
    var transaction = db.transaction("SampleObjectStore", "readwrite");
    var store = transaction.objectStore("SampleObjectStore");
    var index = store.index("NameIndex");

    // add data
    store.put({id: 1000, name: {first: "Edward", last: "Jones"}});
    store.put({id: 1, name: {first: "John", last: "Hancock"}});
    
    // query
    var getUser1 = store.get(1000);
    var getUser2 = index.get(["Hancock", "John"]);

    getUser1.onsuccess = function() {
        console.log(getUser1.result.name.last);  // Jones
    };

    getUser2.onsuccess = function() {
        console.log(getUser2.result.name.last);   // Hancock
    };

    // close db when transaction is done
    transaction.oncomplete = function() {
        db.close();
    };
}

No comments:

Post a Comment