erp-construccion-backend/src/config/database.ts
rckrdmrd b3cd6e2e51 [SYNC] feat: Completar integración erp-core - FASE 2A
- Crear capa de compatibilidad config/ (database.ts, typeorm.ts, index.ts)
- Exportar Tenant y User en core/entities/index.ts
- Crear Company entity en auth/entities/
- Crear Warehouse entity y módulo warehouses/
- Corregir ApiKey imports para usar core/entities
- Unificar tipos TokenPayload y JwtPayload
- Corregir ZodError.errors -> .issues en controllers CRM, inventory, sales, partners
- Agregar exports InventoryService e InventoryController
- Deshabilitar temporalmente módulo finance (requiere correcciones estructurales)
- Agregar .gitignore estándar

Build: PASANDO (módulo finance excluido temporalmente)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-18 11:43:59 -06:00

77 lines
2.2 KiB
TypeScript

import { Pool, PoolConfig, PoolClient } from 'pg';
// Re-export PoolClient for use in services
export type { PoolClient };
import { config } from './index.js';
// Simple logger for now (can be replaced with winston later)
const logger = {
debug: (msg: string, meta?: object) => console.debug(`[DEBUG] ${msg}`, meta || ''),
info: (msg: string, meta?: object) => console.info(`[INFO] ${msg}`, meta || ''),
warn: (msg: string, meta?: object) => console.warn(`[WARN] ${msg}`, meta || ''),
error: (msg: string, meta?: object) => console.error(`[ERROR] ${msg}`, meta || ''),
};
const poolConfig: PoolConfig = {
host: config.database.host,
port: config.database.port,
database: config.database.name,
user: config.database.user,
password: config.database.password,
max: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000,
};
export const pool = new Pool(poolConfig);
pool.on('connect', () => {
logger.debug('New database connection established');
});
pool.on('error', (err) => {
logger.error('Unexpected database error', { error: err.message });
});
export async function testConnection(): Promise<boolean> {
try {
const client = await pool.connect();
const result = await client.query('SELECT NOW()');
client.release();
logger.info('Database connection successful', { timestamp: result.rows[0].now });
return true;
} catch (error) {
logger.error('Database connection failed', { error: (error as Error).message });
return false;
}
}
export async function query<T = any>(text: string, params?: any[]): Promise<T[]> {
const start = Date.now();
const result = await pool.query(text, params);
const duration = Date.now() - start;
logger.debug('Query executed', {
text: text.substring(0, 100),
duration: `${duration}ms`,
rows: result.rowCount
});
return result.rows as T[];
}
export async function queryOne<T = any>(text: string, params?: any[]): Promise<T | null> {
const rows = await query<T>(text, params);
return rows[0] || null;
}
export async function getClient() {
const client = await pool.connect();
return client;
}
export async function closePool(): Promise<void> {
await pool.end();
logger.info('Database pool closed');
}