50 lines
1.2 KiB
JavaScript
50 lines
1.2 KiB
JavaScript
const DB = require("./db");
|
|
const mysql = require('mysql2');
|
|
|
|
class MySQLDB extends DB {
|
|
constructor() {
|
|
super();
|
|
this.connection = null;
|
|
}
|
|
|
|
async createConnection() {
|
|
this.loadConfig();
|
|
const { mysqldb } = this.config;
|
|
this.connection = mysql.createConnection({
|
|
host: mysqldb.host,
|
|
port: mysqldb.port,
|
|
user: mysqldb.user,
|
|
password: mysqldb.password,
|
|
database: mysqldb.database,
|
|
connectTimeout: 0 // disable timeout
|
|
});
|
|
await this.connection.connect();
|
|
}
|
|
|
|
async closeConnection() {
|
|
if (this.connection) {
|
|
await this.connection.end();
|
|
this.connection = null;
|
|
}
|
|
}
|
|
|
|
async query(query) {
|
|
if (!this.connection) {
|
|
throw new Error('Database not connected');
|
|
}
|
|
const results = await new Promise((resolve, reject) => {
|
|
this.connection.query(query, (err, rows) => {
|
|
if (err) {
|
|
reject(err);
|
|
} else {
|
|
resolve(rows);
|
|
}
|
|
});
|
|
});
|
|
return results;
|
|
}
|
|
}
|
|
|
|
module.exports = MySQLDB;
|
|
|