I am brand new to NodeJS and am struggling to find a solution to making a reusable function to execute a query (passed via a parameter) and then simply return the response to the caller. I want to do it this way as there will be over 100 functions requiring database queries and it'll help reduce code size.
I’ve tried the following as a very primitive test, but the dbA_Read_Data() function always returns undefined, because it's asynchronous. However, 6 days later, and over 15 alternative callback/promise solutions that work for some haven't worked for me and I am no closer to solving this issue and accomplishing the following.
const { Databases } = require('../../utils/enums');
var mysql = require('mysql');
function getAllUsers() {
//This function would be called when an endpoint is hit in my HapiJS system.
var myQuery = "SELECT * FROM Users WHERE Account_Status== 'ACTIVE' ";
var response = dbA_Read_Data(myQuery);
return response;
}
//dbA => website database, contains users/permissions/etc
//Other databases... you get the idea
function dbA_Read_Data(query) {
dbConn = createConnection("localhost", Databases.db_A.name, Databases.db_A.username, Databases.db_A.password);
dbConn.connect();
dbConn.query(query, function(err, rows, fields) {
if (err) throw err;
var myResponseObject = {
query: query,
data: {
count: rows.length,
records: rows
}
}
});
}
function createConnection(host, database, user, password) {
var connection = mysql.createConnection({
host: host,
user: user,
password: password,
database: database
});
return connection;
}
How do I get the function dbA_Read_Data(query) to return the response object to the caller function?