DEV Community

jswalker.in
jswalker.in

Posted on

How to Read IndexedDB data with order?

Create Index on timestamp?

var version = 1;

// Access IndexedDB object everytime
function open_idb(obj,callback){
    var flag = 0;
    try {
        if (DBOpenRequest) {
            flag = 1;
        } else {
            flag = 0;
        }
    } catch (err) {
        flag = 0;
    }

    if (flag == 1) {

        //Use older DB object
        var db = DBOpenRequest.result;
        callback(db);
    } else {

        //Create New db object
        DBOpenRequest = indexedDB.open("test_db", version);
    }

    DBOpenRequest.onsuccess = function(event) {
        try {
            var db = DBOpenRequest.result;
            callback(db);
        } catch (err) {
            callback();
        }
    };

    //Set Index
    DBOpenRequest.onupgradeneeded = function(event) {

        var db = event.target.result;

        //This condition will always satisfy
        if(event.oldVersion<1){
          var object_store = db.createObjectStore('test',{keyPath: 'index'});
              object_store.createIndex("index", "index",{unique:false});
              object_store.createIndex("timestamp", "timestamp",{unique:false});
        }

        db.onerror = function(event) {
            console.log('Error loading database.');
        };
    };
};

Executive Function

function push_test_data(obj,callback){
    var index=obj.index;
    var arr=obj.arr;
    var len = arr.length;
    var db=obj.db;



    if(index<len){

        var transaction = db.transaction(['test'], 'readwrite');
        var object_store = transaction.objectStore('test');
        var entry = {index:arr[index].index,timestamp:arr[index].timestamp};

        var request = object_store.put(entry);
            request.onsuccess=function(){
              index=index+1;
              push_test_data({index:index,arr:arr,db:db},callback);
            };

            request.onerror=function(e){
             console.log("Error ");
             console.log(e);
            };      
    }else{
      callback();
    }
};


function order_by(o_){

        var type=o_.type;
        var key=o_.key;


        open_idb({},function(db){

            var transaction = db.transaction(['test'], 'readwrite');
            var object_store = transaction.objectStore('test');
            var request = object_store.index(key).openCursor(null,type);

            var result = [];
            request.onsuccess = function(event) {
                var cursor = event.target.result;
                //console.log(cursor);
                if(cursor){
                    result.push(cursor.value);
                    cursor.continue();
                }else{
                 console.log(":"+type+":");
                 console.log(result);
                }
            };

            request.onerror = function(e) {
              console.log(e);
            };

        });

}

Initial Push Test Data

open_idb({},function(db){
    var arr=[{index:1,timestamp:Date.now()+1},{index:2,timestamp:Date.now()+2}];
    push_test_data({arr:arr,index:0,db:db},function(){

    });

});

Ascending Order


open_idb({},function(db){
   order_by({key:"timestamp",type:"next"});  // For ascending order by timestamp
});

Descending Order


open_idb({},function(db){
   order_by({key:"timestamp",type:"prev"});  // For descending order by timestamp
});

Top comments (0)