48 lines
1.2 KiB
JavaScript
48 lines
1.2 KiB
JavaScript
const mariadb = require("mariadb");
|
|
let dbConn;
|
|
let conPool;
|
|
// mariadb doc: https://github.com/MariaDB/mariadb-connector-nodejs/blob/master/documentation/promise-api.md
|
|
|
|
async function reconnect() {
|
|
try {
|
|
dbConn = await conPool.getConnection();
|
|
} catch (e) {
|
|
if (e.code === "ECONNREFUSED") {
|
|
let err = new Error("Lost connection to the database");
|
|
err.code = "ERR_DB_CONN_LOST";
|
|
throw err;
|
|
} else {
|
|
throw e;
|
|
}
|
|
}
|
|
}
|
|
|
|
module.exports = async config => {
|
|
conPool = mariadb.createPool({
|
|
host: process.env.DB_HOST,
|
|
user: process.env.DB_USER,
|
|
password: process.env.DB_PASSWORD,
|
|
port: process.env.DB_PORT,
|
|
database: process.env.DATABASE,
|
|
connectionLimit: 10
|
|
});
|
|
|
|
dbConn = await conPool.getConnection();
|
|
return {
|
|
async query(q, p) {
|
|
let res;
|
|
try {
|
|
res = await dbConn.query(q, p);
|
|
} catch (e) {
|
|
if (e.code === "ER_CMD_CONNECTION_CLOSED") {
|
|
await reconnect();
|
|
await this.query(q, p);
|
|
} else {
|
|
throw e;
|
|
}
|
|
}
|
|
return res;
|
|
}
|
|
};
|
|
};
|