How can I access data from loaded from an IndexedDB objectStore? - javascript

Here is my code I want to return getConn.result and use it in my js page. Could you help me?
function readObjectStore(storeName) {
// Open (or create) the database
var open = indexedDB.open("Publisher", 1);
open.onupgradeneeded = function () {}
open.onsuccess = function () {
var db = open.result;
var tx = db.transaction(storeName, "readwrite");
var store = tx.objectStore(storeName);
if (storeName == "connectionStrings") {
var getConn = store.getAll();
getConn.onsuccess = function () {
return getConn.result;
}
}
}
}

Related

Updating the query data in cloud firestore nested map fields

I'm trying to update the data in nested map fields in firestore, my form is a window form that has 4 sides (wSide1,wSide2,wSide3,wSide4), what my form is doing is if customer select 1 field which is wSide1 and it needs to be updated then only this field only be updated but in my case it is updating all 4 sides, the one which is selected for example side 1 only that has the correct updated values other 3 sides updates with the false values. as my form is dynamic it only shows the field which is selected.
I only want to update the field which is selected, all other has to be null.
js & firestore query
function updateWindowForm(form, type){
var name = $('#name_'+type).val();
var type = $('#type_'+type).val();
const taskformWindow = document.getElementById("taskformWindow");
let editStatus = false;
let id = '';
const updateTask = (id, updatedTask) => db.collection('Buildings').doc(buildingID).collection('rooms').doc(roomID).collection('objects').doc(objectID).update(updatedTask);
window.addEventListener("DOMContentLoaded", async (e) => {
id = doc.id;
editStatus = true;
btnsEdit.forEach((btn) => {
btn.addEventListener("click", async (e) => {
try {
const doc = await getTask(e.target.dataset.id);
const task = doc.data();
editStatus = true;
id = doc.id;
taskformWindow["btn-update-data"].innerText = "Update";
} catch (error) {
console.log(error);
}
});
});
});
taskformWindow.addEventListener("click", async (e) => {
e.preventDefault();
var name_Window = document.getElementById('name_Window').value;
var wAluminium = document.getElementById('wAluminium').checked;
var wColorMeasurement = document.getElementById('wColorMeasurement').value;
var wComments = document.getElementById('wComments').value;
var wForEnd1 = document.getElementById('wForEnd1').checked;
var wForEnd2 = document.getElementById('wForEnd2').checked;
var wSideOfWindows = document.getElementById('wSideOfWindows').value;
var wHardwareManufacturer = document.getElementById('wHardwareManufacturer').value;
var wPlastic = document.getElementById('wPlastic').checked;
//Side 1
var wAxis1_1 = document.getElementById('wAxis1_1').checked;
var wAxis1_2 = document.getElementById('wAxis1_2').checked;
var wBackSet1 = document.getElementById('wBackSet1').value;
var wDirectionLR1_1 = document.getElementById('wDirectionLR1_1').checked;
var wDirectionLR1_2 = document.getElementById('wDirectionLR1_2').checked;
var wHandleHeight1 = document.getElementById('wHandleHeight1').value;
var wOverlapWidth1 = document.getElementById('wOverlapWidth1').value;
var wSashRebateHeight1 = document.getElementById('wSashRebateHeight1').value;
var wSashRebateWidth1 = document.getElementById('wSashRebateWidth1').value;
//Side 2
var wAxis2_1 = document.getElementById('wAxis2_1').checked;
var wAxis2_2 = document.getElementById('wAxis2_2').checked;
var wBackSet2 = document.getElementById('wBackSet2').value;
var wDirectionLR2_1 = document.getElementById('wDirectionLR2_1').checked;
var wDirectionLR2_2 = document.getElementById('wDirectionLR2_2').checked;
var wHandleHeight2 = document.getElementById('wHandleHeight2').value;
var wOverlapWidth2 = document.getElementById('wOverlapWidth2').value;
var wSashRebateHeight2 = document.getElementById('wSashRebateHeight2').value;
var wSashRebateWidth2 = document.getElementById('wSashRebateWidth2').value;
//Side 3
var wAxis3_1 = document.getElementById('wAxis3_1').checked;
var wAxis3_2 = document.getElementById('wAxis3_2').checked;
var wBackSet3 = document.getElementById('wBackSet3').value;
var wDirectionLR3_1 = document.getElementById('wDirectionLR3_1').checked;
var wDirectionLR3_2 = document.getElementById('wDirectionLR3_2').checked;
var wHandleHeight3 = document.getElementById('wHandleHeight3').value;
var wOverlapWidth3 = document.getElementById('wOverlapWidth3').value;
var wSashRebateHeight3 = document.getElementById('wSashRebateHeight3').value;
var wSashRebateWidth3 = document.getElementById('wSashRebateWidth3').value;
//Side 4
var wAxis4_1 = document.getElementById('wAxis4_1').checked;
var wAxis4_2 = document.getElementById('wAxis4_2').checked;
var wBackSet4 = document.getElementById('wBackSet4').value;
var wDirectionLR4_1 = document.getElementById('wDirectionLR4_1').checked;
var wDirectionLR4_2 = document.getElementById('wDirectionLR4_2').checked;
var wHandleHeight4 = document.getElementById('wHandleHeight4').value;
var wOverlapWidth4 = document.getElementById('wOverlapWidth4').value;
var wSashRebateHeight4 = document.getElementById('wSashRebateHeight4').value;
var wSashRebateWidth4 = document.getElementById('wSashRebateWidth4').value;
try {
if (!editStatus) {
await updateTask(id, {
name:name_Window,
Form:{
wAluminium: wAluminium,
wColorMeasurement: wColorMeasurement,
wComments: wComments,
wForEnd1: wForEnd1,
wForEnd2: wForEnd2,
wHardwareManufacturer: wHardwareManufacturer,
wPlastic: wPlastic,
wSide1:{
wAxis1_1: wAxis1_1,
wAxis1_2: wAxis1_2,
wBackSet1: wBackSet1,
wDirectionLR1_1: wDirectionLR1_1,
wDirectionLR1_2: wDirectionLR1_2,
wHandleHeight1: wHandleHeight1,
wOverlapWidth1: wOverlapWidth1,
wSashRebateHeight1: wSashRebateHeight1,
wSashRebateWidth1: wSashRebateWidth1,
},
wSide2:{
wAxis2_1: wAxis2_1,
wAxis2_2: wAxis2_2,
wBackSet1: wBackSet2,
wDirectionLR2_1: wDirectionLR2_1,
wDirectionLR2_2: wDirectionLR2_2,
wHandleHeight2: wHandleHeight2,
wOverlapWidth2: wOverlapWidth2,
wSashRebateHeight2: wSashRebateHeight2,
wSashRebateWidth2: wSashRebateWidth2,
},
wSide3:{
wAxis3_1: wAxis3_1,
wAxis3_2: wAxis3_2,
wBackSet1: wBackSet3,
wDirectionLR3_1: wDirectionLR3_1,
wDirectionLR3_2: wDirectionLR3_2,
wHandleHeight3: wHandleHeight3,
wOverlapWidth3: wOverlapWidth3,
wSashRebateHeight3: wSashRebateHeight3,
wSashRebateWidth3: wSashRebateWidth3,
},
wSide4:{
wAxis4_1: wAxis4_1,
wAxis4_2: wAxis4_2,
wBackSet4: wBackSet4,
wDirectionLR4_1: wDirectionLR4_1,
wDirectionLR4_2: wDirectionLR4_2,
wHandleHeight4: wHandleHeight4,
wOverlapWidth4: wOverlapWidth4,
wSashRebateHeight4: wSashRebateHeight4,
wSashRebateWidth4: wSashRebateWidth4,
},
wSideOfWindows: wSideOfWindows,
}
})
editStatus = false;
id = '';
taskformWindow['btn-update-window-data'].innerText = 'Daten aktualisiert';
swal("", "Daten wurden aktualisert!", "success");
}
taskformWindow.reset();
} catch (error) {
console.log(error);
}
});
}
I can't see the code you use for updating your data but I can ausme that you probably did not set the merge to true while saving the data.
Take a look at this code snipped:
var cityRef = db.collection('cities').doc('BJ');
var setWithMerge = cityRef.set({
capital: true
}, { merge: true });
By setting that we ensure to udate only the fields we want to and leave the rest as it is. Still make sure not to send fields with a null value because that is a valid value for firestore and it doesn't mean that those fields will by skipped in the update process. You can find more about it here.

