I have got a SET function which sets the object into IndexedDB with particular key:
_that.set = function(data, key) {
var transaction = _db.transaction([_tblName], "readwrite"),
store = transaction.objectStore(_tblName),
request = store.add(data, key);
request.onerror = function(e) {
console.log("Error", e.target.error.name);
};
request.onsuccess = function(e) {
console.log("Added to db successfully.");
};
};
I have got an UPDATE function which updates the object in IndexedDB with particular key:
_that.update = function(data, key) {
var transaction = _db.transaction([_tblName], "readwrite"),
store = transaction.objectStore(_tblName),
request = store.put(data, key);
request.onerror = function(e) {
console.log("Error", e.target.error.name);
};
request.onsuccess = function(e) {
console.log("Object been updated", key);
};
};
and I have got GET function:
_that.get = function(key, callback) {
if (key === "" || isNaN(key)) {
return;
}
var transaction = _db.transaction([_tblName], "readonly"),
store = transaction.objectStore(_tblName),
request = store.get(key);
request.onsuccess = function(e) {
var res = e.target.result;
callback(key, res);
};
};
I want to create SETORUPDATE function for IndexedDB which will work as SET function, and in case onerror event will call GET function, update data and then call UPDATE function. The error is ConstraintError, which means the object with the respective key already exists in the database. Is there a way to avoid this error comingup in the console, but trigger GET and UPDATE instead? NOTE: Variables with the underscore signs in front are instance variables declared on the top the Class and initialized in the constructor.
UPDATE: I need to change the value of data variable before updating it with the same key only in case the key with some object already exists in the table. That is why it is important to check whether the same key already exists before update. I want something like this:
_that.setOrUpdate = function(data, key) {
var transaction = _db.transaction([_tblName], "readwrite"),
store = transaction.objectStore(_tblName),
request = store.add(data, key);
request.onsuccess = function(e) {
console.log("Added to db successfully.");
};
request.onerror = function(e) {
_that.get(key);
// make some changes to the data
_that.update(data, key);
};
};