Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres LISTEN / NOTIFY with pg-promise

I am trying to setup a simple LISTEN/NOTIFY functionality in PostgreSQL and notify node.js code using pg-promise library.

The pg code I have scaffolded is

CREATE OR REPLACE FUNCTION notify_trigger() RETURNS trigger AS $$
DECLARE
BEGIN
  RAISE NOTICE '%', 'HI';
  PERFORM pg_notify('watchers', TG_TABLE_NAME || ', tags:,' || NEW.tags );
  RETURN new;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER watched_table_trigger BEFORE INSERT OR UPDATE ON assets
FOR EACH ROW EXECUTE PROCEDURE notify_trigger();

It does notify on psql console.

However when I use pg-promise code, it doesn't output console messages as I would hope. The relevant node.js code:

const pgoptions = require('./pgoptions.config.js');
const connectObject = require('./pgconnect.config.js');
const db = require('pg-promise')(pgoptions)(connectObject);

// added listener code for pg listen / notify
db.connect({direct: true})
    .then(function (sco) {
        sco.client.on('assets', function (data) {
            console.log('Received: ', data);
    });
    return sco.none('LISTEN assets');
})
.catch(function (error) {
    console.error('Error:', error);
});

module.exports = resources;

The nodejs code straight out of the pg-promise's Learn By Example documentation here. I did review the other posts about this topic, but didn't find the pg-promise-based solution.

like image 394
Piyush Mehta Avatar asked Nov 04 '25 07:11

Piyush Mehta


1 Answers

It is not

sco.client.on('assets', function (data) {

it is

sco.client.on('notification', function (data) {

i.e. you are subscribing to the generic notification message, not to the channel name. That's how it is shown the very example you quoted.

UPDATE for 2025

Use pg-listener instead ;)

like image 199
vitaly-t Avatar answered Nov 07 '25 08:11

vitaly-t



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!