FIrst commit
This commit is contained in:
52
Classes/Database.js
Normal file
52
Classes/Database.js
Normal file
@@ -0,0 +1,52 @@
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
class Database {
|
||||
constructor(config) {
|
||||
this.pool = mysql.createPool(config);
|
||||
}
|
||||
|
||||
async query(sql, params) {
|
||||
const connection = await this.pool.getConnection();
|
||||
try {
|
||||
const [rows] = await connection.query(sql, params);
|
||||
return rows;
|
||||
} finally {
|
||||
connection.release();
|
||||
}
|
||||
}
|
||||
|
||||
async execute(sql, params) {
|
||||
const connection = await this.pool.getConnection();
|
||||
try {
|
||||
const [result] = await connection.execute(sql, params);
|
||||
return result;
|
||||
} finally {
|
||||
connection.release();
|
||||
}
|
||||
}
|
||||
|
||||
async transaction(callback) {
|
||||
const connection = await this.pool.getConnection();
|
||||
try {
|
||||
await connection.beginTransaction();
|
||||
const result = await callback(connection);
|
||||
await connection.commit();
|
||||
return result;
|
||||
} catch (error) {
|
||||
await connection.rollback();
|
||||
throw error;
|
||||
} finally {
|
||||
connection.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const database = new Database({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASS,
|
||||
database: process.env.DB_NAME
|
||||
});
|
||||
|
||||
export { Database, database };
|
||||
Reference in New Issue
Block a user