howto Node module.exports - javascript

I want to separate the code for executing mysql query in Node, so I am trying to use the Revealing Module pattern here
/* pool -create connection pool mysql*/
var sqlQuery = function (sqlString) {
var _result = pool.getConnection(function (err, connection) {
/* error handling*/
connection.query(sqlString, function (err, rows) {
console.log(this.sql);
if (!err) {
return _result = rows; <============
}
connection.release();
});
return;
});
console.log(_result);
return { recordSet : _result }
};
module.exports = sqlQuery;
How can I return rows to my app.js. the code below for calling sqlQuery is not working
var SqlQuery = require(./path/to/sqlQueryFile);
var rows = SqlQuery('pass sql here').recordSet;
console.log(row);
res.json(rows);

Your code is asynchronous, but you're calling it synchronously.
If you wanted to do it like this, you'll also need to pass a callback to SqlQuery.
/* pool -create connection pool mysql*/
var sqlQuery = function (sqlString, callback) {
var _result = pool.getConnection(function (err, connection) {
/* error handling*/
connection.query(sqlString, function (err, rows) {
console.log(this.sql);
if (!err) {
callback(rows);
}
connection.release();
});
});
};
module.exports = sqlQuery;
And then call it with:
var SqlQuery = require(./path/to/sqlQueryFile);
var rows = SqlQuery('pass sql here', function(recordSet){
console.log(recordSet);
res.json(recordSet);
});
Edit: If you're using newer versions of JavaScript, you have a few more options.
If you have access to Promises, you can do this:
function sqlQuery (sqlString) {
return new Promise((resolve, reject) => {
pool.getConnection(function (err, connection) {
if (err) { return reject(err); } // error handling
connection.query(sqlString, function (err, rows) {
if (err) { return reject(err); }
resolve(rows);
connection.release();
});
});
});
}
module.exports = sqlQuery;
And then you'd use it like:
var SqlQuery = require(./path/to/sqlQueryFile);
SqlQuery('pass sql here')
.then(function(recordSet) {
console.log(recordSet);
res.json(recordSet);
})
.catch(function(err) {
// do your error handling
res.status(500).json({ err: 'Sorry there was an error' });
});
If you're using even newer JavaScript, you can use the async/await syntax (currently available via Babel, and I think in FireFox. Chrome in V55).
var SqlQuery = require(./path/to/sqlQueryFile);
async handleQuery(query) {
try {
var rows = await SqlQuery(query);
res.json(rows);
} catch (e) {
console.log('Error!', e);
}
}
To chain multiple queries together:
async handleQuery(query) {
try {
return await SqlQuery(query);
} catch (e) {
console.log('Error!', e);
}
}
var rows = await handleQuery('select * from tablename');
var rowsToReturn = await handleQuery('select id from another_table where name = "' + rows[0].name + '"');

Related

async await calling function node.js

I have this function, that queries my database, and then calls getNumOfSessionForTrainerClientList function:
var select = "select * from USERS WHERE ASSIGNED_TRAINER = ?"
mysqlconn.connect(function(err) {
if (err) {
console.error('Database connection failed: ' + err.stack);
return;
}
mysqlconn.query(select, [req.session.username], async function(err, rows) {
if (err) {
console.log(err);
} else {
let numOfSessionsLeft = {
numberOfSessionsLeftIs: 0
}
for (var i = 0; i < rows.length; i++) {
getNumOfSessionForTrainerClientList(req, res, rows[i], numOfSessionsLeft)
rows[i]["NUM_OF_SESSIONS_PER_MONTH"] = (parseInt(rows[i]["NUM_OF_SESSIONS_PER_MONTH"]) - numOfSessionsLeft.numberOfSessionsLeftIs)
console.log(numOfSessionsLeft)
}
}
mysqlconn.end();
})
})
and then inside the function getNumOfSessionForTrainerClientList, I have this:
async function getNumOfSessionForTrainerClientList(req, res, rows, numOfSessionsLeft) {
var getNumOfSessionForTrainerClientList = "select * from SCHEDULE WHERE CLIENT_USERNAME = ? AND ASSIGNED_TRAINER = ?"
mysqlconn.connect(async function(err) {
if (err) {
console.error('Database connection failed: ' + err.stack);
return;
}
mysqlconn.query(getNumOfSessionForTrainerClientList, [rows["USERNAME"], req.session.username], async function(err, sessionData) {
if (err) {
console.log(err);
} else {
numOfSessionsLeft.numberOfSessionsLeftIs = 1;
console.log(numOfSessionsLeft.numberOfSessionsLeftIs)
}
})
})
}
however, what is happening is that this line : rows[i]["NUM_OF_SESSIONS_PER_MONTH"] = (parseInt(rows[i]["NUM_OF_SESSIONS_PER_MONTH"]) - numOfSessionsLeft.numberOfSessionsLeftIs) is actually assigning 0 to rows[i]["NUM_OF_SESSIONS_PER_MONTH"] because that variable assignment is happening before the function call for getNumOfSessionForTrainerClientList finishes. So it is happening out of sync. I am not sure how to fix this, i have run into issues with async await before, but nothing like this. would appreciate the help.
For loop is synchronous in nature and hence doesn't wait for your method getNumOfSessionForTrainerClientList to return to continue the iteration.
The right way to do is:
Put your code inside an async block and use await() while calling getNumOfSessionForTrainerClientList call.
Second, your function getNumOfSessionForTrainerClientList should
return a promise.
Sample:
async function functionA() {
var select = "select * from USERS WHERE ASSIGNED_TRAINER = ?"
mysqlconn.connect(function(err) {
if (err) {
console.error('Database connection failed: ' + err.stack);
return;
}
mysqlconn.query(select, [req.session.username], async function(err, rows) {
if (err) {
console.log(err);
} else {
let numOfSessionsLeft = {
numberOfSessionsLeftIs: 0
}
for (var i = 0; i < rows.length; i++) {
await getNumOfSessionForTrainerClientList(req, res, rows[i], numOfSessionsLeft)
rows[i]["NUM_OF_SESSIONS_PER_MONTH"] = (parseInt(rows[i]["NUM_OF_SESSIONS_PER_MONTH"]) - numOfSessionsLeft.numberOfSessionsLeftIs)
console.log(numOfSessionsLeft)
}
}
mysqlconn.end();
})
})
}
And your function getNumOfSessionForTrainerClientList should look like:
async function getNumOfSessionForTrainerClientList(req, res, rows, numOfSessionsLeft) {
return new Promise((resolve, reject) => {
var getNumOfSessionForTrainerClientList = "select * from SCHEDULE WHERE CLIENT_USERNAME = ? AND ASSIGNED_TRAINER = ?"
mysqlconn.connect(async function(err) {
if (err) {
console.error('Database connection failed: ' + err.stack);
return reject(err);
}
mysqlconn.query(getNumOfSessionForTrainerClientList, [rows["USERNAME"], req.session.username], async function(err, sessionData) {
if (err) {
console.log(err);
return reject(err);
} else {
numOfSessionsLeft.numberOfSessionsLeftIs = 1;
console.log(numOfSessionsLeft.numberOfSessionsLeftIs)
return resolve();
}
})
})
})
}
And then call functionA() with whatever params you need to.
You call the function that includes async codes therefore getNumOfSessionForTrainerClientList doesn't depend the codes above (starts with(rows[i]["NUM_OF and console) what you should do is
Make the function async by returning prom
execute it with await keyword
async function trainerClientList(){
return new Promise((resolve,reject)=>{
var getNumOfSessionForTrainerClientList = "select * from SCHEDULE WHERE CLIENT_USERNAME = ? AND ASSIGNED_TRAINER = ?"
mysqlconn.connect(async function(err) {
if (err) {
console.error('Database connection failed: ' + err.stack);
resolve()
}
mysqlconn.query(getNumOfSessionForTrainerClientList, [rows["USERNAME"], req.session.username], async function(err, sessionData) {
if (err) {
console.log(err);
} else {
numOfSessionsLeft.numberOfSessionsLeftIs = 1;
console.log(numOfSessionsLeft.numberOfSessionsLeftIs)
}
})
})
resolve()
})
}
for (var i = 0; i < rows.length; i++) {
await trainerClientList()
rows[i]["NUM_OF_SESSIONS_PER_MONTH"] = (parseInt(rows[i]["NUM_OF_SESSIONS_PER_MONTH"]) - numOfSessionsLeft.numberOfSessionsLeftIs)
console.log(numOfSessionsLeft)
}

Nodejs api structure on calling sql helpers inside another helper all called by a controller

