Error while opening indexeddb with higher version than existing - javascript

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.

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');

AWS Lambda function global variables

I am writing an AWS Lambda function in JavaScript (Node.js) that interacts with CodeCommit through the AWS SDK.
The communication between the services works as expected, I am getting data within the CodeCommit function, but the issue I am facing appears when I want to use this data outside of the function.
I have tried two approaches:
1. Global Variable
Code:
var aws = require('aws-sdk');
var codecommit = new aws.CodeCommit({ apiVersion: '2015-04-13' });
var repoName = ''; // Declared my global variable here
exports.handler = function(event, context) {
var commitId = "69a5f8eeba340d71ba41b8f20d77cc20b301ff52"
var repository = "my-repository"
var params = {
repositoryName: repository
};
codecommit.getRepository(params, function(err, data) {
if (err) {
console.log(err);
var message = "Error getting repository metadata for repository " + repository;
console.log(message);
context.fail(message);
} else {
console.log('Repository Name:', data.repositoryMetadata.repositoryName); // Shown with data
repoName = data.repositoryMetadata.repositoryName; // Setting the variable
console.log('Account Id:', data.repositoryMetadata.accountId); // Shown with data
}
});
console.log(repoName); // Shown as blank in the output
};
Output:
The last written "console.log" is the first to print in the execution results, but shows blank. The two other console.log (within the functions) are then printed, and they show the data.
2. Function
Code:
var aws = require('aws-sdk');
var codecommit = new aws.CodeCommit({ apiVersion: '2015-04-13' });
exports.handler = function(event, context) {
var commitId = "69a5f8eeba340d71ba41b8f20d77cc20b301ff52"
var repository = "my-repository"
var repoData = getRepository(repository)
console.log('Repository Name:', repoData.repositoryName);
console.log('Account Id:', repoData.accountId);
};
function getRepository(repository) {
var params = {
repositoryName: repository
};
codecommit.getRepository(params, function(err, data) {
if (err) {
console.log(err);
var message = "Error getting repository metadata for repository " + repository;
console.log(message);
context.fail(message);
} else {
var repoData = {};
repoData.repositoryName = data.repositoryMetadata.repositoryName;
repoData.accountId = data.repositoryMetadata.accountId;
console.log(repoData); // Shows output in execution results when lines 11 & 12 are commented
return repoData;
}
});
}
Output:
{
"errorType": "TypeError",
"errorMessage": "Cannot read property 'repositoryName' of undefined",
"trace": [
"TypeError: Cannot read property 'repositoryName' of undefined",
" at Runtime.exports.handler (/var/task/index.js:57:46)",
" at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"
]
}
Conclusion
None of those approaches worked. The data is always visible within the function but never outside of it. I suspect that the code outside of the function executes before the function itself, and I wonder if I could make the code to wait that the function has been executed before doing the console.log (and other actions after it). Or maybe I am wrong on another level?
You are using a callback model, in which case the console.log in the first example is being hit before the code in the callback. A better option would be to use async/await.
var aws = require('aws-sdk');
var codecommit = new aws.CodeCommit({ apiVersion: '2015-04-13' });
var repoName = ''; // Declared my global variable here
exports.handler = async function(event, context) {
var commitId = "69a5f8eeba340d71ba41b8f20d77cc20b301ff52"
var repository = "my-repository"
var params = {
repositoryName: repository
};
var data = await codecommit.getRepository(params).promise();
console.log('Repository Name:', data.repositoryMetadata.repositoryName); // Shown with data
repoName = data.repositoryMetadata.repositoryName; // Setting the variable
console.log('Account Id:', data.repositoryMetadata.accountId); // Shown with data
console.log(repoName);
};
Notice that I'm not catching the error here, but if you wanted to you can use a try/catch block. Just be sure you throw a new error in that case if you want the function to fail.

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.

how to store a mongodb array of collections inside an indexedDB

Hello I want to build a local database for my phonegap so user can use it offline.
I have this in angular function that creates a database.
function Database() {
return {
create: function (itemDocs) {
var db = null;
var request = indexedDB.open("myDB", 1);
request.onsuccess = function (event) {
db = event.target.result;
console.log("DB loaded successfully");
};
request.onerror = function (event) {
console.log(event)
};
request.onupgradeneeded = function (event) {
db = event.target.result;
console.log("DB initiliazed / created");
//create collections
db.createObjectStore("items", {keyPath: "_id"});
//create documents
var transaction = db.transaction(["items"], "readwrite");
var items = transaction.objectStore("items");
items.add(itemDocs);
};
}
}
}
The itemDocs holds a mongoDB collection (which is an array of objects) and I want to store that collection inside indexedDB database the problem im having is that I'm getting this annoying error.
Uncaught InvalidStateError: Failed to execute 'transaction' on 'IDBDatabase': A version change transaction is running.
Use var transaction = event.target.transaction instead of var transaction = db.transaction(...);
A full answer is rather lengthy. Briefly, you don't want to create a new transaction in onupgradeneeded. There is already an active transaction available for you.

How to mock event handler method using sinon.js?

I am newbie to Node.js and I am writing DAO layer for HBase which will wrap thrift and provide clear interface to other layers. I am trying to write unit tests for it using sinon.js and mocha but not sure how to ensure mock one event of Thrift connection class and its event handler.
My DAO code is as follows:
var thrift = require('thrift');
var libDirRelativePath = "../../../lib";
var hbaseThriftDirPath = libDirRelativePath + "/hbase-gen-nodejs";
var hbase = require(hbaseThriftDirPath + '/THBaseService');
var hbaseTypes = require(hbaseThriftDirPath + '/hbase_types');
var thritfPrimaryServerAddress = 'nn2';
var thritfBackupServerAddress = 'backup-nn2';
var thriftServerPort = 9090;
exports.putRows = function(tableName, putObjectArray, callback) {
var primaryClusterConnection = thrift.createConnection(thritfPrimaryServerAddress, thriftServerPort, {
transport: thrift.TBufferedTransport,
protocol : thrift.TBinaryProtocol
});
console.log('DEBUG : connection object created.');
var client = thrift.createClient(hbase, primaryClusterConnection);
console.log('DEBUG : client object created.');
primaryClusterConnection.on('connect', onConnectOfPutRows);
primaryClusterConnection.on('connect', function() {
console.log('Connected to HBase thrift server at ' + thritfPrimaryServerAddress + ":" + thriftServerPort);
client.putMultiple(tableName, putObjectArray, callback);
connection.close();
});
primaryClusterConnection.on('error', function() {
console.log('Error occurred in HBase thirft server connection.');
});
}
For above code I Just want to create stubs primaryClusterConnection and client objects which I have managed but problem is that stub of primaryClusterConnection doesn't have any idea about connect event and its handler so console.log('Connected to HBase thrift server at '... line never gets executed. I want to test that part of the code as well. Can anyone please help me in writing proper stubs/mocks for this problem?
My test code is as follows:
var hbaseDao = require('../../../src/dao/hbase/HBaseDao.js');
var libDirRelativePath = "../../../lib";
var hbaseThriftDirPath = libDirRelativePath + "/hbase-gen-nodejs";
var hbase = require(hbaseThriftDirPath + '/THBaseService');
var chai = require('chai');
var should = chai.should();
var expect = chai.expect;
var sinon = require('sinon');
describe("HBaseDao", function() {
describe(".putRows()", function() {
it("Should execute callback after inserting objects in HBase.", function(done) {
var commonStub = sinon.stub();
var connection = {
close : function() {
console.log('connection closed.');
}
};
commonStub.withArgs('nn2', 9090).returns(connection);
var client = {};
commonStub.withArgs(hbase, connection).returns(client);
var tableName = 'DUMMY_READINGS_TABLE';
var callBackMethod = function() {
console.log('dummy callback function.');
};
commonStub.withArgs(tableName, [], callBackMethod).returns(0);
hbaseDao.putRows(tableName, [], callBackMethod);
expect(hbaseDaoSpy.callCount).to.equal(1);
done();
});
Let's start by simplifying the problem a bit.
it.only("Should execute callback after inserting objects in HBase.", function(done) {
var events = require('events');
var hbaseDao = new events.EventEmitter();
hbaseDao.putRows = function() {
console.log('putting rows');
this.emit('notify');
};
hbaseDao.on('notify', function(){
console.log('notify event fired');
done(); //here's where you call the callback to assert that the event has fired
});
sinon.spy(hbaseDao, 'putRows');
var commonStub = sinon.stub();
var tableName = 'DUMMY_READINGS_TABLE';
var client = {};
var connection = {
close : function() {
console.log('connection closed.');
}
};
var callBackMethod = function() {
console.log('dummy callback function.');
};
commonStub.withArgs('nn2', 9090).returns(connection);
commonStub.withArgs({}, connection).returns(client);
commonStub.withArgs(tableName, [], callBackMethod).returns(0);
hbaseDao.putRows(tableName, [], callBackMethod);
//assertions
assert(hbaseDao.putRows.calledOnce);
});
The above test will just work, because it creates a new "hbaseDao" from a simple event emitter and has the method and the notify event ready to go.
Because we're doing an async test, we need to have the done callback in the spec. Notice that this will only fire "done" when the event has occurred. Hence, the test will not pass unless the event fires. Also notice that we're spying specifically on the the hbaseDao 'putRows' and we're asserting that the its called once, another way to ensure that the test is working. Now consider this example and apply it to your original question.
I think you almost got it, but you need to put your done callback in the callback stub as so:
var callBackMethod = function() {
console.log('dummy callback function.');
done();
};
That way, when your primaryClusterConnection.on('connect') event is fired, the supplied callback will execute the done and complete the test.
That being said, you should leave your primaryClusterConnection intact and let the implementation details of hbaseDao not be considered in your test.
You mentioned that:
primaryClusterConnection doesn't have any idea about connect
But that can't be right, because you're creating a new connection in the test and there's nothing in your implementation that tells me you have changed the event handler for the connection.
So I think in the end, you're missing the point of the test, which is simply should execute callback... and you're stubbing out stuff that you don't even need to.
Try something like this:
//use it.only to make sure there's no other tests running
it.only("Should execute callback after inserting objects in HBase.", function(done) {
//get the class
var hbaseDao = require('../../../src/dao/hbase/HBaseDao.js');
//spy on the method
sinon.spy(hbaseDao, 'putRows');
//create a table name
var tableName = 'DUMMY_READINGS_TABLE';
//create callback method with done.
var callBackMethod = function() {
console.log('dummy callback function.');
done();
};
//run the function under test
hbaseDao.putRows(tableName, [], callBackMethod);
//assert called once
assert(hbaseDao.putRows.calledOnce);
});

Categories