目标:
当向特定的PostgreSQL表中插入新记录时,我希望PostgreSQL通知我的node.js Web应用程序,以便它可以启动对外部服务的API调用。
我了解基本步骤如下:
- 建立一个执行pg_notify()方法的PostgreSQL触发器函数。
- 建立一个在表插入后执行触发器函数的PostgreSQL触发器。
- 建立一个在node.js中监听特定频道PostgreSQL通知的机制。
以下是各个步骤的具体说明:
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(); });
当后端web应用程序服务器正在运行并插入db表中的新记录时,我希望在我的web应用程序终端中看到通知消息,但是没有任何东西出现。我怀疑问题出在index.js的最后一个代码块中,但一直没有能够隔离它。
有关如何在index.js中正确接收通知的任何建议?提前致谢。