I am working on nodejs with mysql(8.x). I have intalled mysql library from npm.
I wrote some code like below.
File A - connection.js
const pooledConInfo = {
host: 'localhost',
user: 'user',
password: 'pw',
database: 'db',
insecureAuth : true,
connectionLimit : 10,
};
const pooledConnection = mysql.createPool(pooledConInfo);
module.exports = pooledConnection;
File B - MemberRouter.js
const con = require('../db/connection');
...
router.get('/api/member', (req, res, nxt) => {
let rs = Object.assign({}, resForm);
try {
con.getConnection((err, connection) => { // #1. Do not want to repeat in every query situation
if(err) throw err;
connection.query('SELECT * FROM MEMBER LIMIT ?', 10, (err, result, fields) => {
connection.release(); // #2. Do not want to repeat in every query situation
if(err) throw err;
rs.data = result;
return res.json(rs);
})
});
} catch (queryException) {
rs.cause = queryException;
return res.json(rs);
}
});
It works, but I do not believe people use like this.
This is the main 2 questions I want to ask
- The most annoying part is I have to release each pool in every query callback. Is it right way
- Is there any good pattern to apply ? I want to wrap
getConnection
andconnection.release
part...
Thanks