-
Notifications
You must be signed in to change notification settings - Fork 16
/
web.js
52 lines (45 loc) · 1.98 KB
/
web.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
var express = require("express");
var mysql = require('mysql');
var app = express();
app.use(express.logger());
var db_config = {
host: 'us-cdbr-east-04.cleardb.com',
user: 'b6d6c6e8740d20',
password: 'b3f75ada',
database: 'heroku_1daa39da0375291'
};
var connection;
function handleDisconnect() {
console.log('1. connecting to db:');
connection = mysql.createConnection(db_config); // Recreate the connection, since
// the old one cannot be reused.
connection.connect(function(err) { // The server is either down
if (err) { // or restarting (takes a while sometimes).
console.log('2. error when connecting to db:', err);
setTimeout(handleDisconnect, 1000); // We introduce a delay before attempting to reconnect,
} // to avoid a hot loop, and to allow our node script to
}); // process asynchronous requests in the meantime.
// If you're also serving http, display a 503 error.
connection.on('error', function(err) {
console.log('3. db error', err);
if (err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
handleDisconnect(); // lost due to either server restart, or a
} else { // connnection idle timeout (the wait_timeout
throw err; // server variable configures this)
}
});
}
handleDisconnect();
app.get('/', function(request, response) {
connection.query('SELECT * from t_users', function(err, rows, fields) {
if (err) {
console.log('error: ', err);
throw err;
}
response.send(['Hello World!!!! HOLA MUNDO!!!!', rows]);
});
});
var port = process.env.PORT || 5000;
app.listen(port, function() {
console.log("Listening on " + port);
});