2020-10-19 06:57:02 +02:00
|
|
|
import config from './config';
|
2022-04-12 08:15:57 +02:00
|
|
|
import { createPool, Pool, PoolConnection } from 'mysql2/promise';
|
2020-10-13 10:27:52 +02:00
|
|
|
import logger from './logger';
|
2022-03-13 14:57:17 +01:00
|
|
|
import { PoolOptions } from 'mysql2/typings/mysql';
|
2019-07-21 16:59:47 +02:00
|
|
|
|
|
|
|
export class DB {
|
2022-04-12 08:15:57 +02:00
|
|
|
static connectionsReady: number[] = [];
|
|
|
|
static pool: Pool | null = null;
|
|
|
|
|
|
|
|
static poolConfig = (): PoolOptions => {
|
|
|
|
const poolConfig: PoolOptions = {
|
2022-03-13 14:57:17 +01:00
|
|
|
port: config.DATABASE.PORT,
|
|
|
|
database: config.DATABASE.DATABASE,
|
|
|
|
user: config.DATABASE.USERNAME,
|
|
|
|
password: config.DATABASE.PASSWORD,
|
|
|
|
connectionLimit: 10,
|
|
|
|
supportBigNumbers: true,
|
|
|
|
timezone: '+00:00',
|
2022-04-12 08:15:57 +02:00
|
|
|
};
|
2022-03-13 14:57:17 +01:00
|
|
|
|
2022-04-12 08:15:57 +02:00
|
|
|
if (config.DATABASE.SOCKET !== '') {
|
2022-03-14 14:11:04 +01:00
|
|
|
poolConfig.socketPath = config.DATABASE.SOCKET;
|
|
|
|
} else {
|
|
|
|
poolConfig.host = config.DATABASE.HOST;
|
|
|
|
}
|
2022-03-13 14:57:17 +01:00
|
|
|
|
|
|
|
return poolConfig;
|
|
|
|
}
|
2022-03-12 14:47:33 +01:00
|
|
|
|
2022-04-12 08:15:57 +02:00
|
|
|
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'`);
|
|
|
|
});
|
2022-03-12 14:47:33 +01:00
|
|
|
}
|
2022-04-12 08:15:57 +02:00
|
|
|
return DB.pool;
|
|
|
|
}
|
|
|
|
|
|
|
|
static async query(query, params?) {
|
|
|
|
const pool = await DB.getPool();
|
|
|
|
return pool.query(query, params);
|
2022-03-12 14:47:33 +01:00
|
|
|
}
|
2019-07-21 16:59:47 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
export async function checkDbConnection() {
|
|
|
|
try {
|
2022-04-12 08:15:57 +02:00
|
|
|
await DB.query('SELECT ?', [1]);
|
2020-10-13 10:27:52 +02:00
|
|
|
logger.info('Database connection established.');
|
2019-07-21 16:59:47 +02:00
|
|
|
} catch (e) {
|
2021-08-31 14:09:33 +02:00
|
|
|
logger.err('Could not connect to database: ' + (e instanceof Error ? e.message : e));
|
2019-07-21 16:59:47 +02:00
|
|
|
process.exit(1);
|
|
|
|
}
|
|
|
|
}
|