← back to NationalPaperHangers
lib/db.js
39 lines
const { Pool } = require('pg');
// node-postgres falls back to process.env.PGPASSWORD when `password` is omitted.
// An empty-string PGPASSWORD still triggers SASL auth → fails. Strip it.
if (process.env.PGPASSWORD === '') delete process.env.PGPASSWORD;
// node-postgres requires `password` to be either a non-empty string or omitted
// entirely. Passing `''` triggers SASL auth and fails with
// "client password must be a string".
const pgConfig = {
host: process.env.PGHOST || 'localhost',
port: parseInt(process.env.PGPORT || '5432', 10),
database: process.env.PGDATABASE || 'national_paper_hangers',
user: process.env.PGUSER || process.env.USER,
max: 10,
idleTimeoutMillis: 30000
};
if (process.env.PGPASSWORD && process.env.PGPASSWORD.length > 0) {
pgConfig.password = process.env.PGPASSWORD;
}
const pool = new Pool(pgConfig);
pool.on('error', (err) => {
console.error('[pg pool error]', err.message);
});
module.exports = {
pool,
query: (text, params) => pool.query(text, params),
one: async (text, params) => {
const r = await pool.query(text, params);
return r.rows[0] || null;
},
many: async (text, params) => {
const r = await pool.query(text, params);
return r.rows;
}
};