mirror of
https://git.coastit.co.za/caitlin/CRM_ENVR.git
synced 2026-07-10 11:15:43 +02:00
33 lines
843 B
TypeScript
33 lines
843 B
TypeScript
import { Pool } from "pg"
|
|
|
|
const dbUrl = process.env.DATABASE_URL
|
|
if (!dbUrl) {
|
|
throw new Error("DATABASE_URL environment variable is required")
|
|
}
|
|
const pool = new Pool({
|
|
connectionString: dbUrl,
|
|
max: 20,
|
|
idleTimeoutMillis: 30000,
|
|
connectionTimeoutMillis: 5000,
|
|
ssl: dbUrl.includes("localhost") || dbUrl.includes("127.0.0.1") ? false : { rejectUnauthorized: false },
|
|
})
|
|
|
|
pool.on("error", (err) => {
|
|
console.error("Unexpected database pool error:", err)
|
|
})
|
|
|
|
export async function query(text: string, params?: unknown[], userId?: string) {
|
|
const client = await pool.connect()
|
|
try {
|
|
if (userId) {
|
|
await client.query("SELECT set_config('app.current_user_id', $1, true)", [userId])
|
|
}
|
|
const result = await client.query(text, params)
|
|
return result
|
|
} finally {
|
|
client.release()
|
|
}
|
|
}
|
|
|
|
export default pool
|