Created
December 7, 2015 17:55
-
-
Save conoro/9aeccb06bd4bf7a4d8df to your computer and use it in GitHub Desktop.
MySQL Connection Pooling and Data Format for RHMAP Forms
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'); | |
var bodyParser = require('body-parser'); | |
var cors = require('cors'); | |
var mysql = require('mysql'); | |
var pool = mysql.createPool({ | |
connectionLimit : 100, //important | |
host : process.env.MYSQL_HOST, | |
user : process.env.MYSQL_USERNAME, | |
password : process.env.MYSQL_PASSWORD, | |
database : "top100", | |
charset: 'utf8_general_ci', | |
debug : false | |
}); | |
function handle_database(req,res) { | |
pool.getConnection(function(err,connection){ | |
if (err) { | |
connection.release(); | |
res.json({"code" : 100, "status" : "Error in connection database"}); | |
return; | |
} | |
console.log('connected as id ' + connection.threadId); | |
connection.query('SELECT id AS "key", winename AS "value" FROM wines', function(err, rows, fields) { | |
connection.release(); | |
if(!err) { | |
var result = []; | |
for (var i = 0; i < rows.length; i++) { | |
result.push({"key": rows[i].key, "value": rows[i].value, "selected": false}); | |
} | |
res.header('Content-Type', 'application/json; charset=utf-8'); | |
res.json(result); | |
} | |
}); | |
connection.on('error', function(err) { | |
res.json({"code" : 100, "status" : "Error in connection database"}); | |
return; | |
}); | |
}); | |
} | |
function wineRoute() { | |
var wine = new express.Router(); | |
wine.use(cors()); | |
wine.use(bodyParser()); | |
// GET REST endpoint - query params may or may not be populated | |
wine.get('/', function(req, res) { | |
handle_database(req,res); | |
}); | |
return wine; | |
} | |
module.exports = wineRoute; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: