Last active
January 3, 2023 19:25
-
-
Save Slurpgoose/f1af109c5ef87b3cd138ce1f9343632d to your computer and use it in GitHub Desktop.
A method to wrap your node application with a mysql pool.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, 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.
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
For your scenario, it would be better/cleaner to simply use
pool.query()
as I mentioned. Also, I would recommend rejecting thePromise
rather than resolving it if the call returns an error.That way, you don’t need to worry about releasing the connection yourself. The library will take care of it for you.