Skip to content

Instantly share code, notes, and snippets.

@khoahuynhdev
Forked from hagemann/database.js
Created April 20, 2019 06:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save khoahuynhdev/5cb0f5a2ecee55055071c7254e0a6388 to your computer and use it in GitHub Desktop.
Save khoahuynhdev/5cb0f5a2ecee55055071c7254e0a6388 to your computer and use it in GitHub Desktop.
Promisified MySQL middleware for Node.js
const util = require('util')
const mysql = require('mysql')
const pool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
user: 'root',
password: 'password',
database: 'my_database'
})
// Ping database to check for common exception errors.
pool.getConnection((err, connection) => {
if (err) {
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
console.error('Database connection was closed.')
}
if (err.code === 'ER_CON_COUNT_ERROR') {
console.error('Database has too many connections.')
}
if (err.code === 'ECONNREFUSED') {
console.error('Database connection was refused.')
}
}
if (connection) connection.release()
return
})
// Promisify for Node.js async/await.
pool.query = util.promisify(pool.query)
module.exports = pool
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment