node-postgres icon indicating copy to clipboard operation
node-postgres copied to clipboard

Notify/Listen, Keep connection for ever

Open vaggeliskls opened this issue 7 years ago • 5 comments

Is there any way to keep the connection alive forever (with re-connections maybe) in order to receive notifications from postgres ?

vaggeliskls avatar May 24 '18 09:05 vaggeliskls

Listen for a connection-related error on the pool, and then re-connect.

vitaly-t avatar May 30 '18 23:05 vitaly-t

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();

mathroc avatar Oct 10 '18 10:10 mathroc

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.

vitaly-t avatar Oct 10 '18 12:10 vitaly-t

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.

AlexGalays avatar Oct 15 '21 16:10 AlexGalays

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.

snspinn avatar Feb 18 '25 15:02 snspinn