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.