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

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