seguimos confiando en codex
All checks were successful
build-and-deploy / build-and-deploy (push) Successful in 1m4s
All checks were successful
build-and-deploy / build-and-deploy (push) Successful in 1m4s
This commit is contained in:
@@ -4,6 +4,7 @@ import { useRuntimeConfig } from '#imports'
|
||||
const { Pool } = pg
|
||||
|
||||
let pool: pg.Pool | null = null
|
||||
let connectionStringLogged = false
|
||||
|
||||
function buildConnectionString(): string {
|
||||
const config = useRuntimeConfig()
|
||||
@@ -28,6 +29,12 @@ export function getPool(): pg.Pool {
|
||||
if (!pool) {
|
||||
const connectionString = buildConnectionString()
|
||||
|
||||
if (!connectionStringLogged && process.env.NODE_ENV !== 'production') {
|
||||
const masked = connectionString.replace(/:\/\/([^:]+):([^@]+)@/, '://$1:*****@')
|
||||
console.log('[db] Usando connectionString:', masked)
|
||||
connectionStringLogged = true
|
||||
}
|
||||
|
||||
pool = new Pool({
|
||||
connectionString,
|
||||
max: 10,
|
||||
@@ -58,19 +65,38 @@ export async function query<T = any>(
|
||||
): Promise<pg.QueryResult<T>> {
|
||||
const pool = getPool()
|
||||
const start = Date.now()
|
||||
const maxRetries = 2
|
||||
|
||||
try {
|
||||
const result = await pool.query<T>(text, params)
|
||||
const duration = Date.now() - start
|
||||
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
||||
try {
|
||||
const result = await pool.query<T>(text, params)
|
||||
const duration = Date.now() - start
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
console.log('Query ejecutada:', { text, duration: `${duration}ms`, rows: result.rowCount })
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
console.log('Query ejecutada:', { text, duration: `${duration}ms`, rows: result.rowCount })
|
||||
}
|
||||
|
||||
return result
|
||||
} catch (error: any) {
|
||||
const isAuthError = error?.code === '28P01'
|
||||
const isConnError = ['ECONNREFUSED', 'ECONNRESET', '57P01'].includes(error?.code)
|
||||
const shouldRetry = attempt < maxRetries && (isAuthError || isConnError)
|
||||
|
||||
console.error('Error ejecutando query:', { text, params, error: error?.message, code: error?.code, attempt })
|
||||
|
||||
if (shouldRetry) {
|
||||
// Pequeño backoff y reintento
|
||||
await new Promise((res) => setTimeout(res, 500 * (attempt + 1)))
|
||||
// Resetear pool en auth/conn error por si la contraseña/estado cambia en caliente
|
||||
try {
|
||||
await pool.end()
|
||||
} catch (_) {}
|
||||
pool = null
|
||||
continue
|
||||
}
|
||||
|
||||
throw error
|
||||
}
|
||||
|
||||
return result
|
||||
} catch (error) {
|
||||
console.error('Error ejecutando query:', { text, params, error })
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user