artmapper
Version:
Spring Boot clone for Node.js with TypeScript/JavaScript - JPA-like ORM, Lombok decorators, dependency injection, and MySQL support
98 lines • 3.16 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.DatabaseManager = void 0;
const promise_1 = require("mysql2/promise");
class DatabaseManager {
constructor() {
this.pool = null;
this.config = null;
}
static getInstance() {
if (!DatabaseManager.instance) {
DatabaseManager.instance = new DatabaseManager();
}
return DatabaseManager.instance;
}
/**
* Initialize database connection pool
*/
async initialize(config) {
this.config = config;
// Ensure database exists first (before connecting to it)
await this.ensureDatabaseExists(config.database);
const poolOptions = {
host: config.host,
port: config.port,
user: config.user,
password: config.password,
database: config.database,
waitForConnections: config.waitForConnections !== false,
connectionLimit: config.connectionLimit || 10,
queueLimit: config.queueLimit || 0,
};
this.pool = (0, promise_1.createPool)(poolOptions);
// Test connection
try {
const connection = await this.pool.getConnection();
await connection.ping();
connection.release();
console.log('✓ Database connection established');
}
catch (error) {
console.error('✗ Database connection failed:', error);
throw error;
}
}
/**
* Ensure the database exists, create if it doesn't
*/
async ensureDatabaseExists(databaseName) {
if (!this.config)
return;
try {
// Create a connection without specifying database
const tempPool = (0, promise_1.createPool)({
host: this.config.host,
port: this.config.port,
user: this.config.user,
password: this.config.password,
});
await tempPool.execute(`CREATE DATABASE IF NOT EXISTS \`${databaseName}\``);
await tempPool.end();
}
catch (error) {
// If we can't create database, it might already exist or we don't have permissions
// This is not a fatal error, continue
console.warn('Could not create database (may already exist):', error.message);
}
}
/**
* Get the connection pool
*/
getPool() {
if (!this.pool) {
throw new Error('Database not initialized. Call initialize() first.');
}
return this.pool;
}
/**
* Close all database connections
*/
async close() {
if (this.pool) {
await this.pool.end();
this.pool = null;
console.log('✓ Database connections closed');
}
}
/**
* Execute a raw SQL query
*/
async query(sql, params) {
const pool = this.getPool();
const [rows] = await pool.execute(sql, params || []);
return rows;
}
}
exports.DatabaseManager = DatabaseManager;
//# sourceMappingURL=DatabaseConfig.js.map