Legger med env

This commit is contained in:
Håkon Størdal 2025-09-03 00:41:40 +02:00
parent 193b0363e5
commit d7a94ee323
2 changed files with 47 additions and 14 deletions

View file

@ -1,22 +1,44 @@
import { env } from '$env/dynamic/private';
import { Pool } from 'pg';
import { env } from '$env/dynamic/private';
// Create a connection pool
const pool = new Pool({
connectionString: env.DATABASE_URL,
ssl: false
});
// Get DATABASE_URL with fallback
const getDatabaseUrl = () => {
return (
env.DATABASE_URL ||
process.env.DATABASE_URL ||
'postgresql://postgres:password@localhost:5432/egentrening'
);
};
// Lazy pool creation - only create when actually needed
let pool: Pool | null = null;
const getPool = () => {
if (!pool) {
pool = new Pool({
connectionString: getDatabaseUrl(),
ssl: process.env.NODE_ENV === 'production' ? { rejectUnauthorized: false } : false
});
}
return pool;
};
// Simple database client
export const db = {
// Execute a query
async query(text: string, params?: any[]) {
const client = await pool.connect();
try {
const result = await client.query(text, params);
return result;
} finally {
client.release();
const poolInstance = getPool();
const client = await poolInstance.connect();
try {
const result = await client.query(text, params);
return result;
} finally {
client.release();
}
} catch (error) {
console.error('Database query failed:', error);
throw error;
}
},
@ -76,6 +98,9 @@ export const db = {
// Close all connections
async close() {
await pool.end();
if (pool) {
await pool.end();
pool = null;
}
}
};