Skip to content

subscribe to postgres events in node via LISTEN/NOTIFY apis

Notifications You must be signed in to change notification settings

cdaringe/pg-subscribe

Repository files navigation

pg-subscribe

CircleCI JavaScript Style Guide semantic-release Greenkeeper badge

subscribe to postgres events via postgresql notify/listen

this is a fork of pg-pub-sub to address some open issues, provide 1st class typescript support, and improve the api.

install

npm install pg-subscribe --save

usage

basic

import { PgSubscriber } from 'pg-subscribe'
var subscriber = new PgSubscriber('postgres://username@localhost/database')
await subscriber.addChannel('channelName', function onNotify (channelPayload) {
  // Process the payload – if it was JSON that JSON has been parsed into an object for you
})
await subscriber.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

import { PgSubscriber } from 'pg-subscribe'
var subscriber = new PgSubscriber('postgres://username@localhost/database')
await subscriber.addChannel('channelName')
// subscriber is a full EventEmitter object that sends events on channel names
subscriber.once('channelName', function (channelPayload) {
  // do great work!
})

api

a copy of the latest typings can always be found here