AWS Lambda Invoke does not execute the lambda function - mysql

I created 4 Lambda functions to process information that will be written into a MySQL table. the first three function just select, insert and update a MYSQL table record respectively.
I then created a 4th function to accept the record detail as part of the event parameter. This function will first try to select the record by invoking the first lambda function and if it finds it, will update the record on the table using the update lambda function. If it does not find it, it will invoke the insert function to add the record. I am using pool.query on the 3 functions that manipulates the MySQL table. I am also using lambda.invoke to call those three functions from the 4th function.
I was able to successfully test the 4th function locally by passing the record details as parameter and it was able to successfully call the three Lambda function and update the mySQL table record. The problem that I am having is that when I upload the function in AWS Lambda, it does not invoke any of the three functions. I am not seeing any errors in the log so I don't know how to check where the problem is. Here's ,y code that invokes the other functions:
exports.handler = (event, context, callback) => {
var err = null;
var payload = {
qryString : event.qryString,
record: event.updaterecord,
dbConfigPool : event.dbConfigPool
}
var params = {
FunctionName: 'getInventory',
Payload: JSON.stringify(payload)
}
console.log(' before invoke ' + JSON.stringify(params) )
lambda.invoke(params, function(err, data) {
console.log(' aftr invoke ' + JSON.stringify(params) )
if (err) {
console.log('err ' + err, err.stack); // an error occurred
event.message = err + ' query error';
}
else {
console.log('success' + JSON.stringify(data));
console.log(' status code ' + JSON.stringify(data.StatusCode));
console.log(' Payload ' + JSON.stringify(JSON.parse(data.Payload)));
var rowsTemp = JSON.parse(data.Payload);
var rows = rowsTemp.data;
if (!rowsTemp.recordExist) {
console.log('insert')
// Update inventory record only if quantity is not negative
var newQuantity = 0
newQuantity = parseFloat(event.updaterecord.quantity);
if (Math.sign(newQuantity) === 1) {
var payload = {
record: event.updaterecord,
dbConfigPool : event.dbConfigPool
}
console.log('insert' + JSON.stringify(payload));
var params = {
FunctionName: 'insertInventory',
Payload: JSON.stringify(payload)
}
lambda.invoke(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
}
}
else {
newQuantity = 0
newQuantity = parseFloat(event.updaterecord.quantity) + parseFloat(rows[0].quantity);
if (Math.sign(newQuantity) === 1) {
event.updaterecord.quantity = newQuantity;
} else {
// Set to zero if the result is negative
event.updaterecord.quantity = 0;
}
console.log('value ' + JSON.stringify(newQuantity) + ' updaterecord' + JSON.stringify(event.updaterecord.quantity) );
var payload = {
qryString : event.qryString,
record: event.updaterecord,
dbConfigPool : event.dbConfigPool
}
console.log('update' + JSON.stringify(payload));
var params = {
FunctionName: 'updateInventory',
Payload: JSON.stringify(payload)
}
console.log(' before invoke ' + JSON.stringify(params) )
lambda.invoke(params, function(err, data) {
console.log(' after invoke ' + JSON.stringify(params) )
if (err) {
console.log('err ' + err, err.stack); // an error occurred
event.message = err + ' query error';
} else {
console.log(data);
} // else
}); // lambda invoke
}
} // successful response
});
console.log(' end of function');
var completed = true;
context.callbackWaitsForEmptyEventLoop = false;
callback(null, completed);
}
Apologies if the code is quite long. But I wanted to show that I did put a number of console.logs to monitor where is goes through. The cloudwatch logs only shows the first message before the first lambda.invoke and then it shows the last message for the end of the function.
I am also not seeing any log entries in cloudwatch for the three functions that has been invoked.
06/17
ok, since I am still unable to make this work, I simplified the code to just the following:
exports.handler = (event, context, callback) => {
var err = null;
var updatedRecord = false;
var responseDetail = {};
var payload = {
qryString : event.qryString,
record: event.updaterecord,
dbConfigPool : event.dbConfigPool
}
var params = {
FunctionName: 'getInventory',
Payload: JSON.stringify(payload)
}
console.log(' before invoke ' + JSON.stringify(params));
lambda.invoke(params, function(err, data) {
if (err) {
event.message = err + ' query error';
callback(err,event.message);
}
else {
console.log('success' + JSON.stringify(data));
console.log(' status code ' + JSON.stringify(data.StatusCode));
console.log(' Payload ' + JSON.stringify(JSON.parse(data.Payload)));
callback(null, data);
} // successful response
});
console.log(' end of function');
// var completed = true;
// context.callbackWaitsForEmptyEventLoop = false;
// callback(null, completed);
}
However, the function is timing out when I do my test. I have also given the role attached to the functions full Lambda and RDS access.

First of all - welcome to callback hell! I will return to this later.
This is a simple code that invokes a lambda function.
var params = {
FunctionName: 'LAMBDA_FUNCTION_NAME', /* required */
};
lambda.invoke(params, function(err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
}
else {
console.log(data); // successful response
}
});
lambda.invoke function has two parameters (params, function(err,data){..}). The first one is a simple JSON object. The second one is a function - a callback function. This function will be "called back" when the execution of lambda.invoke (you could think LAMBDA_FUNCTION_NAME) ends. If an error occurs it would be "stored" in err variable otherwise returned data will be stored in data variable (This is not the right explanation but I am trying to keep it simple here).
What happens when you want to invoke two lambda functions one after another?
var params1 = {
FunctionName: 'LAMBDA_FUNCTION_1_NAME', /* required */
};
lambda.invoke(params1, function(err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
}
else {
console.log('Lambda function 1 invoked!');
console.log(data); // successful response
}
});
var params2 = {
FunctionName: 'LAMBDA_FUNCTION_2_NAME', /* required */
};
lambda.invoke(params2, function(err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
}
else {
console.log('Lambda function 2 invoked!');
console.log(data); // successful response
}
});
console.log('I am done!');
Depending on execution time of LAMBDA_FUNCTION_1_NAME and LAMBDA_FUNCTION_2_NAME you could see different outputs like:
Lambda function 1 invoked!
I am done!
or
Lambda function 1 invoked!
Lambda function 2 invoked!
I am done!
or even
Lambda function 1 invoked!
I am done!
Lambda function 2 invoked!
This is because you are calling lambda.invoke and after that (without waiting) you are calling lambda.invoke again. After that (of course without waiting) the previous functions to end you are calling console.log('I am done!');
You could solve this by putting each function in previous function's callback. Something like this:
var params1 = {
FunctionName: 'LAMBDA_FUNCTION_1_NAME', /* required */
};
lambda.invoke(params1, function(err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
}
else {
console.log('Lambda function 1 invoked!');
console.log(data); // successful response
var params2 = {
FunctionName: 'LAMBDA_FUNCTION_2_NAME', /* required */
};
lambda.invoke(params2, function(err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
}
else {
console.log('Lambda function 2 invoked!');
console.log(data); // successful response
console.log('I am done!');
}
});
}
});
That way your output would be:
Lambda function 1 invoked!
Lambda function 2 invoked!
I am done!
But if you want to invoke 3 or more functions one after another you will end up with nested code. This is the callback hell. You could re-write you code in that way. But in my opinion it is a good idea to check waterfall async library
async.waterfall([
function(callback) {
callback(null, 'one', 'two');
},
function(arg1, arg2, callback) {
// arg1 now equals 'one' and arg2 now equals 'two'
callback(null, 'three');
},
function(arg1, callback) {
// arg1 now equals 'three'
callback(null, 'done');
}
], function (err, result) {
// result now equals 'done'
})
Pseudo code should look like this:
async.waterfall([
function(callback1) {
var params1 = {
FunctionName: 'LAMBDA_FUNCTION_1_NAME', /* required */
};
lambda.invoke(params1, function(err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
}
else {
console.log('LAMBDA_FUNCTION_1_NAME finished!');
callback1(null,data);
}
});
},
function(result_from_function_1, callback2) {
console.log(result_from_function_1); // outputs result from LAMBDA_FUNCTION_1_NAME
var params2 = {
FunctionName: 'LAMBDA_FUNCTION_2_NAME', /* required */
};
lambda.invoke(params2, function(err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
}
else {
console.log('LAMBDA_FUNCTION_2_NAME finished!');
callback2(null,data);
}
});
},
function(result_from_function_2, callback3) {
console.log(result_from_function_2); // outputs result from LAMBDA_FUNCTION_2_NAME
var params3 = {
FunctionName: 'LAMBDA_FUNCTION_3_NAME', /* required */
};
lambda.invoke(params3, function(err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
}
else {
console.log('LAMBDA_FUNCTION_3_NAME finished!');
callback3(null,data);
}
});
}
], function (err, result) {
// result now equals LAMBDA_FUNCTION_3_NAME result
})
Please note that all callbacks (callback1, callback2 and callback3) could be with name "callback" only. I changed their names for better understanding.

Think about what this does:
lambda.invoke(params, function(err, data) { ...
It starts "doing something" (the fact that happens to be invoking another lambda function is actually unimportant) and when "something" is done, it calls function(), right?
But it also returns immediately, and the next statement executes.
Meanwhile "something" is being handled by the asynchronous event loop.
The "next statement" is
console.log(' end of function');
Then, you're telling lambda "hey, I may have some async stuff going on, but don't worry about waiting for it to finish":
context.callbackWaitsForEmptyEventLoop = false;
So the good news is your code is doing what is was written to do... but that turns out to be wrong.
Everywhere you have one of these two things...
// an error occurred
// successful response
...those are the places you should be calling callback(), not at the end of the handler function, which your code reaches very quickly, as it is supposed to.
You shouldn't need to use context.callbackWaitsForEmptyEventLoop = false; if you properly disconnect your database connections and all modules you include are well-behaved. While that has its purposes, there seem to be a lot of people using it to cover up for subtle unfinished business.
Or, for a tidier solution, where you only have one mention of the callback at the end and your function { function { function { nesting doesn't get so out of control, use async-waterfall.

Related

Node js and mysql return query result

hi i'm newly learning nodejs and connected mysql database
now i want to save the result of a select query in a variable of some type but i cant.
var campGround = [];
console.log("Select Statement started....");
con.connect(function(error){
if(!error){
console.log("Connected");
var sql = "select * from campgrounds";
con.query(sql,function(err,result,field){
if (!err) {
// console.log(JSON.parse(result));
for(var i =0;i<result.length;i++)
{
try {
// console.log(result[i]);
setCampground(result[i]);
// campGround.push(result[i]);
} catch (error) {
console.log(error.message);
}
}
}
else{
console.log("Error while selecting record from campground table. ");
}
});
}else{
console.log("Error DataBase Not Connected!!! select statement");
}
});
function setCampground(value){
this.campGround.push(value);
}
console.log("length after execution :: "+campGround.length);
campGround.forEach(function(value){
console.log("Campground array");
console.log(value);
});
when i execute the above code and debug it...the select statement return from the database 3 records...but when i push them into the array ... and print the array nothing happens...please help
i cant find anything that could help me.
Your mysql query call is asynchronous (callback based) and your call to log the campGround is outside that callback so that means you are making a call but not waiting for that call to finish. That is the reason your campGround is not printing any thing.
You need to move following lines inside the callback where are are handling the error and response. something like this
const campGround = [];
console.log("Select Statement started....");
con.connect(function (error) {
if (!error) {
console.log("Connected");
const sql = "select * from campgrounds";
con.query(sql, function (err, result, field) {
if (!err) {
// console.log(JSON.parse(result));
for (let i = 0; i < result.length; i++) {
try {
// console.log(result[i]);
setCampground(result[i]);
// campGround.push(result[i]);
} catch (error) {
console.log(error.message);
}
}
} else {
console.log("Error while selecting record from campground table. ");
}
console.log(`length after execution :: ${campGround.length}`);
campGround.forEach(function (value) {
console.log("Campground array");
console.log(value);
});
});
} else {
console.log("Error DataBase Not Connected!!! select statement");
}
});
function setCampground(value) {
this.campGround.push(value);
}
You have:
const campGround = [];
that is global variable (or module scope);
Then in the code you have a function
function setCampground(value) {
this.campGround.push(value);
}
which is also in global scope (or module scope)
Therefore this.campGround is not campGround;
Change this.campGround .push(value); into campGround .push(value); and everything should work now.

Can't return from a function

So what i am trying to do is, create a function, use mysql(don't care how, but i found an npm for it so using that for now.) to get information from my database and then feed my json with it. It works fine as long as the console.log() is in the right spot, but i have to return it so i have to move it further down. But when i do that, it won't show in my other file, which i need it to be at.
I have 2 of the basically same script, one is just for another faction.
- So i will only show one, as if i find a solution for one of them, i have a solution for both.
get_ally_online_players: function (guild) {
con.query("SELECT * FROM user_dbs WHERE guild='"+ guild +"'", function (err, result, fields) {
var con2 = mysql.createConnection({
host: result[0].host,
user: result[0].username,
password: result[0].password,
database: result[0].database
})
con2.connect()
con2.query("SELECT * FROM characters WHERE online='1' AND race=1 OR race=3 OR race=4 OR race=7 OR race=11", function (err, result, fields) {
allycount = 0
console.dir(result)
result.forEach(function(result) {
allycount = allycount+1
})
return allycount
});
con2.end()
});
}
Here is where i try to have it:
if(recieved.content === "!status")
{
var horde_players
var ally_players
horde_players == guilddb.get_horde_online_players("585919060722712670")
ally_players == guilddb.get_ally_online_players("585919060722712670")
console.log(guilddb.test())
//console.log(ally_players)
recieved.channel.send(ally_players + " : " + horde_players)
}
I have tried so many things... I've also read that you have to use callbacks since it's apparently going too fast, like it can't query before...
I'd like to stay away from the callback though, since it seems like a hassle to have inside the script. But if it's absolutely necessary, so be it. It returns with "undefined" btw. I have also tried to use promises instead and put a setTimeout function etc.
First of all, sorry about my English.
Actually you are commiting some mistakes.
You where commiting a mistake asigning values to horde_players and ally_players values
if (recieved.content === "!status") {
var horde_players
var ally_players
horde_players = guilddb.get_horde_online_players("585919060722712670")
ally_players = guilddb.get_ally_online_players("585919060722712670")
console.log(guilddb.test())
//console.log(ally_players)
recieved.channel.send(ally_players + " : " + horde_players)
}
With (==) you are comparing values, not setting.
Now lets talk about async operations.
I prepared an example. This is like in your case, you are trying to run two async operations that may finish at different times, but you need both of them finished before running something else. Try to run it:
function async1(id, callback) {
setTimeout(function() {
callback('The user with ' + id + ' is called Sergio');
}, 6000);
}
function async2(id, callback) {
setTimeout(function() {
callback('The user with ' + id + ' is called Jack');
}, 2000);
}
var result1;
var result2;
async1(1, function(result) {
result1 = result;
});
async2(2, function(result) {
result2 = result;
});
console.log('Finished result: ' + result1 + result2); // Finished result: undefined undefined
The finished result was run before finishing both async operations. Bad...
With callbacks, we need to nest the functions (if you had to do more async operations, you could lead into Callback Hell)
function async1(id, callback) {
setTimeout(function() {
callback('The user with ' + id + ' is called Sergio');
}, 6000);
}
function async2(id, callback) {
setTimeout(function() {
callback('The user with ' + id + ' is called Jack');
}, 2000);
}
var result1;
var result2;
async1(1, function(result) {
result1 = result;
async2(2, function(result) {
result2 = result;
console.log('Finished result: ' + result1 + result2); // 'Finished result: The user with 1 is called SergioThe user with 2 is called Jack
});
});
For your case, this would be my solution. Maybe I would improve more things like using const-let and ES6 features (async-await, arrow functions...), passing db connectors trought params... but maybe it's easier to you to understand now
var guilddb = {
get_horde_online_players: function(guild, callback) {
callback('Implement me!');
},
get_ally_online_players: function(guild, callback) {
con.query("SELECT * FROM user_dbs WHERE guild='" + guild + "'", function (err, result, fields) {
var con2 = mysql.createConnection({
host: result[0].host,
user: result[0].username,
password: result[0].password,
database: result[0].database
});
con2.connect();
con2.query("SELECT * FROM characters WHERE online='1' AND race=1 OR race=3 OR race=4 OR race=7 OR race=11", function (err, result, fields) {
var allycount = 0;
console.dir(result);
result.forEach(function(result) {
allycount = allycount+1
});
con2.end();
callback(allycount);
});
});
}
}
if (recieved.content === "!status") {
guilddb.get_horde_online_players("585919060722712670", function(result) {
var horde_players = result;
guilddb.get_ally_online_players("585919060722712670", function(result) {
var ally_players = result;
console.log(guilddb.test());
console.log(ally_players);
recieved.channel.send(ally_players + " : " + horde_players);
});
});
}
Hope it helps.
Your query is asynchronous so the function will implicitly return undefined before the query finishes.
Therefore, you will need to use callbacks or promises.
You can use callbacks like this:
// Accept a callback function as an argument
get_ally_online_players: function (guild, callback) {
con.query("SELECT * FROM user_dbs WHERE guild='"+ guild +"'", function (err, result, fields) {
var con2 = mysql.createConnection({
host: result[0].host,
user: result[0].username,
password: result[0].password,
database: result[0].database
})
con2.connect()
con2.query("SELECT * FROM characters WHERE online='1' AND race=1 OR race=3 OR race=4 OR race=7 OR race=11", function (err, result, fields) {
allycount = 0
console.dir(result)
result.forEach(function(result) {
allycount = allycount+1
})
// Pass the result to the callback function
callback(allycount)
})
con2.end()
})
}
...and then pass a callback function to get_ally_online_players that will receive the data when ready:
if (recieved.content === "!status") {
var horde_players
var ally_players
horde_players = guilddb.get_horde_online_players("585919060722712670")
// Pass a callback function that will receive the data when ready
guilddb.get_ally_online_players("585919060722712670", function(ally_players) {
console.log(ally_players)
recieved.channel.send(ally_players + " : " + horde_players)
})
}
I hope this helps.

Using Lodash to loop through https.get when parsing XML to JSON in Node

I'm trying to parse XML to JSON in Node. I'm using xml2js. I'd like to incorporate Lodash to loop through each number in an array and use the corresponding url to convert the XML to JSON. When I use the code below, I get a Non-whitespace before first tag error. Any idea what I'm doing wrong?
const no = [78787878,78787879, 787878780];
_.forEach(no, https.get('https://tsdrapi.uspto.gov/ts/cd/casestatus/'+no+'/info.xml', function (res) {
res.on('data', function (chunk) {
response_data += chunk;
});
res.on('end', function () {
parser.parseString(response_data, function (err, result) {
if (err) {
console.log('Got error: ' + err.message);
} else {
console.log(util.inspect(result, false, null));
}
});
});
res.on('error', function (err) {
console.log('Got error: ' + err.message);
});
}));
Honestly the forEach helper in LoDash is kind of silly. forEach is a prototype method of any Array instance. One problem is that these functional helpers are not designed to handle async flow control.
While there are a dozen ways to handle flow control the easiest would probably be to use caolan/async module's map() method.
You're code would look something like:
var no = [78787878,78787879, 787878780];
async.map(no, function(cb) {
https.get('https://tsdrapi.uspto.gov/ts/cd/casestatus/'+no+'/info.xml', function (res) {
var response_data = '';
res.on('data', function (chunk) {
response_data += chunk;
});
res.on('end', function () {
parser.parseString(response_data, function (err, result) {
if (err) {
cb(err);
} else {
cb(null, result);
}
});
});
res.on('error', cb);
})
}, function(err, results) {
if(err) {
console.log("Error occured: ", err);
}
else {
console.log("Results(array): ", results);
}
});
The difference here is that async maps the array to a function with a callback. This way you can gather the response from each request into an array and fire a callback when each request has responded. If one of them error's out the process stops and fires the final callback where the error is logged(or you can write logic to handle another way).

Process exited before completing request (Lambda + DynamoDB)

For some reason I am getting the Process exited before completing request error.
Here is my code:
var http = require('http');
var aws = require('aws-sdk');
var ddb = new aws.DynamoDB();
function getUser(userid) {
var q = ddb.getItem({
TableName: "clients",
Key: {
ClientID: { S: userid } }
}, function(err, data) {
if (err) {
console.log(err);
return err;
}
else {
console.log(data);
}
});
//console.log(q);
}
exports.handler = function(event, context) {
getUser('user23');
console.log("called DynamoDB");
};
After googling a few people suggested changing the time out to a higher amount. Which I did to one minute.
However the function only took:
Duration : 2542.23 ms
I have also checked and double checked the table name and the key name etc...
The console log has this :
2016-03-21T04:09:46.390Z - Received event
2016-03-21T04:09:46.751Z - called DynamoDB
2016-03-21T04:09:47.012Z - {}
END RequestId: id123
Can anyone see why this is not working?
Edit
As per the answer below I tried:
console.log('Loading event');
var AWS = require('aws-sdk');
var dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'});
exports.handler = function(event, context) {
console.log(JSON.stringify(event, null, ' '));
dynamodb.listTables(function(err, data) {
console.log(JSON.stringify(data, null, ' '));
});
var tableName = "clients";
var datetime = new Date().getTime().toString();
dynamodb.getItem({
TableName: tableName,
Key: {
ClientID: { S: "gr5f4sgnca25hki" } }
}, function(err, data) {
if (err) {
context.done('error','putting item into dynamodb failed: '+err);
}
else {
context.done(data);
}
});
};
but now my response is:
"errorMessage": "[object Object]"
What I am trying to do is this: Check if Item exists in database. Get the parameters from the entry if exists, then do something with the parameters
Can anyone help me?
First of all, context.done expects an Error object as the first argument, not a string containing the word "error".
Second, if the Error object is null or undefined, then the termination will be taken as a succeed.
Now, consider your callback function:
function (err, data)
{
if (err) {
context.done('error', 'putting item into dynamodb failed: ' + err);
}
else {
context.done(data);
}
}
If you have an error, then your lambda will terminate in a failure, which is expected, but the errorMessage you'll get would simply be "error", which isn't much informative.
If you don't have an error, then your lambda will also terminate in a failure, because you are passing in data as the first argument to context.done, and remember that the first argument is always the Error object.
To fix this, you can simply do:
function (err, data)
{
if (err) {
context.done(err);
} else {
context.done(null, data);
}
}
Or even better:
function (err, data)
{
context.done(err, data);
}
If you don't want to handle the item and just return it immediately, you can use context.done as your callback function to the DynamoDB operation:
dynamodb.getItem({
TableName: tableName,
Key: {
ClientID: { S: "gr5f4sgnca25hki" }
}
}, context.done);
You need to signal Lambda end of function.
Important
To properly terminate your Lambda function execution, you must call context.succeed(), context.fail(), or context.done() method. If you don't, either your Lambda function will continue to run until the Node.js event queue is empty, or your Lambda function times out.
Here is an example:
https://gist.github.com/markusklems/1e7218d76d7583f1f7b3
"errorMessage": "[object Object]"
can be solved by a small change as follows
function(err, data) {
if (err) {
context.done(err);
}
else {
context.succeed(data);
}
});
Note where context.succeed differs() from context.done()

Problem with mysql wrapper function

I'm playing with a Node.JS app for the first time, and so far I love it, but I'm having a problem...
I have written a wrapper function on the client.query function that simply allows me to pass a parameter and it gets the query from an array of allowed queries...
var runProcedure = function(proc, vars){
var params;
if(typeof vars != 'undefined'){
params.concat(eval('(' + vars + ')'));
}
this._client.query(queries[proc], params, function(err, results, fields){
if(err) { throw err; }
if(results){
return(results);
}else{
return "No data found.";
}
});
}
The function works correctly and if I console.log results, the data I want is there.. however, it's not getting returned to where I called it...
var data = runProcedure(procedureName, parameters);
console.log(data); // undefined
While troubleshooting, it seems that the query function is run asynchronously.... but this causes me a big problem. The runProcedure function is being called from within an http request handler.. so I need to be able to access the response variable. I guess I could pass it all the way down as a parameter... but that seems clumsy. What is the best code pattern to handle this? Should I set the response as a global var? can I run the mysql synchronously?
Cheers,
whiteatom
just pass your data to callback instead of returning with return
var runProcedure = function(proc, vars, callback) {
var params;
if(typeof vars != 'undefined'){
params.concat(eval('(' + vars + ')'));
}
this._client.query(queries[proc], params, function(err, results, fields){
if(err) { throw err; }
if(results){
callback(results);
}else{
callback('No data found.');
}
});
}
Now in http request handler:
// ...
function httpRequestHandler(req, resp)
{
//...
runProcedure(proc, vars, function(dbResp) {
if (dbResp === 'No data found.')
{
// handle error
} else {
// do something with result
}
})
}