Open IndexedDb transaction on IE11 throw NotFoundError - javascript

I try to open and save some data in an indexedDB.
The indexeddb is encapsulate in a webworker but each time i try to open a transaction on IE11, it throws a "notFoundError" (works well on FF).
This is my simplified code :
var dbApi = indexedDB || webkitIndexedDB || mozIndexedDB || msIndexedDB;
var transactionApi = IDBTransaction || webkitIDBTransaction || mozIDBTransaction || msIDBTransaction || {};
var request = dbApi.open('myDB', 1);
var db;
request.onerror = handle_error;
request.onupgradeneeded = handle_upgrade;
request.onsuccess = function(event) {
console.log("Open db ok");
db = event.target.result;
try {
var t = db.transaction(["packet"], (transactionApi.READ_WRITE ? transactionApi.READ_WRITE : 'readwrite')); // Throw error here
t.onsuccess = function() {
var os = t.objectStore("packet");
var cmd = os.put("Some data", -2);
}
}
catch(e) {
console.log(e);
}
};
Thanks

I answer myself : on IE11, we can't create indexeddb from webworker. Db has to be created from main thread and web worker is able to access it after.

Related

indexddb A version change transaction is running

i am new in indexedddb.
when I want to create a transaction with a inceased version of the database (I increase the version because otherwise the upgradneeded event is never executed), I have the error "A version change transaction is running" which displays.
that's my code (it's from MDN):
var request = window.indexedDB.open("new-db", 8);
request.addEventListener('upgradeneeded', event => {
console.log("bonjour");
var db = event.target.result;
var request = db.transaction([], "readwrite")
.objectStore("customers")
.delete("444-44-4444");
request.onsuccess = function (event) {
// c'est supprimé !
};
});
request.onsuccess = function () {
console.log("open");
}
THANKS FOR YOUR HELP.
Replace this:
var request = db.transaction([], "readwrite")
.objectStore("customers")
.delete("444-44-4444");
With this:
var existingVersionChangeTransaction = event.target.transaction;
existingVersionChangeTransaction.objectStore('customers').delete('444-44-4444');

How can I open multiple WebSocket streams

I am trying to stream data from the Binance WebSocket API, I have it working for one symbol at a time.
if ("WebSocket" in window) {
//open websocket
var symbols = getSymbol();
//console.log(symbols);
symbols.forEach(function(entry) {
console.log(entry);
})
var ws = new WebSocket("wss://stream.binance.com:9443/ws/btcusdt#miniTicker")
ws.onopen = function() {
console.log("Binance connected...");
};
ws.onmessage = function(evt) {
var r_msg = evt.data;
var jr_msg = JSON.parse(r_msg);
}
ws.onclose = function() {
console.log("Binance disconnected");
}
} else {
alert("WebSocket is NOT supported");
}
the line var symbols = getSymbol(); creates an array of 431 symbols, my logic (and what I am trying to achieve) is to add the new websocket() to the forEach and stream price data from all of the currency pairs.
I'm not sure if this is possible at all or what a better solution would be but I wish to stream and display live data from the api.
Your idea about putting the new WebSocket() inside the for-each should work. However,
I'm not sure if you are allowed to opening hundreds of web sockets from the same tab, and there could also be some performance issues related to it.
According to the API documentation, it is possible to open just one web socket which will send you data from a list of streams, or even just all streams. Just construct the URLs like this:
Specific streams: wss://stream.binance.com:9443/ws/stream1/stream2/stream3
All streams: wss://stream.binance.com:9443/ws/!miniTicker#arr
Here is a code sample that takes these things into consideration. By default this code uses the URL for all streams, but it also has the code (commented out) that uses specific streams.
let streams = [
"ethbtc#miniTicker","bnbbtc#miniTicker","wavesbtc#miniTicker","bchabcbtc#miniTicker",
"bchsvbtc#miniTicker","xrpbtc#miniTicker","tusdbtc#miniTicker","eosbtc#miniTicker",
"trxbtc#miniTicker","ltcbtc#miniTicker","xlmbtc#miniTicker","bcptbtc#miniTicker",
"adabtc#miniTicker","zilbtc#miniTicker","xmrbtc#miniTicker","stratbtc#miniTicker",
"zecbtc#miniTicker","qkcbtc#miniTicker","neobtc#miniTicker","dashbtc#miniTicker","zrxbtc#miniTicker"
];
let trackedStreams = [];
//let ws = new WebSocket("wss://stream.binance.com:9443/ws/" + streams.join('/'));
let ws = new WebSocket("wss://stream.binance.com:9443/ws/!miniTicker#arr");
ws.onopen = function() {
console.log("Binance connected...");
};
ws.onmessage = function(evt) {
try {
let msgs = JSON.parse(evt.data);
if (Array.isArray(msgs)) {
for (let msg of msgs) {
handleMessage(msg);
}
} else {
handleMessage(msgs)
}
} catch (e) {
console.log('Unknown message: ' + evt.data, e);
}
}
ws.onclose = function() {
console.log("Binance disconnected");
}
function handleMessage(msg) {
const stream = msg.s;
if (trackedStreams.indexOf(stream) === -1) {
document.getElementById('streams').innerHTML += '<br/>' + stream + ': <span id="stream_' + stream + '"></span>';
trackedStreams.push(stream);
document.getElementById('totalstreams').innerText = trackedStreams.length;
}
document.getElementById('stream_' + stream).innerText = msg.v;
}
<span id="totalstreams"></span> streams tracked<br/>
Total traded base asset volume:<br/>
<div id="streams"></div>

