generic async callback function - javascript

this.init = function (onupgradeneeded, onsuccess) {
var openRequest = indexedDB.open(dbName);
openRequest.onupgradeneeded = function (e) {
db = e.target.result;
if (!db.objectStoreNames.contains(objectStoreName)) {
console.log('Creating the ' + objectStoreName + ' objectstore');
db.createObjectStore(objectStoreName, { keyPath: "id", autoIncrement: true });
}
};
openRequest.onsuccess = function (e) {
db = e.target.result;
db.onerror = function (event) {
// Generic error handler for all errors targeted at this database requests
console.log("Database error: " + event.target.errorCode);
};
};
};
Called by:
var idb = new Demo.IndexedDB();
idb.init();
When the init function runs, it will either end up in openRequest.onupgradeneeded or openRequest.onsuccess.
What i would like to know is if its possible to create a generic callback function that gets called in both function. So regardless of which of the two functions that runs i can know when theyre done by using
idb.init(function(){
//onupgradeneeded or onsuccess completed
});
Hope you get the idea, otherwise ill elaborate.
Thanks

Just pass in one callback function and call that one single callback in both cases:
this.init = function (onFinish) {
var openRequest = indexedDB.open(dbName);
openRequest.onupgradeneeded = function (e) {
db = e.target.result;
if (!db.objectStoreNames.contains(objectStoreName)) {
console.log('Creating the ' + objectStoreName + ' objectstore');
db.createObjectStore(objectStoreName, { keyPath: "id", autoIncrement: true });
}
onFinish();
};
openRequest.onsuccess = function (e) {
db = e.target.result;
db.onerror = function (event) {
// Generic error handler for all errors targeted at this database requests
console.log("Database error: " + event.target.errorCode);
};
onFinish();
};
};

Related

How to read object written through cordova file plugin?

I read on Cordova's documentation for android platform a code snipped and tried to use it for writing a JS object on a text file. The object gets successfully written but when I read it with FileReader API I can't get output as expected.
function writeFile(fileEntry, dataObj, isAppend) {
// Create a FileWriter object for our FileEntry (log.txt).
fileEntry.createWriter(function (fileWriter) {
fileWriter.onwriteend = function() {
console.log("Successful file read...");
readFile(fileEntry);
};
fileWriter.onerror = function (e) {
console.log("Failed file read: " + e.toString());
};
// If we are appending data to file, go to the end of the file.
if (isAppend) {
try {
fileWriter.seek(fileWriter.length);
}
catch (e) {
console.log("file doesn't exist!");
}
}
fileWriter.write(dataObj);
});
}
function readFile(fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function() {
console.log("Successful file read: " + this.result);
//displayFileData(fileEntry.fullPath + ": " + this.result);
};
reader.onload = function(){
k=reader.readAsText(file);
};
reader.readAsText(file);
},onErrorLoadFs );
}
Format of object I want to read :
function sub(name,absent,present){
this.name=name;
this.absent=absent;
this.present=present;
}
var S = new sub('Physics',1,3);
var k= new sub();
What exactly I want to do :
I am writing an object S on the file which appears like this when opened
{"name":"Physics","absent":1, "present" : 3}
Now after reading the file (which in my case is filetoAppend.txt) I want to assign these values to another object k so that when I run k.name, Physics is shown as output.
console output
k
"{"name":"Physics","absent":1,"present":3}"
k.name
undefined
With the Cordova File Plugin, there are two essential pieces of information to remember:
1.Like all Cordova plugins, you have to wait for the deviceready event before you try anything,
2.Then, Use window.resolveLocalFileSystemURL(<path>, <successHandler>, <errorHandler>)
window.resolveLocalFileSystemURL() returns a FileEntry or DirectoryEntry instance (depending on whether you gave a file or a directory as path as its first parameter), which you can then work with.
WRITING TO A FILE
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady() {
function writeToFile(fileName, data) {
data = JSON.stringify(data, null, '\t');
window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function (directoryEntry) {
directoryEntry.getFile(fileName, { create: true }, function (fileEntry) {
fileEntry.createWriter(function (fileWriter) {
fileWriter.onwriteend = function (e) {
// for real-world usage, you might consider passing a success callback
console.log('Write of file "' + fileName + '"" completed.');
};
fileWriter.onerror = function (e) {
// you could hook this up with our global error handler, or pass in an error callback
console.log('Write failed: ' + e.toString());
};
var blob = new Blob([data], { type: 'text/plain' });
fileWriter.write(blob);
}, errorHandler.bind(null, fileName));
}, errorHandler.bind(null, fileName));
}, errorHandler.bind(null, fileName));
}
writeToFile('example.json', { foo: 'bar' });
}
WRITING FROM FILE
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady() {
function readFromFile(fileName, cb) {
var pathToFile = cordova.file.dataDirectory + fileName;
window.resolveLocalFileSystemURL(pathToFile, function (fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function (e) {
cb(JSON.parse(this.result));
};
reader.readAsText(file);
}, errorHandler.bind(null, fileName));
}, errorHandler.bind(null, fileName));
}
var fileData;
readFromFile('data.json', function (data) {
fileData = data;
});
}
cb is the callback function that you need to pass when calling this function
For full reference use:https://www.neontribe.co.uk/cordova-file-plugin-examples/
Updated based on your updated Question
In reader.onloadend you can get the result of the file and assign to your output object k or can call callback function incase.
reader.onloadend = function (e) {
//cb(JSON.parse(this.result));
var k=JSON.parse(this.result);
console.log(k.name + ", " + k.absent+ ", " + k.present);
};
var k = JSON.parse('{"name":"Physics","absent":1, "present" : 3}');
console.log(k.name + ", " + k.absent + ", " + k.present);

