Skip to content

Instantly share code, notes, and snippets.

@saiumesh535
Last active February 13, 2018 18:24
Show Gist options
  • Select an option

  • Save saiumesh535/9af07aea931bc0e02d2b6dca3a1bb1e4 to your computer and use it in GitHub Desktop.

Select an option

Save saiumesh535/9af07aea931bc0e02d2b6dca3a1bb1e4 to your computer and use it in GitHub Desktop.
connecting MySQL in express nodejs
const express = require('express');
const app = express();
/* requiring middleware */
const { getConnection } = require('./app/middlewares/mysql');
/* connecting mysql before going to requested route */
app.use('/auth', getConnection, require('./app/controllers/auth'));
/* this is config file for our application */
/* rather you can config details in process envs */
module.exports = {
mysql : {
host: 'localhost',
user : 'root',
password: '',
database : 'mysql_database',
connectionLimit: 10
}
}
/* this file helps to connect mysql database */
/* this file location might look like this ----> /middlewares/mysql.js */
const mysql = require('mysql');
const config = require('../utils/config');
let pool;
const passConneciton = (req, res, next) => {
pool.getConnection((err, connection) => {
if (err) {
next(err);
} else {
/* adding connection to res object, so it can be used in router */
res.locals.mysqlConn = connection;
next();
/* release connection when you are done */
res.on('finish', () => {
connection.release();
});
}
});
};
module.exports = {
getConnection: async (req, res, next) => {
/* if pool already been set then re-use it */
if (pool) {
passConneciton(req, res, next);
} else {
/* create pool
here, we are getting mysql config from config.js,
but you can also opt for process evn's
*/
pool = mysql.createPool(config.mysql);
passConneciton(req, res, next);
}
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment