'use strict';

const fs = require('fs');
const escape = require('pg-escape');

const hasDBAvailable = Boolean(process.env.DB);

if (!hasDBAvailable) {
  module.exports = {};
  return;
}

const pgConfig = {
  host: 'localhost',
  user: process.env.PGUSER || 'hmbserver',
  password: process.env.PGPASSWORD || fs.readFileSync('db-password', {encoding: 'utf8'}),
  database: process.env.PGDATABASE || 'hmb'
};

const Pool = require('pg').Pool;
const pgPool = new Pool(pgConfig);
pgPool.on('error', (err, client) => {
  logger.error('Idle psql client error', {
    errorMsg: err.message,
    errorStack: err.stack,
    client
  });
});

function insertUser(username, email, passwordHash) {
  return pgPool.query('insert into users values($1, $2, \'\', $3)', [
    escape.string(username),
    escape.string(email),
    passwordHash
  ]);
}

module.exports = {
  hasDBAvailable,
  pgPool,
  insertUser
};

@@ -34,16 +34,46 @@
 ('fs');%0A
+const path = require('path');%0A
 const es
@@ -210,16 +210,105 @@
 urn;%0A%7D%0A%0A
+const pgPass = fs.readFileSync(path.join(__dirname, 'db-password'), %7Bencoding: 'utf8'%7D);%0A
 const pg
@@ -424,58 +424,14 @@
  %7C%7C 
-fs.readFileSync('db-password', %7Bencoding: 'utf8'%7D)
+pgPass
 ,%0A  

Fix path handling for db-password