IndexedDB open DB request weird behavior

I have an app (questionnaire) that uses indexedDB.
We have one database and several stores in it.
Stores have data already stored in them.
At some point a dashboard html file is loaded. In this file I am calling couple of functions:
function init(){
adjustUsedScreenHeight();
db_init();
setInstitutionInstRow();
loadRecommendations();
loadResultsFromDB();
fillEvaluations();
document.addEventListener("deviceready", onDeviceReady, function(e) {console.log(e);});
}
The init() function is called on body onLoad.
setInstitutionInstRow() looks like these:
function setInstitutionInstRow(localId){
//localId = 10;
if (localId == undefined){
console.log("Localid underfined: ");
//open db, open objectstore;
var request = indexedDB.open("kcapp_db", "1.0");
request.onsuccess = function() {
var db = request.result;
var tx = db.transaction ("LOCALINSTITUTIONS", "readonly");
var store = tx.objectStore("LOCALINSTITUTIONS");
tx.oncomplete = function(){
db.close();
}
tx.onerror = function(){
console.log("Transaction error on setInstInstRow");
}
var cursor = store.openCursor();
cursor.onsuccess= function () {
var match = cursor.result;
console.log ("Retrieved item: " + match.value.instid);
// alert("Added new data");
if (match){
setInstituionInstRow(match.value.instid);
console.log("Got localid: " + math.value.instid);
}
else
console.log("localinsid: it is empty " );
};
cursor.onerror = function () {
console.log("Error: " + item.result.errorCode);
}
}
request.onerror = function () {
console.log("Error: " + request.result.errorCode );
}
request.oncomplete = function (){
console.log("The transaction is done: setInstitutionRow()");
}
request.onupgradeneeded = function (){
console.log("Upgrade needed ...");
}
request.onblocked = function(){
console.log("DB is Blocked ...");
}
} else {
instid = localId;
var now = new Date();
//console.log("["+now.getTime()+"]setInstituionInstRow - instid set to "+localId);
//open db, open objectstore;
var request = indexedDB.open("kcapp_db", "1.0");
request.onsuccess = function() {
var db = this.result;
var tx = db.transaction ("INSTITUTIONS", "readonly");
var store = tx.objectStore("INSTITUTIONS");
var item = store.get(localId);
console.log(item);
item.onsuccess= function () {
console.log ("Retrieved item: ");
if (item.length > 0)
var lInstitution = item.result.value;
kitaDisplayValue = lInstitution.krippe;
};
item.onerror = function () {
console.log("Error: " + item.result.errorCode);
}
}
request.onerror = function () {
console.log("Error: " + request.result.errorCode );
}
}
Now the problem is,
var request = indexedDB.open("kcapp_db", "1.0");
the above request is never getting into any onsuccess, oncomplete, onerror states. I debugged with Chrome tools, it never getting into any above states.
Accordingly I am not getting any data from transactions.
And there are no errors in Chrome console.
And here is the request value from Chrome dev:
From above image the readyState: done , which means it should fire an event (success, error, blocked etc). But it is not going into any of them.
I am looking into it, and still can not figure out why it is not working.
Have to mention that the other functions from init() is behaving the same way.
Looking forward to get some help.
You may be using an invalid version parameter to the open function. Try indexedDB.open('kcapp_db', 1); instead.
Like Josh said, your version parameter should be an integer, not a string.
Your request object can get 4 events in response to the open request: success, error, upgradeneeded, or blocked. Add event listeners for all of those (e.g. request.onblocked = ...) and see which one is getting fired.
I had that problem but only with the "onupgradeneeded" event. I fixed it changing the name of the "open" function. At the begining I had a very long name; I changed it for a short one and start working. I don't know if this is the real problem but it was solved at that moment.
My code:
if (this.isSupported) {
this.openRequest = indexedDB.open("OrdenesMant", 1);
/**
* Creación de la base de datos con tablas y claves primarias
*/
this.openRequest.onupgradeneeded = function(oEvent) {
...
Hope it works for you as well.

How to add initial data in indexeddb only once

I am creating an indexeddb, and have several stores in it.
Have some data that has to be initially added when stores are created.
I have function where I create database and stores:
function db_init(){
var request = indexedDB.open("db", "1.0");
request.onupgradeneeded = function(){
var db = request.result;
//store 1
db.createObjectStore("store1", {keypath: "id", autoIncrement: true});
//add initial datas;
//store2
db.createObjectStore("store2", {keypath: "id", autoIncrement: true});
//...
//store 3
// init necessary databases
db_populate();
}
request.onsuccess = function (){
db = request.result;
populate:db();
}
}
And inside db_populate function have 4 other functions where I am populating datastores:
function db_populate() {
init_store1();
init_store2();
//...
console.log("db populated with data");
}
Each init_score populates stores with transactions like below:
var tx = db.transaction("store1", "readwrite");
var store = tx.objectStore("store1");
Now, I have a problem. Every time I open or refresh the page, the initial data are duplicated. There are added over again.
When I add db_populate at the end of onupgradeneeded function, I get an error:
Uncaught TypeError: Cannot read property 'transaction' of undefined
on line:
var tx = db.transaction ("store1", "readwrite");
What I am trying to achieve is to create data stores with its initial data once and that is it.
Any idea what I am doing wrong?
Thanks in advance.
That's due to the fact that you can't insert data during a upgrade needed event. What you need to do instead is close the connection after the upgrade and reopen it again for the data insert.
The flow should be something like this:
function db_init() {
var request = indexedDB.open("db");
var dbShouldInit = false;
request.onupgradeneeded = function(e) {
var db = e.target.result;
dbShouldInit = true;
//store 1
db.createObjectStore("store1", {
keypath: "id",
autoIncrement: true
});
//add initial datas;
//store2
db.createObjectStore("store2", {
keypath: "id",
autoIncrement: true
});
}
request.onsuccess = function(e) {
e.target.result.close();
if(dbShouldInit)//executes only if DB init happened
db_populate(); //close the db first and then call init
}
}
function db_populate() {
init_store1(init_store2); //pass init 2 as callback
}
function init_store1(callback) {
var request = indexedDB.open("db");
request.onsuccess = function(e) {
var db = e.target.result;
var tx = db.transaction("store1", "readwrite");
var store = tx.objectStore("store1");
//init code here
tx.oncomplete = function(e) {
callback(); //here call the init for second function
};
}
}
function init_store2() {
var request = indexedDB.open("db");
request.onsuccess = function(e) {
var db = e.target.result;
var tx = db.transaction("store2", "readwrite");
var store = tx.objectStore("store2");
//init code here
tx.oncomplete = function(e) {
//here the app can continue
};
}
}
(function () {
//indexedDB.deleteDatabase("store");
var openDB = indexedDB.open("store", 1);
openDB.onupgradeneeded = function () {
var db = openDB.result;
var store;
if (!db.objectStoreNames.contains("example")) {
store = db.createObjectStore("example", {keyPath: "some"});
store.put({some: "initData"});
}
};
openDB.onsuccess = function (e) {
var db = e.target.result;
var rqst = db.transaction("example", "readonly")
.objectStore("example")
.get("initData");
rqst.onsuccess = function (e) {
console.log(rqst.result);
};
};
})();

indexedDB openCursor transaction onsuccess returns empty array

req = db.openCursor();
req.customerData=new Array() //[{a:1}]
req.onsuccess = function(e) {
var cursor = e.currentTarget.result;
if (cursor) {
//console.log(cursor.value);
e.currentTarget.customerData.push(cursor.value);
e.currentTarget.customerData.push("hello?");
cursor.continue()
}
else {
console.log(e.currentTarget.customerData) //this always correct
}
}
console.log(req.customerData); //outside the onsuccess everything is gone?
console.log(req);
I can see customerData when I open the object in the chrome console
console.log(req.customerData);
But when I do the above it is empty?
replacing new Array() with [{a:1}]
console.log(req.customerData);
I can see a and also the other objects
but then agian
console.log(req.customerData[0].a);
works and the other objects are gone.
How can I save customerData? I tried just pushing numbers or text but same thing after transaction is done. I can't get the data out only display it on console.log() during the transaction?
I know it must be something past by reference but every variable I trow in dissapears?
Added full example below just type write() and read() in console
<script>
var iDB
ready=function(){
var request = indexedDB.open("my-database",1);
request.onupgradeneeded = function(e) {
var db = e.currentTarget.result
var store = db.createObjectStore("store", {keyPath: "muts", autoIncrement:false})
//store.createIndex("by_submit", "submit", {unique: false})
console.log('db upgrade', 'v'+db.version)
}
request.onerror = function(e) {
//var db = e.currentTarget.result;
//db.close()
console.error('db error ',e)
}
request.onsuccess = function(e) {
var db = e.currentTarget.result
db.onversionchange = function(e) {
db.close()
console.log('db changed', 'v'+db.version, 'CLOSED')
}
console.log('db setup', 'v'+db.version, 'OK')
}
iDB=request
}
drop=function(){
iDB.result.close()
var req = indexedDB.deleteDatabase(this.iDB.result.name);
req.onsuccess = function() {console.log("Deleted database successfully")}
req.onerror = function() {console.log("Couldn't delete database")}
req.onblocked = function() {console.log("Couldn't delete database due to the operation being blocked")}
}
read=function(){
var db=iDB
.result
.transaction(["store"], "readwrite").objectStore("store");
var req = db.openCursor();
req.iData=new Array();
req.onsuccess = function(e) {
var cursor = e.currentTarget.result;
if (cursor) {
e.currentTarget.iData.push(cursor.value);
e.currentTarget.iData.push("hello");
cursor.continue()
}
else {
console.log(e.currentTarget.iData)
}
}
console.log(req.iData)
}
write=function(){
var db=document.querySelector('my\-database')
.iDB
.result
.transaction(["store"], "readwrite").objectStore("store");
var customerData = [
{muts: "Bill", qty: "1"},
{muts: "Donna", qty: "1"}
]
for (var i in customerData){db.put(customerData[i])}
}
ready()
</script>
A few things
I recommend not setting custom properties of an IDBRequest object. Create and access objects that are in an outer scope instead.
There is no need to use event.currentTarget. event.target is sufficient (and so is 'this', and so is the request object itself).
onversionchange is deprecated.
Due to the asynchronous nature of indexedDB, you may be trying to print something out to the console that does not yet exist, or no longer exists. Instead, try printing something out when the transaction completes.
For example:
function populateArray(openDatabaseHandle, onCompleteCallbackFunction) {
var transaction = openDatabaseHandle.transaction('store');
var store = transaction.objectStore('store');
var myArray = [];
var request = store.openCursor();
request.onsuccess = function() {
var cursor = this.result;
if(!cursor) return;
myArray.push(cursor.value);
cursor.continue();
};
transaction.oncomplete = function() {
onCompleteCallbackFunction(myArray);
};
}
// An example of calling the above function
var conn = indexedDB.open(...);
conn.onsuccess = function() {
populateArray(this.result, onPopulated);
};
// An example of a callback function that can be passed to
// the populateArray function above
function onPopulated(data) {
console.debug(data);
data.forEach(function(obj) {
console.debug('Object: %o', obj);
});
}

how to pass callback to onerror method globally?

i have a piece of code for IndexedDB
GetObj = function(storeName, key, callback){
var db = indexedDB.db;
if(db){
var transaction = db.transaction([storeName], transactionType.READ_ONLY);
var obj = undefined;
transaction.oncomplete = function(event) {
if(callback){
callback(obj);
}
};
var objectStore = transaction.objectStore(storeName);
var request = objectStore.get(key);
request.onerror = function (e){
console.log("onError: in", e);
if (callback) {
callback(-1);//error
}
}
request.onsuccess = function(event) {
obj = request.result;
};
}
}
I would like to define the request.onerror function globally so that i can reuse that function for all onerror (instead of copy pasting it all over the place). problem is howto pass callback?
Just define it in a higher scope:
var onerrorHandler = function (e, callback){
console.log("onError: in", e);
if (callback) {
callback(-1);//error
}
};
And then use that for the callback:
... snip
var request = objectStore.get(key);
request.onerror = function (e) {
onerrorHandler(e, callback);
};
... snip
I will rather avoid global error handler.
As you see, the code is not really reduce, but expended to include another wrapper function. In doing so, the error stack trace is not telling which request is causing error.

Categories

Resources