How to promisify a MySql function using bluebird? - mysql

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() {} );

Related

Return MySql results from JavaScript Class

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

Custom express-validator

My custom-validator always return true although when result is not undefined and i have returned false in that case
const validatorOptions = {
customValidators: {
not_exist: (inputParam) => {
let qry = 'select * from Users where email = ?';
let exist= db.query(qry, inputParam, (err, result) => {
if (err)
throw err;
if (result) {
console.log("Exist");
return false;
} else
return true;
});
return exist;
}
}
};
I tried using Promise, but still it's not working.
const validatorOptions = {
customValidators: {
isUniqueEmail: (email) => {
function getRecord(email) {
return new Promise(function(resolve, reject) {
let qry = 'select * from Users where email = ?';
db.query(qry, email, (err, result) => {
if (err)
reject(err);
else {
resolve(result);
}
});
});
};
getRecord(email).then(function(res) {
return (res.length == 0);
}).catch((err) => { throw err; });;
}
}
};
req.checkBody('email', 'Email already exist').isUniqueEmail();
That is because you're returning the variable exist which is equal to db.query() (and always a truthy value).
I had some questions about this code (because I don't see how it could run in the current state):
Seems odd to have customValidators as a child to validatorOptions, is there a reason for this?
Is there a reason you're mixing camel and snake case?
Do you think the custom validator method name could be more descriptive as to its' purpose, such as isUniqueEmailAddress?
Why isn't the SQL statement concatenating the argument into the
Do you think this code should implement some SQL input cleansing for security reasons?
Does db.query() really expect 3 arguments??? (I would think it just needs SQL and callback)
Since db.query() is performing an asynchronous operation, have you considered using Promises?

Node.js express and mySQL data

I just started learning JavaScript and Node.JS and I'm really struggling with the concepts of callbacks. So I went on and tried to implement them to get mySQL data pushed to a site.
I began with this:
// connection stuff happened already. Connection works fine.
app.get('/home', function(req,res){
var sql = `select u.* from users u`;
var sql2 = `select u.* from users2 u`;
usersA = [];
usersB = [];
connection.query(sql, function(error, results, fields){
if (error) throw error;
results.forEach(function(user){
usersA.push({
"id":user.id,
"name":user.name,
"lastname":user.lastname
});
});
connection.query(sql2, function(error, results, fields){
if (error) throw error;
results.forEach(function(user){
usersB.push({
"id":user.id,
"name":user.name,
"lastname":user.lastname
});
});
res.render("index", {
usersA: usersA,
usersB: usersB
});
});
});
});
This works. But I feel like this is the wrong approach considering there could be way more than 2 queries.
I need to get both arrays filled before the index is rendered. And I'd like to achieve that a little more straightforward without nesting multiple queries within each other.
Maybe I'm just not used to code looking like that. If this is a valid approach even for 10 or more querys I'll just stick with it. It just feels wrong.
So I started looking into this SO thread and tried to somehow get things to work but it didn't:
function executeQuery(query, callback) {
connection.query(query, function (err, rows, fields) {
if (err) {
return callback(err, null);
} else {
return callback(null, rows);
}
})
}
function getResult(query,callback) {
executeQuery(query, function (err, rows) {
if (!err) {
callback(null,rows);
} else {
callback(true,err);
}
});
}
function getUsers(sqlQry){
getResult(sqlQry,function(err,rows){
if(!err){
return rows;
} else {
console.log(err);
}
});
}
With this prepared I tried the following:
var sql = `select u.* from users u`;
var sql2 = `select u.* from users2 u`;
app.get('/home', function(req,res){
res.render("index", {
usersA: getUsers(sql),
usersB: getUsers(sql2)
});
}
But my usersA/usersB are empty. I guess that's some kind of scoping/asynch problem as getUsers() returns before the query is executed.
From what I've read so far this might be a good place for promises.
I added an answer with my solution.
I found an answer to my question
I found this article on codeburst about Node.js and mySQL using promises and went trying it. So all the credit to them.
app.get('/home', function(req,res){
var db = new Database({
host : "someHost.someDomain",
user : "someUser",
password : "somePassword",
database : "someDatabase"
});
var sql = `select u.* from users u`;
var sql2 = `select u.* from users2 u`;
usersA = [];
usersB = [];
db.query(sql)
.then(rows => {
rows.forEach(function(user){
usersA.push({
"id":user.id,
"name":user.name,
"lastname":user.lastname
});
});
return db.query(sql2)
})
.then(rows => {
rows.forEach(function(user){
usersB.push({
"id":user.id,
"name":user.name,
"lastname":user.lastname
});
});
return db.close();
}, err => {
return db.close().then( () => { throw err; } )
})
.then( () => {
res.render("index", {
usersA: usersA,
usersB: usersB
});
}).catch( err => {
console.log(err);
} )
I don't really get how this works yet but I'll read into it. This allows for handling multiple nested queries with promises which are way easier to handle than simply nesting everything.
If anyone has another way of doing this or feels the need explaining what's happening here I'd very much appreaciate it!
For the sake of completion without visiting the URLs here is the mentioned database class:
class Database {
constructor( config ) {
this.connection = mysql.createConnection( config );
}
query( sql, args ) {
return new Promise( ( resolve, reject ) => {
this.connection.query( sql, args, ( err, rows ) => {
if ( err )
return reject( err );
resolve( rows );
} );
} );
}
close() {
return new Promise( ( resolve, reject ) => {
this.connection.end( err => {
if ( err )
return reject( err );
resolve();
} );
} );
}
}

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;
}

More reliable loop to update ObjectID in Mongo?

I am migrating from SQL to NOSQL but still want to maintain a separate record and use ObjectIDs to link in some cases. I have this loop which works... in part.
router.get('/col', function(req, res, next) {
var stream = Record.find().stream();
stream.on('data', function (doc) {
if(doc.oldcolid){
Collection.findOne({da: doc.oldcolid}, function(err, col){
doc.collectionId = col._id
doc.save()
console.log(col.name)
})
}
})
stream.on('error', function (err) {
console.log(err)
})
stream.on('close', function () {
console.log("done")
})
});
However, it seems to finish and miss many records.
> db.records.count({collectionId: null})
12130
> db.records.count({collectionId: {$exists: true}})
5882
> db.records.count({oldcolid: {$exists: true}})
18012
I stored the old ID from the MySQL database in both collections to do the link. There are no obvious errors but it consistently seems to fall over. I do not seem to hit the on('close') function either.
OK, so thinking about this in reverse was simpler.
var stream = Collection.find().stream();
stream.on('data', function (doc) {
console.log(doc.da)
stream.pause()
Record.update({oldcolid: doc.da}, {collectionId: doc._id}, { multi: true }, function (err, raw) {
if(err) {console.log(err)}
console.log(raw)
stream.resume()
})
})
stream.on('error', function (err) {
console.log(err)
})
stream.on('close', function () {
console.log("done")
})
Fewer operations, less trouble.