I'm using knex to access a PostgreSQL database. Now supposed I run my application, and at some point in time the database crashes.
How do I figure this out?
Is there an event that I can subscribe to to get informed?
Something such as:
knex.on('disconnect', () => {
// ...
});
Or similar?
PS: I have seen that there were issues on this in the past as well (e.g., #407, #522, …), but none of them really comes up with a suitable and working solution.
We had another look at it, and what we did _not_ want to do is to periodically run queries against the database such as SELECT 1.
Hence, we decided to check the underlying TCP/IP connection, which emits an end event on the client. This client you need to build by yourself, either using knex.client.driver.Client or by using pg.Client directly.
Anyway, sample code looks like this:
'use strict';
const parse = require('pg-connection-string').parse;
const pg = require('pg');
const connectionString = 'postgres://user:[email protected]:5432/mydb';
const client = new pg.Client(parse(connectionString));
client.connect(err => {
client.on('end', () => {
console.log('end');
});
});
Most helpful comment
We had another look at it, and what we did _not_ want to do is to periodically run queries against the database such as
SELECT 1.Hence, we decided to check the underlying TCP/IP connection, which emits an
endevent on the client. This client you need to build by yourself, either usingknex.client.driver.Clientor by usingpg.Clientdirectly.Anyway, sample code looks like this: