69 lines
1.6 KiB
JavaScript
69 lines
1.6 KiB
JavaScript
|
|
/**
|
||
|
|
* PostgreSQL database client with connection pooling
|
||
|
|
*/
|
||
|
|
import { Pool } from 'pg';
|
||
|
|
/**
|
||
|
|
* Create a PostgreSQL connection pool
|
||
|
|
*/
|
||
|
|
export function createPool(config) {
|
||
|
|
const poolConfig = {
|
||
|
|
connectionString: config.connectionString,
|
||
|
|
host: config.host,
|
||
|
|
port: config.port,
|
||
|
|
database: config.database,
|
||
|
|
user: config.user,
|
||
|
|
password: config.password,
|
||
|
|
max: config.max || 20,
|
||
|
|
idleTimeoutMillis: config.idleTimeoutMillis || 30000,
|
||
|
|
connectionTimeoutMillis: config.connectionTimeoutMillis || 2000,
|
||
|
|
};
|
||
|
|
return new Pool(poolConfig);
|
||
|
|
}
|
||
|
|
/**
|
||
|
|
* Default database pool instance
|
||
|
|
*/
|
||
|
|
let defaultPool = null;
|
||
|
|
/**
|
||
|
|
* Get or create the default database pool
|
||
|
|
*/
|
||
|
|
export function getPool(config) {
|
||
|
|
if (!defaultPool) {
|
||
|
|
if (!config) {
|
||
|
|
throw new Error('Database configuration required for first pool creation');
|
||
|
|
}
|
||
|
|
defaultPool = createPool(config);
|
||
|
|
}
|
||
|
|
return defaultPool;
|
||
|
|
}
|
||
|
|
/**
|
||
|
|
* Execute a query
|
||
|
|
*/
|
||
|
|
export async function query(text, params) {
|
||
|
|
if (!defaultPool) {
|
||
|
|
throw new Error('Database pool not initialized. Call getPool() with configuration first.');
|
||
|
|
}
|
||
|
|
return defaultPool.query(text, params);
|
||
|
|
}
|
||
|
|
/**
|
||
|
|
* Close the database pool
|
||
|
|
*/
|
||
|
|
export async function closePool() {
|
||
|
|
if (defaultPool) {
|
||
|
|
await defaultPool.end();
|
||
|
|
defaultPool = null;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
/**
|
||
|
|
* Health check for database connection
|
||
|
|
*/
|
||
|
|
export async function healthCheck() {
|
||
|
|
try {
|
||
|
|
const pool = getPool();
|
||
|
|
await pool.query('SELECT 1');
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
catch {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
//# sourceMappingURL=client.js.map
|