2020-10-19 11:57:02 +07:00
|
|
|
import config from './config';
|
2022-04-12 15:15:57 +09:00
|
|
|
import { createPool, Pool, PoolConnection } from 'mysql2/promise';
|
2020-10-13 15:27:52 +07:00
|
|
|
import logger from './logger';
|
2022-08-08 09:00:11 +02:00
|
|
|
import { FieldPacket, OkPacket, PoolOptions, ResultSetHeader, RowDataPacket } from 'mysql2/typings/mysql';
|
2019-07-21 17:59:47 +03:00
|
|
|
|
2022-04-13 17:38:42 +04:00
|
|
|
class DB {
|
|
|
|
constructor() {
|
2022-04-12 15:15:57 +09:00
|
|
|
if (config.DATABASE.SOCKET !== '') {
|
2022-04-13 17:38:42 +04:00
|
|
|
this.poolConfig.socketPath = config.DATABASE.SOCKET;
|
2022-03-14 13:11:04 +00:00
|
|
|
} else {
|
2022-04-13 17:38:42 +04:00
|
|
|
this.poolConfig.host = config.DATABASE.HOST;
|
2022-03-14 13:11:04 +00:00
|
|
|
}
|
2022-04-13 17:38:42 +04: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-06-07 11:28:39 +02:00
|
|
|
private checkDBFlag() {
|
|
|
|
if (config.DATABASE.ENABLED === false) {
|
|
|
|
logger.err('Trying to use DB feature but config.DATABASE.ENABLED is set to false, please open an issue');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-08-08 09:00:11 +02:00
|
|
|
public async query<T extends RowDataPacket[][] | RowDataPacket[] | OkPacket |
|
|
|
|
OkPacket[] | ResultSetHeader>(query, params?): Promise<[T, FieldPacket[]]>
|
|
|
|
{
|
2022-06-07 11:28:39 +02:00
|
|
|
this.checkDBFlag();
|
2022-04-13 17:38:42 +04:00
|
|
|
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 17:38:42 +04:00
|
|
|
public async checkDbConnection() {
|
2022-06-07 11:28:39 +02:00
|
|
|
this.checkDBFlag();
|
2022-04-13 17:38:42 +04:00
|
|
|
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 15:15:57 +09:00
|
|
|
}
|
|
|
|
|
2022-04-13 17:38:42 +04: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 17:59:47 +03:00
|
|
|
}
|
|
|
|
|
2022-04-13 17:38:42 +04:00
|
|
|
export default new DB();
|