mempool/backend/src/database.ts

55 lines
1.4 KiB
TypeScript
Raw Normal View History

import config from './config';
2022-04-12 08:15:57 +02:00
import { createPool, Pool, PoolConnection } from 'mysql2/promise';
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 !== '') {
poolConfig.socketPath = config.DATABASE.SOCKET;
} else {
poolConfig.host = config.DATABASE.HOST;
}
2022-03-13 14:57:17 +01:00
return poolConfig;
}
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-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);
}
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]);
logger.info('Database connection established.');
2019-07-21 16:59:47 +02:00
} catch (e) {
logger.err('Could not connect to database: ' + (e instanceof Error ? e.message : e));
2019-07-21 16:59:47 +02:00
process.exit(1);
}
}