Created
August 12, 2018 11:19
-
-
Save dfa1234/3096dc6525425eb375dc1ad582eb8c1d to your computer and use it in GitHub Desktop.
Mysql Pool Failsafe Connection
This file contains hidden or 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
import * as mysql from "mysql"; | |
import {MysqlError, Pool, PoolConnection} from "mysql"; | |
import {dbMysqlConf} from "./config"; | |
const MAX_ATTEMPS = 10; | |
let attempts = 0; | |
export const managePoolConnection = (app:any) => new Promise((resolve: (status:string) => void, reject: (status:string) => void) => { | |
let pool: Pool = mysql.createPool(dbMysqlConf); | |
pool.getConnection((err: MysqlError, connection: PoolConnection) => { | |
if (err) { | |
attempts++; | |
if (attempts > MAX_ATTEMPS) { | |
reject(`Mysql Error: More than ${MAX_ATTEMPS}, cancelling. Error ${err.errno} : ${err.sqlMessage}`) | |
} else { | |
setTimeout(() => { | |
managePoolConnection(app).then(resolve, reject) | |
}, 2000); | |
} | |
return; | |
} else { | |
attempts = 0; | |
(app as any).poolConnection = connection; | |
connection.on('error', (err: MysqlError) => { | |
console.log(`Mysql Error: Cannot establish a connection with the database. (${err.code})`); | |
switch (err.code) { | |
case "PROTOCOL_CONNECTION_LOST": | |
managePoolConnection(app).then(resolve, reject); | |
break; | |
case "PROTOCOL_ENQUEUE_AFTER_QUIT": | |
managePoolConnection(app).then(resolve, reject); | |
break; | |
case "PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR": | |
managePoolConnection(app).then(resolve, reject); | |
break; | |
case "PROTOCOL_ENQUEUE_HANDSHAKE_TWICE": | |
//managePoolConnection.then(resolve, reject); | |
break; | |
default: | |
managePoolConnection(app).then(resolve, reject); | |
break; | |
} | |
}); | |
resolve(`Mysql: connection successful`); | |
} | |
}); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Then in the index.ts (app is the express server but could be something else)