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
|
|
|
|
2022-04-13 15:38:42 +02:00
|
|
|
class DB {
|
|
|
|
constructor() {
|
2022-04-12 08:15:57 +02:00
|
|
|
if (config.DATABASE.SOCKET !== '') {
|
2022-04-13 15:38:42 +02:00
|
|
|
this.poolConfig.socketPath = config.DATABASE.SOCKET;
|
2022-03-14 14:11:04 +01:00
|
|
|
} else {
|
2022-04-13 15:38:42 +02:00
|
|
|
this.poolConfig.host = config.DATABASE.HOST;
|
2022-03-14 14:11:04 +01:00
|
|
|
}
|
2022-04-13 15:38:42 +02:00
|
|
|
}
|
|
|
|
private pool: Pool | null = null;
|
|
|
|
private poolConfig: PoolOptions = {
|
|
|
|
port: config.DATABASE.PORT,
|
|
|
|
database: config.DATABASE.DATABASE,
|
|
|
|
user: config.DATABASE.USERNAME,
|
|
|
|
password: config.DATABASE.PASSWORD,
|
|
|
|
connectionLimit: 10,
|
|
|
|
supportBigNumbers: true,
|
|
|
|
timezone: '+00:00',
|
|
|
|
};
|
2022-03-13 14:57:17 +01:00
|
|
|
|
2022-04-13 15:38:42 +02:00
|
|
|
public async query(query, params?) {
|
|
|
|
const pool = await this.getPool();
|
|
|
|
return pool.query(query, params);
|
2022-03-13 14:57:17 +01:00
|
|
|
}
|
2022-03-12 14:47:33 +01:00
|
|
|
|
2022-04-13 15:38:42 +02:00
|
|
|
public async checkDbConnection() {
|
|
|
|
try {
|
|
|
|
await this.query('SELECT ?', [1]);
|
|
|
|
logger.info('Database connection established.');
|
|
|
|
} catch (e) {
|
|
|
|
logger.err('Could not connect to database: ' + (e instanceof Error ? e.message : e));
|
|
|
|
process.exit(1);
|
2022-03-12 14:47:33 +01:00
|
|
|
}
|
2022-04-12 08:15:57 +02:00
|
|
|
}
|
|
|
|
|
2022-04-13 15:38:42 +02:00
|
|
|
private async getPool(): Promise<Pool> {
|
|
|
|
if (this.pool === null) {
|
|
|
|
this.pool = createPool(this.poolConfig);
|
|
|
|
this.pool.on('connection', function (newConnection: PoolConnection) {
|
|
|
|
newConnection.query(`SET time_zone='+00:00'`);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
return this.pool;
|
2022-03-12 14:47:33 +01:00
|
|
|
}
|
2019-07-21 16:59:47 +02:00
|
|
|
}
|
|
|
|
|
2022-04-13 15:38:42 +02:00
|
|
|
export default new DB();
|