From a56ef5a0f1d136066c746ed9a8abd26c48bcddfd Mon Sep 17 00:00:00 2001 From: Felix Albrigtsen Date: Tue, 5 Apr 2022 10:58:40 +0200 Subject: [PATCH] Auto restart database connection --- src/server/tmdb.js | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/src/server/tmdb.js b/src/server/tmdb.js index 95d03e6..9b0056c 100644 --- a/src/server/tmdb.js +++ b/src/server/tmdb.js @@ -19,12 +19,35 @@ module.exports = { const mysql = require("mysql"); -let connection = mysql.createConnection({ +let db_config = { host: process.env.DB_HOST, user: process.env.DB_USER, password: process.env.DB_PASSWORD, database: process.env.DB_DATABASE -}); +}; +let connection +// https://stackoverflow.com/a/20211143 +function handleDisconnect() { + connection = mysql.createConnection(db_config); // Recreate the connection + + connection.connect(function(err) { + if(err) { + console.log('error when connecting to db:', err); + setTimeout(handleDisconnect, 2000); // 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('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(); //Start the auto-restarting connection function escapeString(str) { // return mysql.escape(str);