Notify/Listen, Keep connection for ever
Is there any way to keep the connection alive forever (with re-connections maybe) in order to receive notifications from postgres ?
Listen for a connection-related error on the pool, and then re-connect.
I'm trying to figure this out too,
I have listeners that works for a while but stop receiving notifications after a while, I added console.log on "end", "error" and "warning" events but nothing shows up
but maybe this is another issue because the connection still shows up in postgres
fwiw, my attempt looks like that:
const setupEventListener = async () => {
console.log(`setting up postgres handler`);
const client = await pool.connect();
client.on("notification", () => {
console.log(`got a postgres notification`);
// do something
});
client.on("error", () => {
console.log("the end");
});
client.on("error", (err) => {
console.log("something bad has happened!", err.stack, err);
});
client.on("notice", () => {
console.log("something not that bad has happened!");
});
console.log(`setting up postgres listeners`);
await client.query(`listen "log.event"`);
console.log(`ready`);
};
setupEventListener();
As I wrote above:
Listen for a connection-related error on the pool, and then re-connect.
Listen for error on the pool object. You are doing it only on the client object.
This area lacks documentation, it's really unclear what are the best practices to use LISTEN/NOTIFY.
In a previous ticket, you said a client (= one connection, which is what I would expect) should be used, not a pool: https://github.com/brianc/node-postgres/issues/1543#issuecomment-353622236
did something change? it seems really broken to use a pool for that usage.
In a previous ticket, you said a client (= one connection, which is what I would expect) should be used, not a pool: #1543 (comment)
I think the point is that the re-connection/keep-alive process (as per OP's question) should be handled at the pool level. The actual handling of the notify event should be handled at the client level.