Wait Callback and our result data to take another proccess out of this function

i have this class (product).
var Product = function () {
this.products = [];
this.priceFrom = null;
this.priceTo = null;
this.countDone = 0;
};
Product.prototype = {
constructor: Product,
getProductsByPriceRange: function (priceFrom, priceTo) {
var xhrUrl = "<?= base_url('market/products/xhr_product_price_range') ?>";
var xhrData = {price_from: priceFrom, price_to: priceTo};
var xhrType = "json";
var UtilsClass = new Utils();
UtilsClass.xhrConnection(xhrUrl, xhrData, xhrType, function (data) {
/* MY DATA IS HERE */
});
},
buildList:function (products) {
for (var i = 0; i < products.length; i++) {
var product = products[i];
console.log("product");
}
},
buildOne: function (product) {
}
};
/*....more classes */
And another piece of code (out of product class):
var fromPrice = data.from;
var toPrice = data.to;
var ProductClass = new Product();
var lastCountDone = ProductClass.countDone;
ProductClass.priceFrom = fromPrice;
ProductClass.priceTo = toPrice;
var myProducts = ProductClass.getProductsByPriceRange(ProductClass.priceFrom, ProductClass.priceTo);
My question is... can i wait callback of UtilsClass.xhrConnection (in first piece) and use generated data of callback in second piece of code (out of first piece).
Any ideas would be very valuable to me. Thank you!
var Product = function () {
this.products = [];
this.priceFrom = null;
this.priceTo = null;
this.countDone = 0;
};
Product.prototype = {
constructor: Product,
getProductsByPriceRange: function (priceFrom, priceTo) {
var xhrUrl = "<?= base_url('market/products/xhr_product_price_range') ?>";
var xhrData = {price_from: priceFrom, price_to: priceTo};
var xhrType = "json";
var UtilsClass = new Utils();
return new Promise(function(resolve, reject){
UtilsClass.xhrConnection(xhrUrl, xhrData, xhrType, function (data) {
/* MY DATA IS HERE */
resolve(data)
});
});
},
buildList:function (products) {
for (var i = 0; i < products.length; i++) {
var product = products[i];
console.log("product");
}
},
buildOne: function (product) {
}
};
While calling,
var fromPrice = data.from;
var toPrice = data.to;
var ProductClass = new Product();
var lastCountDone = ProductClass.countDone;
ProductClass.priceFrom = fromPrice;
ProductClass.priceTo = toPrice;
var myProducts = ProductClass.getProductsByPriceRange(ProductClass.priceFrom, ProductClass.priceTo).then(function(data){%your data will be available here%});

