const mysql = require('mysql2/promise');
const {env} = require('./env');

const pool = mysql.createPool({
  ...env.db,
  waitForConnections: true,
  namedPlaceholders: true,
  decimalNumbers: true,
  dateStrings: true,
});

async function transaction(callback) {
  const connection = await 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();
  }
}

module.exports = {pool, transaction};