I'm studying to create a simple API with mysql. I've understood and implemented the simple structure in which the app call the router, that call the controller, that call the service. But now i'm developing a multiple tag service module and I've realized that I need to call the same sql queries services declared in it. I show you the code for a better understanding:
tag_service.js:
const mysql = require("../../config/database");
module.exports = {
insertTags: async (data, callBack) => {
const connection = await mysql.connection();
let results = '';
const tagsArray = data.tags.map(tag => [data.id_manager,data.cod_table,data.id_record,tag])
try {
//console.log("at insertCallout...");
await connection.query("START TRANSACTION");
results = await connection.query(
`INSERT INTO s_com_tags (id_manager,cod_table,id_record,tag)
VALUES (?,?,?)`,
[tagsArray]
);
await connection.query("COMMIT");
} catch (err) {
await connection.query("ROLLBACK");
//console.log('ROLLBACK at insertCallout', err);
throw err;
} finally {
await connection.release();
return callBack(null, results);
}
},
deleteTags: async (data, callBack) => {
//console.log(data);
let results = '';
const connection = await mysql.connection();
try {
//console.log("at deleteCallouts...");
await connection.query("START TRANSACTION");
results = await connection.query(
`DELETE FROM s_com_tags
WHERE cod_table = ? AND id_record = ? AND tag IN (?)`,
[data.code_table, data.id_record,data.tags]
);
//console.log(res);
await connection.query("COMMIT");
} catch (err) {
await connection.query("ROLLBACK");
//console.log('ROLLBACK at deleteCallouts', err);
throw err;
} finally {
await connection.release();
return callBack(null, Callouts);
}
},
};
controller's structure that will use the service:
module.exports = {
updateLabDesc: async (req, res, next) => {
try {
const body = req.body;
if(!body.internal_code){
updateLabDesc(body.manager, async (err, results) => {
if (err) {
return next(createError.InternalServerError())
}
});
}
updateTags(body, async (err, results) => {
if (err) {
return next(createError.InternalServerError())
}
return res.json({
success: (results ? 1 : 0 ),
message: (results || 0) + " LabDesc inserted successfully"
});
});
} catch (error) {
next(error)
}
},
};
But the update is something like
updateTag function => {
try {
const current_tags = await getTags(req.body);
let newTags = [];
let oldTags = [];
req.body.tags.forEach(tag => {
if(!current_tags.includes(tag))
newTags.push(tag)
});
await insertTags(newTags);
current_tags.tags.forEach(tag => {
if(!req.body.tags.includes(tag))
oldTags.push(tag)
});
await deleteTags(oldTags);
} catch (error) {
next(error)
}
},
Basically, the tag_service has insertTags and deleteTags but I need the updateTags to call these functions as well. The final controller will call insertTags, deleteTags and updateTags. How can I structure these calls?
It is a controller that could call 2 helpers (insertTag and deleteTags) and another helper (updateTags) that call these 2 helpers. Any ideas?

How to wrap node.js function to access them in organized way

So I come to this, I want to write into a DB and do other operations to work with my program logic, this is the guide that I'm following Node.js Class Creation:
//## This is my mysql_test.js file
function MySQL(){
var mysql = require('mysql');
var con = mysql.createConnection({
//data omitted
});
function AppendRecordset (req, res){
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query(req, function (err, res) {
if (err) throw err;
console.log("1 record inserted");
});
});
}
function UpdateRecordset (req, res) {
con.connect(function(err) {
if (err) throw err;
con.query(req, function (err, res) {
if (err) throw err;
console.log(result.affectedRows + " record(s) updated");
});
});
}
function DeleteRecordset (req, res){
con.connect(function(err) {
if (err) throw err;
con.query(req, function (err, res) {
if (err) throw err;
console.log("Number of records deleted: " + result.affectedRows);
});
});
}
function GetRecordset (req, res) {
con.connect(function(err) {
if (err) throw err;
con.query(req, function (err, res, fields) {
if (err) throw err;
console.log(result);
});
});
}
}
I then have in a separate file(s) my app logic, and want to use what of the above as an object/class so I wrote this accordingly to that guide:
//##this is inside my main app file
//declare the sql processor
require('./mysql_test.js');
var DB = MySQL();
DB.AppendRecordset(sql_string, res); //sql_string contains a valid SQL statement
But when I try to acces it using `` I get this error message: ReferenceError: MySQL is not defined what am I doing wrong?
I think these functions handle your routes, so I didn't change them. Because I don't know how your router is desined.
Create a file dbHangler.js and write this single function:
const mysql = require('mysql');
let con;
exports.execQuery = (query) => {
return new Promise((resolve, reject) => {
if(!con) {
con = mysql.createConnection({
//data omitted
});
}
con.connect(function(err) {
if(err) {
reject(err);
}
else {
console.log("Connected!");
con.query(query, function (err, res) {
if (err) {
reject(err);
}
else {
resolve(res);
}
});
}
});
});
};
In your dedicated.js file, now you can write:
const dbObject = require('path/to/dbHandler');
function AppendRecordset (req, res){
dbObject.execQuery(req)
.then(result => {
console.log(result.affectedRows + " record(s) updated");
})
.catch(error => {
// handle error
});
}
function AppendRecordset (req, res){
dbObject.execQuery(req)
.then(result => {
console.log("Number of records deleted: " + result.affectedRows);
})
.catch(error => {
// handle error
});
}
function AppendRecordset (req, res){
dbObject.execQuery(req)
.then(result => {
console.log(result);
})
.catch(error => {
// handle error
});
}
UPDATE
I hope this one helps you.
DbHandler.js
const mysql = require('mysql');
class DbHandler {
constructor(config) {
let self = this;
self.dbConfig = config;
self.connection = mysql.createConnection({
//data omitted
});
}
queryExecuter(query) {
let self = this;
return new Promise((resolve, reject) => {
self.connection.connect(function (err) {
if (err) {
reject(err);
}
else {
console.log("Connected!");
self.connection.query(query, function (err, res) {
if (err) {
reject(err);
}
else {
resolve(res);
}
});
}
});
});
}
AppendRecordset(query) {
let self = this;
return self.queryExecuter(query)
.then(result => {
console.log("1 record inserted");
return result;
})
.catch(error => {
// handle error
throw error;
});
}
UpdateRecordset(query) {
let self = this;
return self.queryExecuter(query)
.then(result => {
console.log(result.affectedRows + " record(s) updated");
return result;
})
.catch(error => {
// handle error
throw error;
});
}
// and other functions
}
module.exports = DbHandler;
And use it like below:
let DB = require('/path/to/DbHandler');
let myDb = new DB(/* db config */);
db.UpdateRecordset('your query')
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
});

I'm learning how to use asnyc in Node. Why doesn't my code return anything (logs, errors) to console?

I have the following code which I'm using to learn how to transition from callbacks, through to async, then moving onto promises and finally await.
For the first time, I'm really struggling to understand why I get nothing at all returned to the console.
I have several logging events in place, but these never trigger inside the code, and non of the errors are thrown / exceptions raised.
I have put in additional logging outside the functions to demonstrate that the files running when requesting eg, nodemon app.js from the terminal. However, the terminal hangs on 'starting'.
What am I doing wrong?
In addition to the code here, I have tried extensively wrapping different parts in try / catch blocks, but nothing is ever returned.
index.js:
const mysql = require('mysql');
const async = require('async');
const dbConfig = require('./db');
const employees = require('./employees');
async.series(
[
function(callback) {
mysql.createConnection(dbConfig, function(err) {
callback(err);
});
},
function(callback) {
employees.getEmployee(101, function(err, emp) {
if (err) {
callback(err);
return;
}
console.log(emp);
});
}
],
function(err) {
if (err) {
console.log(err);
}
}
);
employees.js:
const mysql = require('mysql');
const async = require('async');
function getEmployee(empId, getEmployeeCallback) {
async.waterfall(
[
function(callback) {
mysql.createConnection(function(err, conn) {
if (err) {
console.log('Error getting connection', err);
} else {
console.log('Connected to database');
}
callback(err, conn);
});
},
function(conn, callback) {
conn.execute(
`select *
from employees`,
function(err, result) {
if (err) {
console.log('Error executing query', err);
} else {
console.log('Query executed');
}
callback(err, conn, result);
}
);
}
],
function(err, conn, result) {
if (err) {
getEmployeeCallback(err);
} else {
getEmployeeCallback(null, result.rows[0]);
}
// If error getting conn, no need to close.
if (conn) {
conn.close(function(err) {
if (err) {
console.log('Error closing connection', err);
} else {
console.log('Connection closed');
}
});
}
}
);
}
module.exports.getEmployee = getEmployee;
db.js:
var mysql = require('mysql');
var connection = mysql.createConnection({
host:'localhost',
user:'developer',
password:'superseceretpassword',
database:'testing'
});
connection.connect(function(err) {
if (err) throw err;
});
module.exports = connection;

Node Js callback return function

I want to return database value in node js and pass as a variable in ejs file.
Bellow is the code, Which I used. it did not return value.
function getExternalLocation(cb) {
mssql.connect(msSqlSettings, function (err ) {
if (err) {
cb(err);
}
var getQuery = "SELECT [Title] FROM [dbo].[StyleTemplates] " ;
//console.log(getQuery);
var request = new mssql.Request();
// query to the database and get the data
request.query(getQuery, function (err, rows) {
mssql.close();
cb(err, rows);
});
});
}
exports.eejsBlock_editbarMenuLeft = function (hook_name, args, cb) {
var userData = getExternalLocation(args, function(err, rows) {});
args.content = args.content + eejs.require(
'ep_resources/templates/editbarButtons.ejs', {
userData: userData
});
return cb();
})
userData did not return any value.
var userData = getExternalLocation(args, function(err, rows) {});
I don't think userData will get right data in async function, there is no await, so you can try to get data in callback.
getExternalLocation(args, function(err, rows) {
var userData = rows;
args.content = args.content + eejs.require(
'ep_resources/templates/editbarButtons.ejs', {
userData: userData
});
});

Categories