Skip to content

Instantly share code, notes, and snippets.

@Slurpgoose
Last active January 3, 2023 19:25
Show Gist options
  • Save Slurpgoose/f1af109c5ef87b3cd138ce1f9343632d to your computer and use it in GitHub Desktop.
Save Slurpgoose/f1af109c5ef87b3cd138ce1f9343632d to your computer and use it in GitHub Desktop.
A method to wrap your node application with a mysql pool.
/*
Created with refrence from
https://gist.github.com/binki/52662f18ae6fc89b18b020b89aa4e1cd
http://www.madhur.co.in/blog/2016/09/05/nodejs-connection-pooling.html
*/
const mysql = require('mysql'); // import
const pool = mysql.createPool({ // create pool instance
host: "*",
user: "*",
password: "*",
connectionLimit: 100, //important
});
/*
parse successful queries by converting RowDataPacket to JS Object
*/
const onSuccess = (rows) => {
return (
JSON.parse(
JSON.stringify(rows)
)
)
}
const hitQuery = (query) =>
new Promise((resolve, reject) => {
pool.query(query, (ex, rows) => {
(
(ex) ? reject(ex) :
resolve(rows)
)
});
})
.then((rows) => onSuccess(rows));
module.exports = hitQuery;
const hitQuery = require('./mysqlConnector.js');
query = (` select * from users where username="sam"`);
hitQuery(query)
.then(response => console.log(response))
.catch(e => console.log(e))
@binki
Copy link

binki commented Feb 26, 2020

For your scenario, it would be better/cleaner to simply use pool.query() as I mentioned. Also, I would recommend rejecting the Promise rather than resolving it if the call returns an error.

const hitQuery = query => new Promise((resolve, reject) => {
  pool.query(query, (ex, rows) => {
    if (ex) {
      reject(ex);
    } else {
      resolve(rows);
    }
  });
}).then(onSuccess);

That way, you don’t need to worry about releasing the connection yourself. The library will take care of it for you.

@Slurpgoose
Copy link
Author

@binki, thanks for the reply!
jeez I wish I would have just read your comments carefully would have saved me over an hour dealing with async nonsense. ill update my gist incase some one ends up stumbling upon it.

@binki
Copy link

binki commented Feb 26, 2020

No problem! Thanks for updating your gist!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment