You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
68 lines
1.8 KiB
68 lines
1.8 KiB
import { Pool } from "pg";
|
|
|
|
// Database configuration
|
|
export interface DatabaseConfig {
|
|
host: string;
|
|
port: number;
|
|
database: string;
|
|
username: string;
|
|
password: string;
|
|
}
|
|
|
|
export function getDatabaseConfig(): DatabaseConfig {
|
|
// Parse DATABASE_URL if it exists, otherwise use individual env vars
|
|
if (process.env.DATABASE_URL) {
|
|
const url = new URL(process.env.DATABASE_URL);
|
|
return {
|
|
host: url.hostname,
|
|
port: parseInt(url.port) || 5432,
|
|
database: url.pathname.slice(1), // Remove leading slash
|
|
username: url.username,
|
|
password: url.password,
|
|
};
|
|
}
|
|
|
|
return {
|
|
host: process.env.DB_HOST || "localhost",
|
|
port: parseInt(process.env.DB_PORT || "5432"),
|
|
database: process.env.DB_NAME || "reya_render",
|
|
username: process.env.DB_USER || "miranshala",
|
|
password: process.env.DB_PASSWORD || "",
|
|
};
|
|
}
|
|
|
|
// Create a connection pool
|
|
let pool: Pool | null = null;
|
|
|
|
export function getPool(): Pool {
|
|
if (!pool) {
|
|
const config = getDatabaseConfig();
|
|
pool = new Pool({
|
|
host: config.host,
|
|
port: config.port,
|
|
database: config.database,
|
|
user: config.username,
|
|
password: config.password,
|
|
max: 20, // Maximum number of clients in the pool
|
|
idleTimeoutMillis: 30000, // Close idle clients after 30 seconds
|
|
connectionTimeoutMillis: 2000, // Return an error after 2 seconds if connection could not be established
|
|
});
|
|
}
|
|
return pool;
|
|
}
|
|
|
|
// Test database connection
|
|
export async function testConnection(): Promise<boolean> {
|
|
try {
|
|
const pool = getPool();
|
|
const client = await pool.connect();
|
|
await client.query("SELECT NOW()");
|
|
client.release();
|
|
console.log("Database connection successful");
|
|
return true;
|
|
} catch (error) {
|
|
console.error("Database connection failed:", error);
|
|
return false;
|
|
}
|
|
}
|