Get all data from a table in a JSON - Indexeddb

3

Hello! I need to get all data from a table in a JSON. (Using the Indexeddb database). How to proceed?

    
asked by anonymous 29.06.2016 / 15:04

1 answer

0

Follow the Steps

1 - Step: read the Mozilla website

2 - Step: Create the indexedDB database

var cidades = [
{
  "cidade":"cidadeum",
  "latitude":-25.2985296,
  "longitude":-57.6710677
},
{
  "cidade":"cidadedois",
  "latitude":-25.465034,
  "longitude":-56.0183859
},
{
  "cidade":"cidadetres",
  "latitude":-25.4933441,
  "longitude":-54.6710438
},
 {
  "cidade":"cidadequatro",
  "latitude":-24.1586759,
  "longitude":-56.636503
},
 {
  "cidade":"cidadecinco",
  "latitude":-22.5450875,
  "longitude":-55.7618963
}
];

var IDBSetting = {
    name: "indexedDBName",
    version: 1,
    tables: [{
        tableName: "cidades",
        keyPath: "seq",
        autoIncrement: true,
        index: ["cidade", "latitude", "longitude"],
        unique: [false, false, false]
    }]
};

! function() {
    console.log("indexeDB init");

    var req = indexedDB.open(IDBSetting.name, IDBSetting.version);

    req.onsuccess = function(event) {
        console.log("indexedDB open success");
    };

    req.onerror = function(event) {
        console.log("indexed DB open fail");
    };

    //callback run init or versionUp
    req.onupgradeneeded = function(event) {
        console.log("init onupgradeneeded indexedDB ");
        var db = event.target.result;

        for (var i in IDBSetting.tables) {
            var OS = db.createObjectStore(IDBSetting.tables[i].tableName, {
                keyPath: IDBSetting.tables[i].keyPath,
                autoIncrement: IDBSetting.tables[i].autoIncrement
            });

            for (var j in IDBSetting.tables[i].index) {
                OS.createIndex(IDBSetting.tables[i].index[j], IDBSetting.tables[i].index[j], {
                    unique: IDBSetting.tables[i].unique[j]
                });
            }
        }
    }
}();

3 - Step: addData - Adding the data

var IDBFuncSet = {
    //write
    addData: function(table, data) {
        var req = indexedDB.open(IDBSetting.name, IDBSetting.version);

        req.onsuccess = function(event) {
            try {
                console.log("addData indexedDB open success");
                var db = req.result;
                var transaction = db.transaction([table], "readwrite");
                var objectStore = transaction.objectStore(table);
                var objectStoreRequest = objectStore.add(data);
            } catch (e) {
                console.log("addDataFunction table or data null error");
                console.log(e);
            }

            objectStoreRequest.onsuccess = function(event) {
                //console.log("Call data Insert success");
            }
            objectStoreRequest.onerror = function(event) {
                console.log("addData error");
            }
        };

        req.onerror = function(event) {
            console.log("addData indexed DB open fail");
        };
    }
}

for(var i in cidades){
   IDBFuncSet.addData("cidades",cidades[i]);
}

4 - Step: getAllData - Returning all data

IDBFuncSet.getAllData = function(arr, table) {
    try {
        var req = indexedDB.open(IDBSetting.name, IDBSetting.version);

        req.onsuccess = function(event) {
            var db = req.result;
            var transaction = db.transaction([table], "readonly");
            var objectStore = transaction.objectStore(table);

            var objectStoreRequest = objectStore.openCursor();

            objectStoreRequest.onsuccess = function(event) {
                var cursor = event.target.result;
                if (cursor) {
                    arr.push(cursor.value);
                    cursor.continue();
                } else {

                }
            }
        };
        req.onerror = function(event) {
            console.log("getAllData indexed DB open fail");
        };
    } catch (e) {
        console.log(e);
    }
}
var cidadesArr = [];
IDBFuncSet.getAllData(cidadesArr, "cidades");

console.log(cidadesArr);

Another Tutorial

Retrieve all data

If you want to get all the data instead of an object store, then you may need to use a cursor. Here is another function that makes use of cursor to retrieve all data from the object store:

function readAll() {
        var objectStore = db.transaction("customers").objectStore("customers");

        objectStore.openCursor().onsuccess = function(event) {
          var cursor = event.target.result;
          if (cursor) {
                alert("Name for id " + cursor.key + " is " + cursor.value.name + ", Age: " + cursor.value.age + ", Email: " + cursor.value.email);
                cursor.continue();
          }
          else {
                alert("Não há mais entradas!");
          }
        };     
}

As you can see, we've implemented the openCursor () method to accomplish the goal. OpenCursor () is used to iterate over multiple records in a database. It can accept several parameters, such as limiting the scale items, the direction we want to do iteration and so on. In this case, we leave no parameters.

The cursor object itself is the result of the request. We have implemented the continue () function to continue with the next iteration in the circuit. When the loop comes to an end, then we get the alert with the content "There are no more entries!".

See the demo: link

Source: link

There is also a lib that you can implement with indexedDB :

link

I hope I have helped.

    
10.08.2016 / 04:19