gohorsejobs/seeder-api/src/db.js
Tiago Yamamoto 2ed84f6d56 refactor(seeder): convert to API service and fix SSL connection
- Refactored seeder to Express API with /seed and /reset endpoints
- Updated Dockerfile to run server.js
- Fixed DB connection for managed postgres (stripped sslmode)
- Fixed tags seeder export syntax
- Preserved CLI functionality
2026-01-02 09:19:01 -03:00

68 lines
1.7 KiB
JavaScript

import pg from 'pg';
import dotenv from 'dotenv';
dotenv.config();
const { Pool } = pg;
const {
DATABASE_URL,
DB_HOST = 'localhost',
DB_PORT = '5432',
DB_USER = 'postgres',
DB_PASSWORD = 'postgres',
DB_NAME = 'gohorsejobs',
DB_SSLMODE = 'disable',
} = process.env;
const config = DATABASE_URL
? {
// Remove sslmode from connection string to avoid conflicts
connectionString: DATABASE_URL.replace('?sslmode=require', '').replace('&sslmode=require', ''),
ssl: { rejectUnauthorized: false }
}
: {
host: DB_HOST,
port: Number(DB_PORT),
user: DB_USER,
password: DB_PASSWORD,
database: DB_NAME,
ssl: DB_SSLMODE === 'require' ? { rejectUnauthorized: false } : false,
};
console.log('🔌 DB Config:', {
...config,
connectionString: config.connectionString ? '***' : undefined,
password: '***'
});
// Database connection configuration
export const pool = new Pool(config);
// Test database connection
export async function testConnection() {
try {
const client = await pool.connect();
console.log('✅ Database connected successfully');
client.release();
return true;
} catch (error) {
console.error('❌ Database connection failed:', error.message);
return false;
}
}
// Execute a query
export async function query(text, params) {
const start = Date.now();
const res = await pool.query(text, params);
const duration = Date.now() - start;
console.log('Executed query', { text, duration, rows: res.rowCount });
return res;
}
// Close the pool
export async function closePool() {
await pool.end();
console.log('Database connection pool closed');
}