Saturday 17 December 2016

Integrating mysql connections pool with restify

I'm trying to create a REST service which deals with databases with restify and mysql.I have something like that:var restify = require('restify'); var mysql = require('mysql'); var server = restify.createServer(); //Empty db info on purpose var pool = mysql.createPool({ host : '', user : '', password : '', database : '' }); connection.connect(); server.get('/authenticate', function authenticate(req, res, next) { pool.getConnection(function(err, connection) { connection.query('SELECT * FROM sometable WHERE id = 1', function(err, rows) { if (err) throw err; connection.release(); res.send(rows); next(); }); }); }); server.listen(3000); Do I need to fetch a connection from the pool for each request like I'm doing or is it not supposed to look like that?It feels a bit cumbersome, especially since I'd have to repeat that connection logic in many other routes I'd like to add.I could create a class with a simplified interface that creates a query in a connection fetched from the pool and releases the connection once the query is resolved, but I feel like I'm complicating things that should already be simple.Did I get the concept right or am I misunderstanding something?

Submitted December 17, 2016 at 05:31PM by royibernthal

No comments:

Post a Comment