PG PubSub
A Publish/Subscribe implementation on top of PostgreSQL NOTIFY/LISTEN
Installation
npm install pg-pubsub --save
Requirements
Usage
const PGPubsub = require('pg-pubsub');
const pubsubInstance = new PGPubsub(uri[, options]);
Options
{
[log]: Function
}
Methods
- addChannel(channelName[, eventListener]) – starts listening on a channel and optionally adds an event listener for that event. As
PGPubsub
inherits from EventEmitter
one can also add it oneself. Returns a Promise
that resolves when the listening has started. - removeChannel(channelName[, eventListener]) – either removes all event listeners and stops listeneing on the channel or removes the specified event listener and stops listening on the channel if that was the last listener attached.
- publish(channelName, data) – publishes the specified data JSON-encoded to the specified channel. It may be better to do this by sending the
NOTIFY channelName, '{"hello":"world"}'
query yourself using your ordinary Postgres pool, rather than relying on the single connection of this module. Returns a Promise
that will become rejected or resolved depending on the success of the Postgres call. - close(): Promise – closes down the database connection and removes all listeners. Useful for graceful shutdowns.
- All EventEmitter methods are inherited from
EventEmitter
Examples
Simple
const pubsubInstance = new PGPubsub('postgres://username@localhost/database');
await pubsubInstance.addChannel('channelName', function (channelPayload) {
});
await pubsubInstance.publish('channelName', { hello: "world" });
The above sends NOTIFY channelName, '{"hello":"world"}'
to PostgreSQL, which will trigger the above listener with the parsed JSON in channelPayload
.
Advanced
const pubsubInstance = new PGPubsub('postgres://username@localhost/database');
await pubsubInstance.addChannel('channelName');
pubsubInstance.once('channelName', channelPayload => {
});
Description
Creating a PGPubsub
instance will not do much up front. It will prepare itself to start a Postgres connection once the first channel is added and then it will keep a connection open until its shut down, reconnecting it if it gets lost, so that it can constantly listen for new notifications.
Lint / Test
- setup a postgres database to run the integration tests
- the easist way to do this is via docker,
docker run -it -p 5432:5432 -e POSTGRES_DB=pgpubsub_test postgres
npm test
For an all-in-one command, try:
docker rm -f pgpubsub_test || true && \
docker run -itd -p 5432:5432 -e POSTGRES_DB=pgpubsub_test --name pgpubsub_test postgres && \
npm test && \
docker rm -f pgpubsub_test