Refactor database pool use
This commit is contained in:
@@ -1,11 +1,14 @@
|
||||
import config from './config';
|
||||
import { createPool, PoolConnection } from 'mysql2/promise';
|
||||
import { createPool, Pool, PoolConnection } from 'mysql2/promise';
|
||||
import logger from './logger';
|
||||
import { PoolOptions } from 'mysql2/typings/mysql';
|
||||
|
||||
export class DB {
|
||||
static poolConfig = ():PoolOptions => {
|
||||
let poolConfig:PoolOptions = {
|
||||
static connectionsReady: number[] = [];
|
||||
static pool: Pool | null = null;
|
||||
|
||||
static poolConfig = (): PoolOptions => {
|
||||
const poolConfig: PoolOptions = {
|
||||
port: config.DATABASE.PORT,
|
||||
database: config.DATABASE.DATABASE,
|
||||
user: config.DATABASE.USERNAME,
|
||||
@@ -13,9 +16,9 @@ export class DB {
|
||||
connectionLimit: 10,
|
||||
supportBigNumbers: true,
|
||||
timezone: '+00:00',
|
||||
}
|
||||
};
|
||||
|
||||
if (config.DATABASE.SOCKET !== "") {
|
||||
if (config.DATABASE.SOCKET !== '') {
|
||||
poolConfig.socketPath = config.DATABASE.SOCKET;
|
||||
} else {
|
||||
poolConfig.host = config.DATABASE.HOST;
|
||||
@@ -23,27 +26,27 @@ export class DB {
|
||||
|
||||
return poolConfig;
|
||||
}
|
||||
|
||||
static pool = createPool(DB.poolConfig());
|
||||
|
||||
static connectionsReady: number[] = [];
|
||||
|
||||
static async getConnection() {
|
||||
const connection: PoolConnection = await DB.pool.getConnection();
|
||||
const connectionId = connection['connection'].connectionId;
|
||||
if (!DB.connectionsReady.includes(connectionId)) {
|
||||
await connection.query(`SET time_zone='+00:00';`);
|
||||
this.connectionsReady.push(connectionId);
|
||||
static async getPool(): Promise<Pool> {
|
||||
if (DB.pool === null) {
|
||||
DB.pool = createPool(DB.poolConfig());
|
||||
DB.pool.on('connection', function (newConnection: PoolConnection) {
|
||||
newConnection.query(`SET time_zone='+00:00'`);
|
||||
});
|
||||
}
|
||||
return connection;
|
||||
return DB.pool;
|
||||
}
|
||||
|
||||
static async query(query, params?) {
|
||||
const pool = await DB.getPool();
|
||||
return pool.query(query, params);
|
||||
}
|
||||
}
|
||||
|
||||
export async function checkDbConnection() {
|
||||
try {
|
||||
const connection = await DB.getConnection();
|
||||
await DB.query('SELECT ?', [1]);
|
||||
logger.info('Database connection established.');
|
||||
connection.release();
|
||||
} catch (e) {
|
||||
logger.err('Could not connect to database: ' + (e instanceof Error ? e.message : e));
|
||||
process.exit(1);
|
||||
|
||||
Reference in New Issue
Block a user