When using IndexedDB, how can I delete multiple records using an index that is not the key?

I have code to create an indexedDB here:
function create_db() {
var indexedDB = window.indexedDB || window.webkitIndexedDB || window.msIndexedDB;
var request = indexedDB.open(“photos”, 2);
request.onupgradeneeded = function(event) {
var db = event.target.result;
// Create photo db
var photo_store = db.createObjectStore("photos", {keyPath: "photo_id"});
var photo_id_index = photo_store.createIndex("by_photo_id", "photo_id", {unique: true});
var dest_id_index = photo_store.createIndex("by_destination_id", "destination_id");
console.log(“store created”);
};
request.onsuccess = function(event) {
console.log(“store opened”);
};
request.onerror = function(event) {
console.log("error: " + event);
};
}
My code to remove entries:
function remove_photos = function (destination_id, db) {
var transaction = db.transaction("photos", "readwrite");
var store = transaction.objectStore("photos");
var index = store.index("by_destination_id");
var request = index.openCursor(IDBKeyRange.only(destination_id));
request.onsuccess = function() {
var cursor = request.result;
if (cursor) {
cursor.delete();
cursor.continue();
}
};
}
How can I delete records using the by_destination_id index so that I can delete all records with a given destination_id, which is an integer?
Thanks for any help.
I found the solution to my issue, the IDBKeyRange.only function doesn't like integers it needs to be a string, so substituting this line in:
var request = index.openCursor(IDBKeyRange.only(destination_id.toString()));
Make the code work.

HTML5 IndexedDB - How to merge all records into one

