Files
EmployeeManagementSystem/backend-deno/config/database.ts
2025-11-27 22:50:08 +00:00

80 lines
2.0 KiB
TypeScript

import { createPool, Pool } from "mysql2/promise";
import { load } from "@std/dotenv";
// Load environment variables
await load({ export: true });
const config = {
host: Deno.env.get("DB_HOST") || "localhost",
user: Deno.env.get("DB_USER") || "root",
password: Deno.env.get("DB_PASSWORD") || "admin123",
database: Deno.env.get("DB_NAME") || "work_allocation",
port: parseInt(Deno.env.get("DB_PORT") || "3306"),
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
enableKeepAlive: true,
keepAliveInitialDelay: 0,
};
class Database {
private pool: Pool | null = null;
private static instance: Database;
private constructor() {}
static getInstance(): Database {
if (!Database.instance) {
Database.instance = new Database();
}
return Database.instance;
}
async connect(): Promise<Pool> {
if (!this.pool) {
this.pool = createPool(config);
// Test connection
try {
const connection = await this.pool.getConnection();
console.log("✅ Database connected successfully");
connection.release();
} catch (error) {
console.error("❌ Database connection failed:", (error as Error).message);
throw error;
}
}
return this.pool;
}
async getPool(): Promise<Pool> {
if (!this.pool) {
return await this.connect();
}
return this.pool;
}
async query<T>(sql: string, params?: unknown[]): Promise<T> {
const pool = await this.getPool();
const [rows] = await pool.query(sql, params);
return rows as T;
}
async execute(sql: string, params?: unknown[]): Promise<{ insertId: number; affectedRows: number }> {
const pool = await this.getPool();
const [result] = await pool.execute(sql, params);
return result as { insertId: number; affectedRows: number };
}
async close(): Promise<void> {
if (this.pool) {
await this.pool.end();
this.pool = null;
console.log("Database connection closed");
}
}
}
export const db = Database.getInstance();
export default db;