When using promise-mysql, we often want a singleton connection created in a .js file:
module.exports = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'mydb',
})
then files for different routes will import and use it:
const connection = require('./connection');
router.get('/', (req, res) => {
connection
.then(conn => conn.query('SELECT * FROM table WHERE id = ?', req.body.id))
.then(rows => res.send(rows));
});
However, calling connection.then(conn => ...)
for every routing function is somewhat troublesome.
In ES6 modules, variables are exported as immutable bindings rather than values. Hence, we can do the following:
let conn;
mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'mydb',
}).then((connection) => { conn = connection; });
export { conn as default }
Now we can use conn directly in routing functions:
import conn from'./connection';
router.get('/', (req, res) => {
conn.query('SELECT * FROM table WHERE id = ?', req.body.id))
.then(rows => res.send(rows));
});
How cool is that? :p
As even Node 9 does not support ES6 modules, Babel has to be used to transpile the source, which wraps the exported value as an object to achieve to same effect.
Note: for some peculiar reason, the export default conn
syntax does not export conn
as live binding.
Leave a Reply
You must be logged in to post a comment.