Files
Duriin-API/src/db/pgAsync.js
T

25 lines
863 B
JavaScript

const { Pool } = require('pg');
const pools = new Map();
function postgresUrl() { return process.env.DURIIN_POSTGRES_URL || process.env.DATABASE_URL; }
function poolFor(schema = 'intelligence') {
const connectionString = postgresUrl();
if (!connectionString) throw new Error('DURIIN_POSTGRES_URL is required');
const key = `${connectionString}|${schema}`;
if (!pools.has(key)) {
pools.set(key, new Pool({
connectionString,
max: Math.max(1, Number(process.env.POSTGRES_HTTP_POOL_SIZE) || 4),
options: `-c search_path=${schema},public`,
}));
}
return pools.get(key);
}
async function all(schema, sql, params = []) { return (await poolFor(schema).query(sql, params)).rows; }
async function get(schema, sql, params = []) { return (await poolFor(schema).query(sql, params)).rows[0]; }
module.exports = { poolFor, all, get };