Skip to content

Commit

Permalink
Fixes for persistent postgres example (#230)
Browse files Browse the repository at this point in the history
* fix: point at the correct spot for pgsql volumes
* check that there is a product table first
* catch error when table hasnn't been created yet

fixes #228
  • Loading branch information
lholmquist authored Jul 12, 2021
1 parent 5f59d82 commit a851768
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 9 deletions.
2 changes: 1 addition & 1 deletion .openshift/postgresql-template-persistent.json
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,7 @@
"volumeMounts": [
{
"name": "${DATABASE_SERVICE_NAME}-data",
"mountPath": "/var/lib/postgresql/data"
"mountPath": "/var/lib/pgsql/data"
}
]
}
Expand Down
28 changes: 20 additions & 8 deletions lib/db/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,26 @@
const { Pool } = require('pg');

const serviceHost = process.env.MY_DATABASE_SERVICE_HOST || process.env.POSTGRESQL_SERVICE_HOST || 'localhost';
const user = process.env.DB_USERNAME || process.env.POSTGRESQL_USER || 'user';
const password = process.env.DB_PASSWORD || process.env.POSTGRESQL_PASSWORD || 'password';
const user = process.env.DB_USERNAME || process.env.POSTGRESQL_USER || 'luke';
const password = process.env.DB_PASSWORD || process.env.POSTGRESQL_PASSWORD || 'secret';
const databaseName = process.env.POSTGRESQL_DATABASE || 'my_data';
const connectionString = `postgresql://${user}:${password}@${serviceHost}:5432/${databaseName}`;

const pool = new Pool({
connectionString
});

let didInitHappen = false;
async function didInitHappen () {
const query = 'select * from products';

try {
await pool.query(query);
console.log('Database Already Created');
return true;
} catch (err) {
return false;
}
}

// -- Create the products table if not present
const initScript = `CREATE TABLE IF NOT EXISTS products (
Expand All @@ -28,17 +38,19 @@ INSERT INTO products (name, stock) values ('Pear', 10);`;

async function query (text, parameters) {
// Check that we have initialized the DB on each Query request
if (!didInitHappen) {
const initHappened = await didInitHappen();
if (!initHappened) {
await init();
}

return pool.query(text, parameters);
}

function init () {
return pool.query(initScript).then(() => {
didInitHappen = true;
});
async function init () {
const initHappened = await didInitHappen();
if (!initHappened) {
return pool.query(initScript);
}
}

module.exports = {
Expand Down

0 comments on commit a851768

Please sign in to comment.