axios / request used for schema / model

I want to build a db of users and if they have a site check if the site is online save the url if not delete it and advise the user that the site is offline. The problem is when the program goes thru the request it seems to do nothing and just jumps out, I tried using axios and request but the problem still remains; I believe it might be due to asynchronous computations. Any help will be really appreciated =)
var r = require('rethinkdb');
var axios = require('axios');
var schema = function(data, callback){
new_schema = true;
var schema = {};
if(new_schema){
schema.user = user.id;
}
schema.name = data.title || '';
schema.email = data.email || '';
if(data.url){
axios.get(data.url).then(function(err, response){
if(err) schema.url = 'no site'
schema.url = 'data.url';
callback(schema);
}).catch(function(error){
console.log(error);
callback(schema);
});
}else{
callback(schema);
}
};
var datos = '';
command.stdout.on('data', (data) => {
datos = datos + data;
});
command.on('close', (code) => {
const objs = JSON.parse(datos);
for (var i in objs) {
let obj = schema(objs[i], function(sch){
console.log(sch);
});
}
}catch(e){
console.log(e);
}
process.exit();
});
});
The problem is due to the asynchronous. To solved it had to use queues and I used the library better-queue. This fix the problem and makes all the calls to the server side.

Mobile Safari 10 IndexedDB Blobs