My idea is download chunks a huge file from server.
Chunks stored into an IndexedDB.
After download all chunks, merge all records into one (as SQL SELECT * FROM XXX ...).
Save into disk "saveAs()" or create URL to IndexedDB...
(Or any idea?)
I do not know how to do step 2. and 3.
(Below is an example of storing 10,000 records in the DB and the expected output after step 2. should be SusanSusanSusanSusanSusan...)
if (transaction) {
transaction.oncomplete = function () {
}
transaction.onabort = function () {
writeToConsoleScreen("transaction aborted.");
localDatabase.db.close();
}
transaction.ontimeout = function () {
writeToConsoleScreen("transaction timeout.");
localDatabase.db.close();
}
var store = transaction.objectStore(osTableName);
if (store) {
var req;
var customer = {};
// create ten thousand records
for (var loop = 0; loop < 10000; loop++) {
customer = {};
customer.fname = 'Susan';
req = store.add(customer);
req.onsuccess = function (ev) {
}
req.onerror = function (ev) {
writeToConsoleScreen("Failed to add record." + " Error: " + ev.message);
}
}
}
}
<!DOCTYPE html>
<script>
var open = indexedDB.open('chunks-example');
open.onupgradeneeded = function() {
// Create schema if necessary
var db = open.result;
db.createObjectStore('chunks');
};
// 1. Chunks stored into an IndexedDB.
open.onsuccess = function() {
var db = open.result;
var tx = db.transaction('chunks', 'readwrite');
var store = tx.objectStore('chunks');
for (var i = 0; i < 10; ++i) {
// For realz, this would be via
// XMLHttpRequest.response and async.
var chunk = new Blob(['chunk ' + i + '\n'],
{type: 'application/octet-stream'});
store.put(chunk, i);
}
tx.oncomplete = function() { merge(db); };
};
// 2. After "download" all chunks, merge all records into one
function merge(db) {
var tx = db.transaction('chunks');
var store = tx.objectStore('chunks');
var chunks = [];
var request = store.openCursor();
request.onsuccess = function() {
var cursor = request.result;
if (cursor) {
chunks.push(cursor.value);
cursor.continue();
} else {
saveAs('myfile', new Blob(chunks,
{type: 'application/octet-stream'}));
}
};
}
// 3. Save into disk "saveAs()"
function saveAs(filename, blob) {
var a = document.documentElement.appendChild(document.createElement('a'));
a.href = URL.createObjectURL(blob);
a.download = filename;
a.click();
a.parentElement.remove(a);
}
</script>

Getting a "setVersion" is not a function error when using indexedDB

