PG PubSub 软件
出版/订阅 邮政通知/邮件
安装
npm install pg-pubsub --save
所需资源
节点.js >= 10.x 邮递: 9.4
使用量
const PGPubsub = require('pg-pubsub');
const pubsubInstance = new PGPubsub(uri[, options]);
选项
{
[log]: Function // default: silent when NODE_ENV=production, otherwise defaults to console.log(...)
}
方法
- 添加Channel( 频道Name [, 事件倾听器]] – 开始在频道上收听,并可选择为该事件添加一个事件收听器. 作为
PGPubsub继承从EventEmitter一个人自己也加. - 删除频道( 频道Name [, 事件倾听器]] – 要么删除所有事件听众并停止在频道上收听,要么删除指定的事件听众并停止在频道上收听,如果这是最后一个附着的听众的话.
- 发布( 频道Name, 数据) – 发布指定数据JSON- 编码到指定频道. 最好还是把电话送过去
NOTIFY channelName, '{"hello":"world"}'使用普通 Postgres 池询问您自己,而不是依赖此模块的单个连接。 a 承诺将被拒绝或解决,取决于Postgres呼叫是否成功. - 关闭 (): 承诺 – 关闭数据库连接并删除所有听众. 对优雅的关闭很有用.
- 全体 事件编辑器方法 从
EventEmitter
实例
简单
const pubsubInstance = new PGPubsub('postgres://username@localhost/database');
pubsubInstance.addChannel('channelName', function (channelPayload) {
// Process the payload – if it was JSON that JSON has been parsed into an object for you
});
pubsubInstance.publish('channelName', { hello: "world" });
以上发送 NOTIFY channelName, '{"hello":"world"}' 到 PostgreSQL, 这将触发上面的听众, 并使用解析过的 JSON channelPayload。 。 。 .
高级
const pubsubInstance = new PGPubsub('postgres://username@localhost/database');
pubsubInstance.addChannel('channelName');
// pubsubInstance is a full EventEmitter object that sends events on channel names
pubsubInstance.once('channelName', function (channelPayload) {
// Process the payload
});
说明
创建一个 PGPubsub 实例不会在前面做很多事情。 它会准备在第一个信道被添加后启动Postgres连接,然后它会保持一个连接打开直到关闭,如果它丢失就重新连接,这样它就可以不断收听新的通知.
林特 / 测试
通过 Make/ Docker 自动化
进行测试的最简单方法是通过 Makefile linux 兼容环境 :
make test
手动执行
如果您想要手动操作测试, 您首先需要访问 PostgreSQL 实例 。 你可以有两种方式:
维娅·多克
docker run --rm -it -p 5432:5432 -e \
POSTGRES_DB=pgpubsub_test -e \
POSTGRES_PASSWORD=postgres postgres
Via 环境文件
您可以创建 环境文件 内 test/.env数字 :
DATABASE_TEST_URL=postgres://postgres:postgres@localhost:5432/postgres
DATABASE_TEST_URL_INVALID_USER=postgres://invalidUser:postgres@localhost:5432/postgres
DATABASE_TEST_URL_INVALID_PASSWORD=postgres://postgres:invalidPassword@localhost:5432/postgres
PostgreSQL 设置完成后,您可以用您的节点环境运行测试 :
npm i
npm test