this is my first post on Stackoverflow, so please be kind.
I have a huge problem, which I couldn't fix by googling (which is pretty rare).
I want to create a simple error handling in my query, but it won't work.
Here's the code:
pool.query("SELECT password_hash FROM User WHERE email = ?",
req.body.EMailLogin, (error, results, fields) => {
if(error) {
// It executes the if aswell as the else statement and I dont know why (if(error) seems to be ignored even if its true)
} else {
// And then it crashes here, because password_hash is undefined
let hash = results[0].password_hash;
bcrypt.compare(req.body.PasswordLogin, hash, function(err, result) {
if (result == true) {
ses.user = req.body.EMailLogin;
req.session.cookie.expires = false;
req.session.save(() => {
return res.redirect('/index');
});
} else {
res.render(); // My Page for Wrong Password (ignore this)
}
});
}
}
);
Throw the error inside the if
if(error) {
throw error;
} else {
I think that the error is how you're passing the parameter, it should be an array:
pool.query("SELECT password_hash FROM User WHERE email = ?",
[req.body.EMailLogin],
I hope this fixes your problem.
You missed to check weather query return data or not and also you can pass values either using object or array(in your case, should be array)
pool.query("SELECT password_hash FROM User WHERE email = ?", [req.body.EMailLogin],
(error, results, fields) => {
if (error) {
// any error like wrong query, connection closed, etc.
// It executes the if aswell as the else statement and I dont know why (if(error) seems to be ignored even if its true)
} else if (results.length === 0) {
// email not found in database
// My Page for Wrong Email ???
} else {
// And then it crashes here, because password_hash is undefined
let hash = results[0].password_hash;
bcrypt.compare(req.body.PasswordLogin, hash, function (err, result) {
if (result == true) {
ses.user = req.body.EMailLogin;
req.session.cookie.expires = false;
req.session.save(() => {
return res.redirect('/index');
});
} else {
res.render(); // My Page for Wrong Password (ignore this)
}
});
}
}
);
Am trying to retrieve all the database records from a table called post using node js but the problem is that only one record is retrieved instead of all.
In php I can use while() loop to loop through the database record to get all data.
Currently, I do not know how to neatly loop through the database in nodejs to get all the records from database. Some Stackoverflow scholars suggest using await/async method but i do not know to to implement it on the code below to make it work. can someone help me fix the issue.
var connection = require('./config');
module.exports.getpost = function (req, res) {
connection.query('SELECT * FROM posts', function (error, results, fields) {
if (error) {
console.log('error');
res.json({
status : false,
message : 'there are some error with the query'
});
} else {
var postid = results[0].id;
var title = results[0].title;
var content = results[0].content;
var type = -1;
console.log(title);
// Checking user status
connection.query('SELECT count(*) as cntStatus,type FROM like_table WHERE userid= ? and postid=?', [userid,postid], function (error, results, fields) {
if (error) {
console.log('error');
res.json({
status : false,
message : 'there are some error with the query'
});
} else {
var total_count = results[0].cntStatus;
if(total_count > 0){
type = results[0].type;
}
var total_count = results[0].cntStatus;
var result = {
"id" : postid,
"title" : title,
"content" : content,
"type" : type,
"likes" : total_count
};
console.log('query okay');
res.json({
//data:results,
data : result
});
}
});
}
});
}
I'm assuming you're using mysql npm. In that case I'm not sure what is the problem in your case. Results param is an array of rows returned by your select statement. So you can use loop to iterate trough all the rows.
You don't actually need to use async/await (which doesn't have any advantage in terms of functionality but looks cleaner). But if you want to get rid of callbacks you need to wrap connection query into a promise or use mysql2 npm which has promise interface. Here is how you can iterate trough all the rows from your select using async/await instead of callback:
var connection = require('./config');
module.exports.getpost = async function (req, res) {
try {
const queryResult = await query('SELECT * FROM posts');
queryResult.forEach(row => {
console.log(row.title);
})
} catch (err) {
console.log('error');
res.json({
status: false,
message: 'there are some error with the query'
});
}
}
Please note that you need to use nodejs 8 to run the code with async/await.
Also you don't need to do another query inside of your posts query, you can merge those two using SQL join
async waterfall - Runs an array of functions in series, each passing their results to the next in the array. However, if any of the functions pass an error to the callback, the next function is not executed and the main callback is immediately called with the error.
var connection = require('./config');
var async = require('async');
module.exports.getpost = function (req, res) {
var arrayOfFuncs = [];
var func_1 = function(callback) {
connection.query('SELECT * FROM posts', function (error, results, fields) {
if (error) {
console.log('error');
callback(error, null);
} else {
var toPass = {};
toPass.postid = results[0].id;
toPass.title = results[0].title;
toPass.content = results[0].content;
toPass.type = -1;
callback(null, toPass);
}
})
}
arrayOfFuncs.push(func_1);
var func_2 = function(prevData, callback) {
connection.query('SELECT count(*) as cntStatus,type FROM like_table WHERE userid= ? and postid=?', [userid,prevData.postid], function (error, results, fields) {
if (error) {
console.log('error');
callback(error, null);
} else {
var total_count = results[0].cntStatus;
if(total_count > 0){
type = results[0].type;
}
var total_count = results[0].cntStatus;
var result = {
"id" : postid,
"title" : title,
"content" : content,
"type" : type,
"likes" : total_count
};
console.log('query okay');
callback(null, result);
}
});
}
arrayOfFuncs.push(func_2);
async.waterfall(arrayOfFuncs, function(errString, finalResult) {
if(errString) {
return res.send(errString);
} else {
return res.send(finalResult);
}
});
}
I am trying to create an authentication system using Hapi and MySQL, I am testing it using postman, and I am also logging the output of the query on the terminal console.
The thing is, the console outputs the query successfully, however, postman returns An internal server error occurred, and the console doesn't return any error. I'll send the handler function of my route, found below:
handler: async function(req, h) {
const pass = req.payload.password;
const username = req.payload.username;
var res;
res = await con.query("SELECT * FROM `Person` WHERE `Username` = ?", username,
(err, rows, fields) => {
if(err) {
console.log("Query Error: ", err, "!");
return err;
} else {
console.log("Query Successful!");
const person = JSON.parse(JSON.stringify(rows[0]));
console.log(person);
if(person != null) {
//const hashedPass = crypto.pbkdf2Sync(req.payload.password, person.salt, 10000, 64, 'sha1').toString('base64');
if(pass != person.Password) {
return boom.badRequest('Invalid username/password.');
} else {
var token = jwt.sign(person, config.jwtKey);
person.token = token;
return person;
}
} else {
return boom.badRequest('Invalid username/password. Failed.');
}
}
}
);
return res;
}
I solved the problem by adding another node_module that encapsulates the regular mysql node module functions with promises.
The package is called promise-mysql.
I Have two mysql queries that runs with promise.
The first one is updates information on a mysql table and then resolves the issue and calls the next mysql query. The problem is that, when it calls the next mysql query the promise returns UNDEFINED and I am not sure why. When I console.log it out in my node js server post request, it gives undefined. I documented on the code which areas are problems.
UpdateUserPath = (data) => new Promise((resolve,reject)=>{
data.UPDATE_DT = getDateTime();
db.query('UPDATE path UPDATE_DT = ? where Owner = ?',
[data.UPDATE_DT, data.Owner], function(err,results,fields){
if(err){
reject('Could not update user path');
}else{
if(results.affectedRows > 0){
data.ID = null;
data.UPDATE_DT = null;
// The problem is here, when this gets resolved it calls the other function SaveUserPath
resolve(saveUserPath(data));
}else{
reject('Could not update user path');
}
}
});
});
saveUserPath = (data) => new Promise((resolve, reject) => {
db.query('INSERT INTO path SET ?', data, function (error, results, fields) {
if (error) {
reject('Could not insert path');
}else{
var Id = results.insertId;
db.query('UPDATE path SET ORIG_ID = ? where ID = ?',[Id, Id], function(err,results,fields){
if(err){
reject('Could not insert row to path table - saveuserpath');
}else{
if(results.affectedRows > 0){
// THIS INFORMATION HERE IS UNDEFINED
return resolve(results[0]);
}else{
reject('Could not update path');
}
}
});
}
});
});
In the server it gets called like this.
getUserPath(req.session.userid).then((path_data)=>{
path_data.status = 1;
UpdateUserPath(path_data).then((result)=>{
console.log(result); // THIS IS UNDEFINED
});
});
I am wondering if resolve(saveUserPath(data)); is the right way to call another promise which is not outside in the server.
I was thinking of just doing it this way.
UpdateUserPath(path_data).then((result)=>{
saveUserPath(result).then((result_save) => {
console.log(result_save); // THIS MIGHT WORK
});
});
But why is the normal way wrong.
I have several guesses why it isn't working, but there are a number of things wrong such that it's better to just clean up the code to a much better design.
When combining multiple asynchronous callback-driven operations in an otherwise promise-based interface, you really want to promisify the underlying functions at their lowest level and then you can implement all your control flow and error handling using the benefits of promises. I think that will also make your problem go away and probably fix a couple other bugs too.
// promisify db.query()
// if a promisified interface is built into your database, use that one instead
db.queryP = function(q, d) {
return new Promise((resolve, reject) {
db.query(q, d, (err, results, fields) => {
if (err) {
reject(err);
} else {
resolve(results);
}
});
});
}
UpdateUserPath = function(data) {
data.UPDATE_DT = getDateTime();
let q = 'UPDATE path UPDATE_DT = ? where Owner = ?';
return db.queryP(q, [data.UPDATE_DT, data.Owner]).then(results => {
if (results.affectedRows > 0) {
data.ID = null;
data.UPDATE_DT = null;
return saveUserPath(data);
} else {
throw new Error('Could not update user path');
}
});
}
saveUserPath = function(data) {
let q = 'INSERT INTO path SET ?'
return db.queryP(q, data).then(results => {
let q2 = 'UPDATE path SET ORIG_ID = ? where ID = ?';
var Id = results.insertId;
return db.queryP(q2, [Id, Id]).then(results2 => {
if (results2.affectedRows > 0) {
return results2[0];
} else {
throw new Error('Could not update path');
}
});
});
}
getUserPath(req.session.userid).then(path_data => {
path_data.status = 1;
return UpdateUserPath(path_data);
}).then(result => {
// process result here
}).catch(err => {
// process error here
});
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;
}