Objective:
When a new record is inserted into a specific PostgreSQL table, I would like PostgreSQL to notify my node.js web application so that it can initiate an API call to an external service.
I understand the basic steps are:
- Establish a PostgreSQL trigger function which will perform pg_notify() method.
- Establish a PostgreSQL trigger which will execute the trigger function after table insert.
- Establish a mechanism in node.js to listen to channel-specific PostgreSQL notification.
Here is my attempt at each step:
Trigger function in notify_app_after_table_insert.pgsql
CREATE OR REPLACE FUNCTION notify_app_after_table_insert() RETURNS TRIGGER AS $BODY$ BEGIN PERFORM pg_notify('channel', row_to_json(NEW)::text); RETURN new; END; $BODY$ LANGUAGE plpgsql
Trigger in trigger_notify_app_after_table_insert.sql
CREATE TRIGGER trigger_notify_app_after_table_insert AFTER INSERT ON table FOR EACH ROW EXECUTE PROCEDURE notify_app_after_table_insert();
Listener mechanism in index.js (inside my web app's backend)
//tools const express = require('express'); const app = express(); const cors = require('cors'); const bodyParser = require('body-parser'); const port = 3001; const pool = require('./db'); //stores my postgresql credentials // Middleware app.use(cors()) app.use(bodyParser.json()) app.use(bodyParser.urlencoded({extended: true})) // Apply app.listen notification to console.log app.listen(port, () => { console.log(`App running on port ${port}.`) }) // Apply channel-specific listener mechanism pool.connect(function(err, client, done) { if(err) { console.log(err); } client.on('notification', function(msg) { console.log(msg); }) client.query("LISTEN channel"); done(); });
Problem:
When the backend web-app server is running and a new record is inserted in the db table, I expect to see a notification message in my web-app's terminal, but nothing appears. I suspect the problem is in the last code block of index.js, but haven't been able to isolate it.
Any suggestions on how to correctly receive the notification in index.js? Thanks in advance.
done();
closes the connection. Drop it. – Eduardo