node-mssql transaction not committing - javascript

I am trying to run queries again my database using node-mssql. Everything works perfect. But when I try to execute queries within a transaction, transaction gets committed but tables remain empty. Can someone check whats wrong with the code:
var transaction = new sql.Transaction(/* [connection] */);
transaction.begin(function(err) {
// ... error checks
console.log("[Info]","Begin Transaction.");
if(err) {
console.log(err);
process.exit(-1)
}
var request = new sql.Request(transaction);
var transactionFailed = false;
var request = new sql.Request(transaction);
//request.multiple = true;
request.verbose = true;
request.query(upsertQuery);
console.log("[Info]",request)
request.on('error', function(err) {
transactionFailed = true;
console.log(['Error'],err.toString())
});
request.on('done', function(errs) {
if(transactionFailed) {
transaction.rollback(function(err) {
if(err) {
console.log(err);
process.exit(-1)
}
else {
process.exit(-1)
}
});
}
else {
transaction.commit(function(err) {
if(err) {
console.log(err);
process.exit(-1)
}
else {
console.log("Transaction Committed!")
}
});
}
});
});

Issue was with my sql query. the above code works fine

Related

JQuery Custom Validation Rule Mysql function always showing error

I am trying to add a custom validation rule to check if username exists or not. My code:
jQuery.validator.addMethod("checkexist", function(myvalue, element) {
checkifexist(function(result) {
if (result == true)
{
return true;
}
else
{
return false;
}
});
}, 'Does not exists!');
and
async function checkifexist(callback) {
const secret = keytar.getPassword('Userdata', 'MysqlPassword');
secret.then((result) => {
var mysql = require("mysql");
var connection = mysql.createConnection({
host: store.get('ip'),
port: store.get('port'),
user: store.get('username'),
password: result,
database: "database"
});
var querystring = 'SELECT * FROM `testdb`';
try
{
connection.query(querystring, (err, rows, fields) => {
if(err){
return callback("error with query", err);
}
var found;
for (var i in rows)
{
if (some check...)
{
return callback(true);
}
}
return callback(false);
});
connection.end(() => {
});
}
catch { }
});
However, if I check the valditation it correctly outputs true or false on every keypress. I still get only validation errors, though it should be a valid input.

How to return a list of SQS queues in a module exports function?

I'm very new to node.js so I think I'm missing something obvious here.
I'm simply trying to get a list of SQS queues using aws-sdk and return them from a module to be accessible to other code. list_queues is the function in question.
The code below works to an extent, I see a "success" log and a log of a string array of all my queues, however, the function does not return that array to the caller and I don't understand why.
const AWS = require('aws-sdk');
AWS.config.update({region: 'eu-west-1'});
var sqs;
var sts = new AWS.STS();
sts.assumeRole({
RoleArn: 'arn:aws:iam::xxxxx:role/UserRole',
RoleSessionName: 'NodeDeveloperRoleSession'
}, function(err, data) {
if (err) { // an error occurred
console.log('Cannot assume role :(');
console.log(err, err.stack);
} else { // successful response
console.log('Assumed role success :)');
AWS.config.update({
accessKeyId: data.Credentials.AccessKeyId,
secretAccessKey: data.Credentials.SecretAccessKey,
sessionToken: data.Credentials.SessionToken
});
sqs = new AWS.SQS({apiVersion: '2012-11-05'});
}
});
exports.list_queues = function() {
sqs.listQueues({}, function(err, data) {
if (err) {
console.log("Error", err);
} else {
console.log("success");
console.log(data.QueueUrls);
return data.QueueUrls;
}
});
}
Any help is appreciated
exports.list_queues = function() { // 2. but you actually want to return from this one
sqs.listQueues({}, function(err, data) { <-----------------
if (err) { |
console.log("Error", err); |
} else { |
console.log("success"); |
console.log(data.QueueUrls); |
return data.QueueUrls; // 1. you are returning from this one
}
});
}
there are two ways you can make it work
Promise based
exports.list_queues = function() {
return sqs.listQueues({}).promise().then((data) => data.QueueUrls);
}
// and in another file you would:
const {list_queues} = require('./list_queues.js');
list_queues.then((queues) => console.log(queues));
Callback based
exports.list_queues = function(cb) { // notice I added callback here
sqs.listQueues({}, function(err, data) {
if (err) {
console.log("Error", err);
} else {
console.log("success");
console.log(data.QueueUrls);
cb(data.QueueUrls);
}
});
}
// and in another file you would:
const {list_queues} = require('./list_queues.js');
list_queues(function(queues) {
console.log(queues);
});
I strongly recommend you to use promise based approach, since it's much more readable and you can make use of async/await on it, which is great.

Elasticsearch.js - wait for ping to complete, async call

I am playing with elasticsearch.js from the browser. I would like to ping elasticsearch, wait for the request to complete and then return the result of the connection. But right now it is happening asynchronously, and returning undefined even when the connection is ok. I have code like this:
var connectionOK = false;
function createElasticsearchClient(hostAddress) {
var client = new $.es.Client({
hosts: hostAddress
});
return client;
}
function checkElasticsearchConnection(client) {
$.when(pingElasticsearch(client)).done(function () {
return connectionOK;
});
}
function pingElasticsearch(client) {
console.log("ELASTICSEARCH: Trying to ping es");
client.ping({
requestTimeout: 30000,
// undocumented params are appended to the query string
hello: "elasticsearch"
}, function (error) {
if (error) {
console.error('ELASTICSEARCH: Cluster is down!');
connectionOK = false;
console.log("INSIDE: " + connectionOK);
} else {
console.log('ELASTICSEARCH: OK');
connectionOK = true;
console.log("INSIDE: " + connectionOK);
}
});
}
and how it is used:
var esClient = createElasticsearchClient("exampleserver.com:9200");
var esCanConnect = (checkElasticsearchConnection(esClient));
You're mixing asynchronous functions with synchronous functions. You could go with this approach instead:
function createElasticsearchClient(hostAddress, callback) {
var client = new $.es.Client({
hosts: hostAddress
});
return callback(client);
}
function pingElasticsearch(client, callback) {
console.log("ELASTICSEARCH: Trying to ping es");
client.ping({
requestTimeout: 30000,
// undocumented params are appended to the query string
hello: "elasticsearch"
}, function (error) {
if (error) {
return callback('ELASTICSEARCH: Cluster is down!');
} else {
return callback(null);
}
});
}
And then run
createElasticsearchClient("exampleserver.com:9200", function(esClient) {
pingElasticsearch(esClient, function(err) {
if (err) console.log(err);
else {
//Everything is ok
console.log('All good');
}
});
});

returning data from node mssql execute functions

I'm using mssql(Microsoft SQL Server client for Node.js) package from npm.I'm trying to execute a stored procedure residing in my sql server database.Everything works fine.However what I want to do is return the recordsets so that i can export this to be used in other module.Below is what I'm trying to do.
function monthlyIceCreamSalesReport (scope){
var connObj = connConfig();
connObj.conn.connect(function(err){
if(err){
console.log(err);
return;
}
connObj.req.input('Month',4);
connObj.req.input('Year',2016);
connObj.req.execute('<myStoredProcedure>', function(err, recordsets, returnValue){
if(err){
console.log(err);
}
else {
console.log(recordsets[0]); // successfully receiving the value
}
connObj.conn.close();
});
});
console.log('check for recordsets', recordsets[0]); // undefined
return recordsets[0];
}
var sqlServerObj = {
monICSalesReport : monthlyIceCreamSalesReport,
};
module.exports = sqlServerObj;
As shown in the code snippet, since the value of recordsets[0] is undefined, exporting this function is of no use.
You can't return this way in async nature. You can get it by passing the callback function
Try to give a callback function like this
function monthlyIceCreamSalesReport(scope, callback) { // pass a callback to get value
var connObj = connConfig();
connObj.conn.connect(function(err) {
if (err) {
console.log(err);
return;
}
connObj.req.input('Month', 4);
connObj.req.input('Year', 2016);
connObj.req.execute('<myStoredProcedure>', function(err, recordsets, returnValue) {
if (err) {
console.log(err);
} else {
console.log(recordsets[0]);
connObj.conn.close();
return callback(null, recordsets[0]); //return as a callback here and get that value in callback from where you called this function
}
});
});
}
var sqlServerObj = {
monICSalesReport: monthlyIceCreamSalesReport,
};
module.exports = sqlServerObj;
Note: See the comment to understand the changes
recordsets[0] is undefinded, because is defined only in connObj.req.execute function scope. You may do this in this way:
function monthlyIceCreamSalesReport (scope, cb){
var connObj = connConfig();
connObj.conn.connect(function(err){
if(err){
console.log(err);
return cb(Error("Something wrong"));
}
connObj.req.input('Month',4);
connObj.req.input('Year',2016);
connObj.req.execute('<myStoredProcedure>', function(err, recordsets, returnValue){
if(err){
console.log(err);
connObj.conn.close();
return cb(Error("Something wrong"));
}
else {
console.log(recordsets[0]); // successfully receiving the value
connObj.conn.close();
return cb(recordsets[0]);
}
});
});
}
var sqlServerObj = {
monICSalesReport : monthlyIceCreamSalesReport,
};
module.exports = sqlServerObj;

Node.js 'headers already sent' when page is refreshed

I keep getting this error (after a certain amount of time) when i refresh the my 'members area' after login. I use response.redirect to redirect to the area (success) or back to sign in form (error). How can i fix this?
app.get('/sellers/login', function(request, response) {
if(request.session.sellerId){
response.redirect( '/sellers/area?logged_in=true');
}
else{
response.render('pages/sellers-login');
}
});
app.post('/authenticate', function(request, response) {
if(request.session.sellerId){
response.redirect('/area?logged_in=true');
}
else{
db.authenticate(request.body.loginid, function(err, results) {
if(err){
response.redirect('/sellers/login?err=1&logged_in=false&type=db');
}
else{
if(results.length >=1){
var hash = results[0]['hash'];
var seller_id = results[0]['id'];
bcrypt.compare(request.body.password, hash, function(err, res) {
if(res){
request.session.sellerId = seller_id;
response.redirect('/sellers/area?logged_in=true');
}
else{
response.redirect('/sellers/login?err=1&logged_in=false&type=pMatch');
}
});
}
else{
response.redirect('/sellers/login?err=1&logged_in=false&type=user');
}
}
});
}
});
app.get('/sellers/area', function(request, response) {
if(request.session.sellerId){
response.render('pages/sellers-area');
}
else{
response.redirect('/sellers/login?not_logged_in=true');
}
});
if(request.session.sellerId){
response.redirect('/area?logged_in=true');
}
db.authenticate(request.body.loginid, function(err, results) {
// ....
});
You send the header when request.session.sellerId evaluates to true by calling the response.redirect, but you continue with the the db.authenticate afterwards.
Inside of that callback you will do another redirect, even when your redirect for that response has already taken place.
Inside of the db.authenticate you have the same problem with the if(err)
EDIT
you need to use an else block (or a return) for both the if (request.session.sellerId) and the if (err) {
if (request.session.sellerId) {
response.redirect('/area?logged_in=true');
} else {
db.authenticate(request.body.loginid, function(err, results) {
if (err) {
response.redirect('/sellers/login?err=1&logged_in=false&type=db');
} else if (results.length >= 1) {
var hash = results[0]['hash'];
var seller_id = results[0]['id'];
bcrypt.compare(request.body.password, hash, function(err, res) {
if (res) {
request.session.sellerId = seller_id;
response.redirect('/sellers/area?logged_in=true');
} else {
response.redirect('/sellers/login?err=1&logged_in=false&type=pMatch');
}
});
} else {
response.redirect('/sellers/login?err=1&logged_in=false&type=user');
}
});
}
I think i've found precisely where the error originates from which lies in the db.authenticate
//db.js
exports.authenticate = function(loginid, callback) {
var sql = "select ...";
pool.getConnection(function(err, connection) {
if(err) {
console.log(err);
callback(true);
return;
}
connection.query(sql, [loginid], function(err, results) {
connection.release();
if(err) {
console.log(err);
callback(true);
return;
}
callback(false, results);
});
connection.on('error', function(err) {
console.log(err);
connection.release();
callback(true);
return;
});
});
};
The connection.on('error',... gets called, so the callback(true) activates causing this error.

Categories

Resources