Return MySql results from JavaScript Class - mysql

I am having an issue returning results from a Express JS model. I think my problem is a lack of understanding of callbacks and JS Classes. I just can't seem to make it work.
I have the following code.
From the server.js I have this route:
app.get('/api/v1/loralocations/:id', LoraLocation.getOne);
Which calls the Controller action below
getOne(req, res) {
const lora_location = LoraLocationModel.findOne(req.params.id);
if (!lora_location) {
return res.status(404).send({'message': 'LoraLocation not found'});
}
return res.status(200).send(lora_location);
},
.
.
.
Model
var pool = require('./mysqlDb.js');
import moment from 'moment';
class LoraLocation {
/**
* class constructor
* #param {object} data
*/
constructor() {
}
findOne(id) {
var sql = ('SELECT test FROM Test WHERE id = ?');
pool.query(sql, [id], function (err, results, fields) {
if (err) return err;
console.log(results); //works
return results; //nope
});
}
The console.log returns the results, but nothing is returned to the controller. I have gone through a number of posts but can't seem to find a solution. I think maybe I need a callback in the controller also?
Would this be a fairly standard pattern for a simple API project?
Thanks

You are using callback incorrectly.
either you can use async/await which is a good option or if you want to stick with callbacks then you need to return callback function.
controllers
const lora_location = LoraLocationModel.findOne(req.params.id, function (err, data) => {
});
in the model it should be
findOne(id, cb) {
var sql = ('SELECT test FROM Test WHERE id = ?');
pool.query(sql, [id], function (err, results, fields) {
if (err) cb(err, []);
console.log(results); //works
cb(null, results);
});
}
you can get more details for callbacks in this link
https://medium.com/better-programming/callbacks-in-node-js-how-why-when-ac293f0403ca

Related

Node Js asyncronic mysql query

I´m trying to do an asynchronous query in NodeJS but keep getting undefined as a result, my code is:
async function Nuevo_Parametro() {
sqlStr = "select * from Parametros limit 10";
conCasos.query(sqlStr, function(err, Resultado, fields) {
if (err) throw err;
return Resultado;
});
}
Nuevo_Parametro().then(Resultado => {
console.log(Resultado);
});
What am I doing wrong?
Thanks in advance
you're mixing callback styles with Promises. The mysql function does not return a Promise, so you can't concatenate it. It uses a callback style - meaning the "async" part is executed in that callback you provide as a parameter.
What you need to do is wrap it up with a Promise and return that. Something along the lines of the following
function Nuevo_Parametro() {
sqlStr="select * from Parametros limit 10"
return new Promise((resolve, reject) => {
conCasos.query(sqlStr, function(err, Resultado,fields) {
if (err) {
return reject(err)
};
resolve(Resultado);
})
})
}
Nuevo_Parametro().then(Resultado => {
console.log(Resultado)
})
Here we return a promise we're creating, and in the callback query offers, I'm resolving it. I kept the variables and property names as they are for simplicity.
If you're going to use extensively the queries, perhaps it might be tedious to be newing promises everytime, so as it's mentioned in this github ticket you can use a wrapper like this one
or maybe use the native promisify utility as this comment states
const fn = util.promisify(connection.query).bind(connection);
const rows = await fn('SELECT col1, col2 FROM users WHERE email = ?', [email]);

How to return result of db from a nested functions in nodejs

I want the result on other file but not getting how to return it
function getUsers(){
console.log("Fetching all user data");
const connection = getConnection();
const sql = "SELECT * FROM users";
var result = connection.query(sql,(err, rows, fields) =>{
if(err){
console.log("Failed to get users data");
res.sendStatus(500);
throw err;
}
console.log("Fetched Users Successfully");
return rows;
})
return result;
}
This is a standard asynchronous function problem.
return rows will not assign rows to the result variable. Second argument of query() function is a callback function and it indicates a block of code that will be executed after rows are fetched. It means that result of the query is only visible inside callback block.
You can fix it in 2 ways:
Write all your code that uses SQL result inside callback function block (You can call another function at that point and pass result as argument for example).
This method is simpler if you are new to javascript programming. I see that you want to use function getUsers() in another place. If you choose this approach, best way would probably be to pass a callback to the getUsers() function and then invoke it in the callback of the query() method.
Example:
getUsers(callback){
const connection = getConnection();
const sql = "SELECT * FROM users";
connection.query(sql,(err, rows, fields) => callback(rows))
}
mainFunction(req,res){
getUsers(doSomethingWithUsers)
}
doSomethingWithUsers(users){
...
}
This is of course, oversimplified pattern, but the idea should be clear.
Research about promises and how they handle async functions. This will require you to "wrap" you function body into Promise object type.
They will allow you to write something like this:
mainFunction(){
getUsers().then(result => ....);
// or even
const users = await getUsers();
}
EDIT:
To wrap "return value of promise", or as we say "to resolve a promise", you can wrap function the following way:
function getUsers(){
console.log("Fetching all user data");
const connection = getConnection();
const sql = "SELECT * FROM users";
return new Promise( (resolve,reject) => {
var result = connection.query(sql,(err, rows, fields) =>{
if(err){
// this will cause promise to "fail"
reject(err);
}
console.log("Fetched Users Successfully");
// this will tell javascript that promise is finished
// and rows are accesable in then()
resolve(rows);
})
})
}
function mainFunction(){
const result = getUsers()
.then(rows =>{/** this will happen if resolve(rows) is called */})
.catch(error => {/** this will be executed if reject(err) happens
*/});
}
// or... (Try/Catch is required since "await" silently fails
async function asyncMainFunction(){
try{
const rows = await getUsers();
// You can use rows from resolve() here;
}catch(error){
// here, reject is called
}
}
Here is a link where you can read more about promises:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
You are not getting the result because the code is asynchronous. So, you have to use async/await to get the result. Your code should look like this:-
async function getUsers(){
console.log("Fetching all user data");
const connection = await getConnection();
const sql = "SELECT * FROM users";
try {
var result = await connection.query(sql);
console.log("Fetched Users Successfully");
return result;
} catch (err) {
console.log("Failed to get users data");
res.sendStatus(500);
throw err;
}
}
Finally, call this function like this:-
var output = await getUsers();
But make sure that you call this line in an async function.
Hope this helps!
create file for function : getUsers.js
module.exports = async getUsers(){
const connection = getConnection();
const sql = "SELECT * FROM users";
var myPromise = () => {
return new Promise((resolve, reject) => {
connection.query(sql, query.params, function (error, results, fields) {
error ? reject(error) : resolve(results);
})
});
}
var result = await (myPromise());
return result;
}
require this file and call function :
var getUsers = require('..path to getUsers');
var data = getUsers().then((data)=>{
}).catch((error)=>{
console.log('error',error)
return error;
});
using callback :
or using callback function :
module.exports = function getUsers(callback){
const connection = getConnection();
const sql = "SELECT * FROM users";
connection.query(sql, query.params, function (error, results, fields) {
if(error){ callback(error,null)}
if(!error && results){
callback(null,results)
}
});
}
require file :
var getUsers = require('..path to getUsers');
call it this way :
getUsers(err,data)=>{
if(err){
return res.send(err);
}
if(!err && data){
return res.send(data);
}
}
function getUsers(callback) {
console.log("Fetching all user data");
const connection = getConnection();
const sql = "SELECT * FROM users";
connection.query(sql, (err, rows, fields) => {
if (err) {
console.log("Failed to get users data");
res.sendStatus(500);
callback(err, null);
}
console.log("Fetched Users Successfully");
callback(null, rows)
})
}
// USE ABOVE FUNCTION AS BELOW...
getUsers(function(err, rows) {
if(err){
console.error(err);
}
console.log(rows);
})

Use promise to process MySQL return value in node.js

I have a python background and is currently migrating to node.js. I have problem adjusting to node.js due to its asynchronous nature.
For example, I am trying to return a value from a MySQL function.
function getLastRecord(name)
{
var connection = getMySQL_connection();
var query_str =
"SELECT name, " +
"FROM records " +
"WHERE (name = ?) " +
"LIMIT 1 ";
var query_var = [name];
var query = connection.query(query_str, query_var, function (err, rows, fields) {
//if (err) throw err;
if (err) {
//throw err;
console.log(err);
logger.info(err);
}
else {
//console.log(rows);
return rows;
}
}); //var query = connection.query(query_str, function (err, rows, fields) {
}
var rows = getLastRecord('name_record');
console.log(rows);
After some reading up, I realize the above code cannot work and I need to return a promise due to node.js's asynchronous nature. I cannot write node.js code like python. How do I convert getLastRecord() to return a promise and how do I handle the returned value?
In fact, what I want to do is something like this;
if (getLastRecord() > 20)
{
console.log("action");
}
How can this be done in node.js in a readable way?
I would like to see how promises can be implemented in this case using bluebird.
This is gonna be a little scattered, forgive me.
First, assuming this code uses the mysql driver API correctly, here's one way you could wrap it to work with a native promise:
function getLastRecord(name)
{
return new Promise(function(resolve, reject) {
// The Promise constructor should catch any errors thrown on
// this tick. Alternately, try/catch and reject(err) on catch.
var connection = getMySQL_connection();
var query_str =
"SELECT name, " +
"FROM records " +
"WHERE (name = ?) " +
"LIMIT 1 ";
var query_var = [name];
connection.query(query_str, query_var, function (err, rows, fields) {
// Call reject on error states,
// call resolve with results
if (err) {
return reject(err);
}
resolve(rows);
});
});
}
getLastRecord('name_record').then(function(rows) {
// now you have your rows, you can see if there are <20 of them
}).catch((err) => setImmediate(() => { throw err; })); // Throw async to escape the promise chain
So one thing: You still have callbacks. Callbacks are just functions that you hand to something to call at some point in the future with arguments of its choosing. So the function arguments in xs.map(fn), the (err, result) functions seen in node and the promise result and error handlers are all callbacks. This is somewhat confused by people referring to a specific kind of callback as "callbacks," the ones of (err, result) used in node core in what's called "continuation-passing style", sometimes called "nodebacks" by people that don't really like them.
For now, at least (async/await is coming eventually), you're pretty much stuck with callbacks, regardless of whether you adopt promises or not.
Also, I'll note that promises aren't immediately, obviously helpful here, as you still have a callback. Promises only really shine when you combine them with Promise.all and promise accumulators a la Array.prototype.reduce. But they do shine sometimes, and they are worth learning.
I have modified your code to use Q(NPM module) promises.
I Assumed your 'getLastRecord()' function that you specified in above snippet works correctly.
You can refer following link to get hold of Q module
Click here : Q documentation
var q = require('q');
function getLastRecord(name)
{
var deferred = q.defer(); // Use Q
var connection = getMySQL_connection();
var query_str =
"SELECT name, " +
"FROM records " +
"WHERE (name = ?) " +
"LIMIT 1 ";
var query_var = [name];
var query = connection.query(query_str, query_var, function (err, rows, fields) {
//if (err) throw err;
if (err) {
//throw err;
deferred.reject(err);
}
else {
//console.log(rows);
deferred.resolve(rows);
}
}); //var query = connection.query(query_str, function (err, rows, fields) {
return deferred.promise;
}
// Call the method like this
getLastRecord('name_record')
.then(function(rows){
// This function get called, when success
console.log(rows);
},function(error){
// This function get called, when error
console.log(error);
});
I am new to Node.js and promises. I was searching for a while for something that will meet my needs and this is what I ended up using after combining several examples I found. I wanted the ability to acquire connection per query and release it right after the query finishes (querySql), or to get a connection from pool and use it within Promise.using scope, or release it whenever I would like it (getSqlConnection).
Using this method you can concat several queries one after another without nesting them.
db.js
var mysql = require('mysql');
var Promise = require("bluebird");
Promise.promisifyAll(mysql);
Promise.promisifyAll(require("mysql/lib/Connection").prototype);
Promise.promisifyAll(require("mysql/lib/Pool").prototype);
var pool = mysql.createPool({
host: 'my_aws_host',
port: '3306',
user: 'my_user',
password: 'my_password',
database: 'db_name'
});
function getSqlConnection() {
return pool.getConnectionAsync().disposer(function (connection) {
console.log("Releasing connection back to pool")
connection.release();
});
}
function querySql (query, params) {
return Promise.using(getSqlConnection(), function (connection) {
console.log("Got connection from pool");
if (typeof params !== 'undefined'){
return connection.queryAsync(query, params);
} else {
return connection.queryAsync(query);
}
});
};
module.exports = {
getSqlConnection : getSqlConnection,
querySql : querySql
};
usage_route.js
var express = require('express');
var router = express.Router();
var dateFormat = require('dateformat');
var db = require('../my_modules/db');
var getSqlConnection = db.getSqlConnection;
var querySql = db.querySql;
var Promise = require("bluebird");
function retrieveUser(token) {
var userQuery = "select id, email from users where token = ?";
return querySql(userQuery, [token])
.then(function(rows){
if (rows.length == 0) {
return Promise.reject("did not find user");
}
var user = rows[0];
return user;
});
}
router.post('/', function (req, res, next) {
Promise.resolve().then(function () {
return retrieveUser(req.body.token);
})
.then(function (user){
email = user.email;
res.status(200).json({ "code": 0, "message": "success", "email": email});
})
.catch(function (err) {
console.error("got error: " + err);
if (err instanceof Error) {
res.status(400).send("General error");
} else {
res.status(200).json({ "code": 1000, "message": err });
}
});
});
module.exports = router;
I am still a bit new to node, so maybe I missed something let me know how it works out. Instead of triggering async node just forces it on you, so you have to think ahead and plan it.
const mysql = require('mysql');
const db = mysql.createConnection({
host: 'localhost',
user: 'user', password: 'password',
database: 'database',
});
db.connect((err) => {
// you should probably add reject instead of throwing error
// reject(new Error());
if(err){throw err;}
console.log('Mysql: Connected');
});
db.promise = (sql) => {
return new Promise((resolve, reject) => {
db.query(sql, (err, result) => {
if(err){reject(new Error());}
else{resolve(result);}
});
});
};
Here I am using the mysql module like normal, but instead I created a new function to handle the promise ahead of time, by adding it to the db const. (you see this as "connection" in a lot of node examples.
Now lets call a mysql query using the promise.
db.promise("SELECT * FROM users WHERE username='john doe' LIMIT 1;")
.then((result)=>{
console.log(result);
}).catch((err)=>{
console.log(err);
});
What I have found this useful for is when you need to do a second query based on the first query.
db.promise("SELECT * FROM users WHERE username='john doe' LIMIT 1;")
.then((result)=>{
console.log(result);
var sql = "SELECT * FROM friends WHERE username='";
sql = result[0];
sql = "';"
return db.promise(sql);
}).then((result)=>{
console.log(result);
}).catch((err)=>{
console.log(err);
});
You should actually use the mysql variables, but this should at least give you an example of using promises with mysql module.
Also with above you can still continue to use the db.query the normal way anytime within these promises, they just work like normal.
Hope this helps with the triangle of death.
You don't need to use promises, you can use a callback function, something like that:
function getLastRecord(name, next)
{
var connection = getMySQL_connection();
var query_str =
"SELECT name, " +
"FROM records " +
"LIMIT 1 ";
var query_var = [name];
var query = connection.query(query_str, query_var, function (err, rows, fields) {
//if (err) throw err;
if (err) {
//throw err;
console.log(err);
logger.info(err);
next(err);
}
else {
//console.log(rows);
next(null, rows);
}
}); //var query = connection.query(query_str, function (err, rows, fields) {
}
getLastRecord('name_record', function(err, data) {
if(err) {
// handle the error
} else {
// handle your data
}
});
Using the package promise-mysql the logic would be to chain promises using then(function(response){your code})
and
catch(function(response){your code}) to catch errors from the "then" blocks preceeding the catch block.
Following this logic, you will pass query results in objects or arrays using return at the end of the block. The return will help passing the query results to the next block. Then, the result will be found in the function argument (here it is test1). Using this logic you can chain several MySql queries and the code that is required to manipulate the result and do whatever you want.
the Connection object is created to be global because every object and variable created in every block are only local. Don't forget that you can chain more "then" blocks.
var config = {
host : 'host',
user : 'user',
password : 'pass',
database : 'database',
};
var mysql = require('promise-mysql');
var connection;
let thename =""; // which can also be an argument if you embed this code in a function
mysql.createConnection(config
).then(function(conn){
connection = conn;
let test = connection.query('select name from records WHERE name=? LIMIT 1',[thename]);
return test;
}).then(function(test1){
console.log("test1"+JSON.stringify(test1)); // result of previous block
var result = connection.query('select * from users'); // A second query if you want
connection.end();
connection = {};
return result;
}).catch(function(error){
if (connection && connection.end) connection.end();
//logs out the error from the previous block (if there is any issue add a second catch behind this one)
console.log(error);
});
To answer your initial question: How can this be done in node.js in a readable way?
There is a library called co, which gives you the possibility to write async code in a synchronous workflow. Just have a look and npm install co.
The problem you face very often with that approach, is, that you do not get Promise back from all the libraries you like to use. So you have either wrap it yourself (see answer from #Joshua Holbrook) or look for a wrapper (for example: npm install mysql-promise)
(Btw: its on the roadmap for ES7 to have native support for this type of workflow with the keywords async await, but its not yet in node: node feature list.)
This can be achieved quite simply, for example with bluebird, as you asked:
var Promise = require('bluebird');
function getLastRecord(name)
{
return new Promise(function(resolve, reject){
var connection = getMySQL_connection();
var query_str =
"SELECT name, " +
"FROM records " +
"WHERE (name = ?) " +
"LIMIT 1 ";
var query_var = [name];
var query = connection.query(query_str, query_var, function (err, rows, fields) {
//if (err) throw err;
if (err) {
//throw err;
console.log(err);
logger.info(err);
reject(err);
}
else {
resolve(rows);
//console.log(rows);
}
}); //var query = connection.query(query_str, function (err, rows, fields) {
});
}
getLastRecord('name_record')
.then(function(rows){
if (rows > 20) {
console.log("action");
}
})
.error(function(e){console.log("Error handler " + e)})
.catch(function(e){console.log("Catch handler " + e)});
May be helpful for others, extending #Dillon Burnett answer
Using async/await and params
db.promise = (sql, params) => {
return new Promise((resolve, reject) => {
db.query(sql,params, (err, result) => {
if(err){reject(new Error());}
else{resolve(result);}
});
});
};
module.exports = db;
async connection(){
const result = await db.promise("SELECT * FROM users WHERE username=?",[username]);
return result;
}

How to promisify a MySql function using bluebird?

Some time ago I decided to switch from PHP to node. In my first projects I didn't want to use any ORM since I thought that I didn't need to complicate my life so much learning another thing (at the moment I was learning node and angular) therefor I decided to use mysql package without anything else. It is important to say that I have some complex queries and I didn't want to learn from sctratch how to make them work using one of the 9000 ORM node have, This is what I've been doing so far:
thing.service.js
Thing.list = function (done) {
db.query("SELECT * FROM thing...",function (err,data) {
if (err) {
done(err)
} else {
done(null,data);
}
});
};
module.exports = Thing;
thing.controler.js
Thing = require('thing.service.js');
Thing.list(function (err,data) {
if (err) {
res.status(500).send('Error D:');
} else {
res.json(data);
}
});
how can I promisify this kind of functions using bluebird ? I've already tried but .... here I am asking for help. This is what I tried
var Thing = Promise.promisifyAll(require('./models/thing.service.js'));
Thing.list().then(function(){})
I have done this way and it is working fine.
const connection = mysql.createConnection({.....});
global.db = Bluebird.promisifyAll(connection);
db.queryAsync("SELECT * FROM users").then(function(rows){
console.log(rows);});
I have never had much luck with promisifyAll and IMO I prefer to handle my internal checks manually. Here is an example of how I would approach this:
//ThingModule
var Promises = require('bluebird');
Things.list = function(params) {
return new Promises(function(resolve, reject) {
db.query('SELECT * FROM thing...', function(err, data) {
return (err ? reject(err) : resolve(data));
});
});
}
//usage
var thinger = require('ThingModule');
thinger.list().then(function(data) {
//do something with data
})
.error(function(err) {
console.error(err);
})
You can also create a function that fires SQL like this :-
function sqlGun(query, obj, callback) {
mySQLconnection.query(query, obj, function(err, rows, fields) {
if (err) {
console.log('Error ==>', err);
// throw err;
return (err, null);
}
console.log(query)
if (rows.length) {
return callback(null, rows);
} else {
return callback(null, [])
}
});
}
Where mySQLconnection is the connection object you get after mysql.createConnection({}).
After that, you can promisify the function and use the promise like below :-
var promisified = Promise.promisify(sqlGun);
promisified(query, {}).then( function() {} );

Node.js returning result from MySQL query

I have the following function that gets a hexcode from the database
function getColour(username, roomCount)
{
connection.query('SELECT hexcode FROM colours WHERE precedence = ?', [roomCount], function(err, result)
{
if (err) throw err;
return result[0].hexcode;
});
}
My problem is that I am returning the result in the callback function but the getColour function doesn't return anything. I want the getColour function to return the value of result[0].hexcode.
At the moment when I called getColour it doesn't return anything
I've tried doing something like
function getColour(username, roomCount)
{
var colour = '';
connection.query('SELECT hexcode FROM colours WHERE precedence = ?', [roomCount], function(err, result)
{
if (err) throw err;
colour = result[0].hexcode;
});
return colour;
}
but of course the SELECT query has finished by the time return the value in colour
You have to do the processing on the results from the db query on a callback only. Just like.
function getColour(username, roomCount, callback)
{
connection.query('SELECT hexcode FROM colours WHERE precedence = ?', [roomCount], function(err, result)
{
if (err)
callback(err,null);
else
callback(null,result[0].hexcode);
});
}
//call Fn for db query with callback
getColour("yourname",4, function(err,data){
if (err) {
// error handling code goes here
console.log("ERROR : ",err);
} else {
// code to execute on data retrieval
console.log("result from db is : ",data);
}
});
If you want to use promises to avoid the so-called "callback hell" there are various approaches.
Here's an example using native promises and the standard MySQL package.
const mysql = require("mysql");
//left here for testing purposes, although there is only one colour in DB
const connection = mysql.createConnection({
host: "remotemysql.com",
user: "aKlLAqAfXH",
password: "PZKuFVGRQD",
database: "aKlLAqAfXH"
});
(async () => {
connection.connect();
const result = await getColour("username", 2);
console.log(result);
connection.end();
})();
function getColour(username, roomCount) {
return new Promise((resolve, reject) => {
connection.query(
"SELECT hexcode FROM colours WHERE precedence = ?",
[roomCount],
(err, result) => {
return err ? reject(err) : resolve(result[0].hexcode);
}
);
});
}
In async functions, you are able to use the await expression which will pause the function execution until a Promise is resolved or rejected. This way the getColour function will return a promise with the MySQL query which will pause the main function execution until the result is returned or a query error is thrown.
A similar but maybe more flexible approach might be using a promise wrapper package of the MySQL library or even a promise-based ORM.