travopti/backend/models/dbConnection.js
2020-06-17 21:50:20 +02:00

44 lines
1.1 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({
...config.dbCredentials,
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;
}
};
};