How to ensure the Knex connection in nodejs
Code explains itself
const config = require("../../config");
const pgsql = require('knex')({
client: 'pg',
connection: {
host: config.PGSQL_HOST,
port: config.PGSQL_PORT,
user: config.PGSQL_USER,
password: config.PGSQL_PWD,
database : config.PGSQL_DB
},
useNullAsDefault: true
});
pgsql.raw("SELECT 1").then(() => {
console.log("PostgreSQL connected");
})
.catch((e) => {
console.log("PostgreSQL not connected");
console.error(e);
});
module.exports = pgsql;
This was discussed earlier this week in knex
issue tracker. https://github.com/tgriesser/knex/issues/1886
Making query is a good way to check that connection can be made to database. If no queries are made, pool doesn't necessary create any initial connections (depends on pool settings).
You may also also wire up pool's afterCreate
callback to notify you when ever there is new connection made to database (https://github.com/knex/documentation/pull/17/files).