IndexedDB in Safari 10 supports blobs now. This works fine on desktop, however mobile Safari on iOS 10 throws an error:
UnknownError
and sometimes in combination:
TransactionInactiveError (DOM IDBDatabase Exception): Failed to store record in an IDBObjectStore:
The transaction is inactive or finished.
The code (shortened):
var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB,
READ_WRITE = IDBTransaction && IDBTransaction.READ_WRITE ? IDBTransaction.READ_WRITE : 'readwrite',
storeName = 'files',
db;
init: function() {
var request = indexedDB.open('mydb');
request.onerror = ...;
request.onupgradeneeded = function() {
db = request.result;
db.createObjectStore(storeName);
};
request.onsuccess = function() {
db = request.result;
};
},
save: function(id, data) {
var put = function(data) {
var objectStore = db.transaction([storeName], READ_WRITE).objectStore(storeName),
request = objectStore.put(data, id);
request.onerror = ...;
request.onsuccess = ...;
};
// not all IndexedDB implementations support storing blobs, only detection is try-catch
try {
put(data);
} catch(err) {
if (data instanceof Blob) {
Helpers.blobToDataURL(data, put);
}
}
}
On Mobile Safari 10 .put() doesn't throw like before, only later in the async error-callback.
Base64 strings work fine.
Bug in Mobile Safari or do I have to change code?
Test Case: http://fiddle.jshell.net/j7wh60vo/7/
Ran across the same problem. Chrome 54 and Safari 10 work fine on desktop, but on Mobile Safari I kept getting the Unknown error when trying to store a Blob into IndexedDB. I can confirm that this really is just an issue with Blobs on Mobile Safari, and not some misuse of the API.
Fortunately, ArrayBuffers work fine. So I instead downloaded the images like:
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';
Then saved them into IndexedDB as ArrayBuffers, and converted them to Blobs after pulling them out to get a url:
putRequest = objectStore.put(arrayBuffer, id);
putRequest.onsuccess = function(event) {
objectStore.get(id).onsuccess = function(event) {
var blob = new Blob([event.target.result], { type: 'image/jpeg'});
var URL = window.URL || window.webkitURL;
blobUrl = URL.createObjectURL(blob);
};
};
I'd rather not have to convert ArrayBuffers to Blobs like this as I assume there is a performance penalty. But it works.
That error looks to me like you have to change the code. That error does not indicate an issue with blobs. That error indicates you have a problem somewhere in how you call functions. To better answer your question, you need to post more of the surrounding code. Specifically, display the parts of the code where you create the transaction and where you create requests on the transaction.
Edit: first, remove the window.indexedDB stuff. Second, do not use 'db' in the way you are using it, because that will not work, the db may be closed by the time save is called.
function save(id, data) {
var openRequest = indexedDB.open(...);
openRequest.onerror = console;
openRequest.onsuccess = function(event) {
var db = openRequest.result;
// Open the transaction
var tx = db.transaction(storeName, 'readwrite');
var store = tx.objectStore(storeName);
// Immediately use the transaction
try {
var putRequest = tx.put(data, id);
putRequest.onerror = console;
} catch(error) {
console.log(error);
}
};
}
Edit2: Additional notes:
Prefixes have been removed, just use indexedDB, not mozIndexedDB or webkitIndexedDB etc
Transaction mode constants have been removed, use either 'readonly' or 'readwrite', or nothing (defaults to readonly)
I am somewhat confused how you are calling request = transaction.put. As far as I am aware, there is no method IDBTransaction.prototype.put as shown in the spec https://w3c.github.io/IndexedDB/#idbtransaction. I am confused as to why the Mozilla docs show an example with transaction.put. Inspecting the prototype of IDBTransaction in Chrome 55 does not show a put method.
There is IDBObjectStore.prototype.put. Your code should not be working at all, on any platform, as it is currently written. So if it did ever work, I am surprised. You should only be using something like var store = transaction.objectStore('store'); store.put(obj); where you call put on the object store.

Error while opening indexeddb with higher version than existing

var database = e.target.result;
var version = Number(database.version);
console.log("in onsuccess>>>>>>>>>>>>>>>>>>>>>>>>>> : "+dbName);
console.log(e);
database.close();
var secondRequest = indexedDB.open(dbName, (version+1));
console.log(secondRequest); // <-- error on this line
//console.log(secondRequest.result);
secondRequest.onupgradeneeded = function (e) {
console.log("in onupgradeneeded>>>>>>>>>>>>>>>>>>>>>>>>>>");
console.log(e);
var database = e.target.result;
//database.setVersion(12);
var objectStore = database.createObjectStore(storeName, {
keyPath: 'id'
});
};
secondRequest.onsuccess = function (e) {
console.log("000000000000000000000000000000");
e.target.result.close();
};
secondRequest.onerror = function(e){
console.log("Error ------------------- ");
console.log(e);
}
in above console I am getting following error in
console.log(secondRequest);
error:
IDBOpenDBRequest
error : [Exception: DOMException]
I have added listner
IDBOpenDBRequest.onerror = function(e){
}
But It is not going there. Help me if anybody have solution.
Although you have some of the core concepts down, your code is really hard to follow as is. To begin with, this e event assignment is undefined:
var database = e.target.result;
Where is the database open()? Where is dbName coming from?
Provide more of your failing code, preferably via jsfiddle, and we'll help you find a solution.
UPDATE: Here's a working example of what you're trying to do.
Output div:
<div id="idb_version"></div>
Code:
var db_name = 'myname',
database_open_request = window.indexedDB.open(db_name);
database_open_request.addEventListener('success', function (e) {
database = e.target.result;
database.close();
var second_database_open_request = window.indexedDB.open(db_name, database.version + 1);
second_database_open_request.addEventListener('upgradeneeded', function (e) {
database = e.target.result;
database.close();
window.document.getElementById("idb_version").innerHTML = database.version;
});
});
When not specifying a version param, you get a reference to the most recent version on success callback. Then I listen for a versionchange and increase the version by one. Run this over and over and you'll see the version increase one by one.

Categories