I tried to use following code to test the performance of IndexedDB.
The code is modified from http://www.html5rocks.com/en/tutorials/indexeddb/todo/ ,
It works well in chrome, but fails in Firefox 10, saying "db.setVersion is not a function".
I want to know how can I modify the code to make it work in firefox?
var count=0;
var MAX=10;
var times=3;
var allTime;
var stime;
var etime;
var html5rocks = {};
var indexedDB = window.indexedDB || window.webkitIndexedDB ||
window.mozIndexedDB;
if ('webkitIndexedDB' in window) {
window.IDBTransaction = window.webkitIDBTransaction;
window.IDBKeyRange = window.webkitIDBKeyRange;
}
html5rocks.indexedDB = {};
html5rocks.indexedDB.db = null;
html5rocks.indexedDB.onerror = function(e) {
//console.log(e);
alert("Why didn't you allow my web app to use IndexedDB?!");
};
html5rocks.indexedDB.open = function(type) {
var request = indexedDB.open("todos");
request.onsuccess = function(e) {
var v = "1.20";
html5rocks.indexedDB.db = e.target.result;
var db = html5rocks.indexedDB.db;
// We can only create Object stores in a setVersion transaction;
if (v!= db.version) {
var setVrequest = db.setVersion(v);
// onsuccess is the only place we can create Object Stores
setVrequest.onerror = html5rocks.indexedDB.onerror;
setVrequest.onsuccess = function(e) {
if(db.objectStoreNames.contains("todo")) {
db.deleteObjectStore("todo");
}
var store = db.createObjectStore("todo",
{keyPath: "number"});
addTest();
};
}
else addTest();
};
request.onerror = html5rocks.indexedDB.onerror;
}
html5rocks.indexedDB.addTodo = function(todoText,num) {
var db = html5rocks.indexedDB.db;
var trans = db.transaction(["todo"], IDBTransaction.READ_WRITE);
var store = trans.objectStore("todo");
var data = {
"text": todoText,
"number": num
};
var request = store.put(data);
request.onsuccess = function(e) {
count++;
if(count>=times*MAX)
{
etime=new Date;
var t=document.getElementById('result').innerHTML;
document.getElementById('result').innerHTML=t+((etime.valueOf()-stime.valueOf())/times)+"<br/>";
allTime=0;stime=new Date;count=0;
getTest();
}
};
request.onerror = function(e) {
console.log("Error Adding: ", e);
};
};
html5rocks.indexedDB.getTodo = function(id) {
var db = html5rocks.indexedDB.db;
var trans = db.transaction(["todo"], IDBTransaction.READ_WRITE);
var store = trans.objectStore("todo");
var request = store.get(id);
request.onsuccess = function(e) {
count++;
if(count>=times*MAX)
{
etime=new Date;
var t=document.getElementById('result').innerHTML;
document.getElementById('result').innerHTML=t+((etime.valueOf()-stime.valueOf())/times)+"<br/>";
allTime=0;stime=new Date;count=0;
delTest();
}
};
request.onerror = function(e) {
console.log("Error getting: ", e);
};
};
html5rocks.indexedDB.deleteTodo = function(id) {
var db = html5rocks.indexedDB.db;
var trans = db.transaction(["todo"], IDBTransaction.READ_WRITE);
var store = trans.objectStore("todo");
var request = store.delete(id);
request.onsuccess = function(e) {
count++;
if(count>=times*MAX)
{
etime=new Date;
var t=document.getElementById('result').innerHTML;
document.getElementById('result').innerHTML=t+((etime.valueOf()-stime.valueOf())/times)+"<br/>";
allTime=0;stime=new Date;count=0;
dataTest();
}
};
request.onerror = function(e) {
console.log("Error Adding: ", e);
};
};
html5rocks.indexedDB.addData = function(d) {
var db = html5rocks.indexedDB.db;
var trans = db.transaction(["todo"], IDBTransaction.READ_WRITE);
var store = trans.objectStore("todo");
var data={
"text":d,
"number":1
};
var request = store.put(data);
request.onsuccess = function(e) {
etime=new Date;
var t=document.getElementById('result').innerHTML;
document.getElementById('result').innerHTML=t+((etime.valueOf()-stime.valueOf()))+"<br/>";
};
request.onerror = function(e) {
console.log("Error Adding: ", e);
};
};
function addTest() {
for(i=1;i<=times*MAX;i++)
html5rocks.indexedDB.addTodo(' ',i);
}
function getTest() {
for(i=1;i<=times*MAX;i++)
html5rocks.indexedDB.getTodo(Math.round(Math.random()*(MAX*times-1)+1));
}
function delTest() {
for(i=1;i<=times*MAX;i++)
html5rocks.indexedDB.deleteTodo(i);
}
function dataTest() {
data=' ';
for(i=1;i<=21;i++)
data=data+data;
stime=new Date
html5rocks.indexedDB.addData(data);
}
function init() {
stime=new Date;
allTime=0;
html5rocks.indexedDB.open();
}
The spec is not finalized. This is currently shipped as the property mozIndexedDB in Gecko and webkitIndexedDB in Chrome until the standard is finalized. So you have to write for moz also. Now this code is only for webkit.
https://developer.mozilla.org/en/IndexedDB
setVersion() is Deprecated
The new way is to define the version in the IDBDatabase.open() method
firefox from version 10.0 implements open() with the new specification in which an indexeddb database IDBDatabase version is set as the second parameter of the open() method
example
var v = "1.20";
var request = indexedDB.open("todos", v);
html5 indexeddb javascript
The problem here is not the one chosen as the correct answer.
The problem is that the IndexedDB examples on HTML5Rocks were written to the pre-January IndexeDB spec. The working group has since published a breaking change going from the setVersion API to the new onupgradedneeded style.
Here, Firefox is technically correct to fail. Star this issue if you want to see Chrome do the same.

Categories

Resources