reopening mysql connection when closed

This commit is contained in:
silas 2021-02-15 12:14:09 +01:00
parent 9db0c798b0
commit 2d136f0214

View File

@ -22,12 +22,12 @@ export class Server {
private initialize(): void { private initialize(): void {
this.app = express(); this.app = express();
this.httpServer = createServer(this.app); this.httpServer = createServer(this.app);
this.mysqlConnection = mysql.createConnection({ // this.mysqlConnection = mysql.createConnection({
host: process.env.MYSQL_HOST || "localhost", // host: process.env.MYSQL_HOST || "localhost",
user: process.env.MYSQL_USER || "root", // user: process.env.MYSQL_USER || "root",
password: process.env.MYSQL_PASSWORD || "", // password: process.env.MYSQL_PASSWORD || "",
database: process.env.MYSQL_DATABASE || "hochzeit" // database: process.env.MYSQL_DATABASE || "hochzeit"
}); // });
this.configureApp(); this.configureApp();
this.configureRoutes(); this.configureRoutes();
@ -36,8 +36,29 @@ export class Server {
private async query(sql): Promise<any[]> { private async query(sql): Promise<any[]> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
try {
if (!this.mysqlConnection || this.mysqlConnection.state === "disconnected"){
console.log("reopening connection...");
this.mysqlConnection = mysql.createConnection({
host: process.env.MYSQL_HOST || "localhost",
user: process.env.MYSQL_USER || "root",
password: process.env.MYSQL_PASSWORD || "",
database: process.env.MYSQL_DATABASE || "hochzeit"
});
// setTimeout(() => {
// this.mysqlConnection.destroy();
// }, 5000);
}
}catch(e){
console.error(e);
reject(e);
}
this.mysqlConnection.query(sql, (error, results) => { this.mysqlConnection.query(sql, (error, results) => {
if (error) { if (error) {
console.error(error);
reject(error) reject(error)
} else { } else {
resolve(results); resolve(results);
@ -84,4 +105,4 @@ export class Server {
callback(this.DEFAULT_PORT); callback(this.DEFAULT_PORT);
}); });
} }
} }