I am building an express application that connects to a postgres database using the pg-promise module.
I would like to ensure that the database connection is successful when starting the application server. In other words, if the connection to the database fails, I'd like to throw an error.
My server.js file is as follows:
const express = require("express");
const databaseConfig= {
"host": "localhost",
"port": 5432,
"database": "library_app",
"user": "postgres"
};
const pgp = require("pg-promise")({});
const db = pgp(databaseConfig);
const app = express();
const port = 5000;
app.listen(port, (err) => {
console.log(`running server on port: ${port}`);
});
The current configuration will start the express server regardless of whether the database connection is valid, which is not the behavior I would like.
I tried browsing the docs but couldn't find a solution. I also tried
const db = pgp(databaseConfig).catch((err) => { // blow up });
but that didn't work because pgp
does not return a promise.