npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

pg-listen

v1.7.0

Published

PostgreSQL LISTEN & NOTIFY that finally works.

Downloads

139,921

Readme

PostgreSQL can act as a message broker: Send notifications with arbitrary payloads from one database client to others.

Works with node.js 8+ and plain JavaScript or TypeScript 3. Uses the Postgres NOTIFY statement and subscribes to notifications using LISTEN.

Features

    📡  Send and subscribe to messages

    ⏳  Continuous connection health checks

    ♻️  Reconnects automatically

    ❗️  Proper error handling

    👌  Type-safe API


Installation

# using npm:
npm install pg-listen

# using yarn:
yarn add pg-listen

Usage

import createSubscriber from "pg-listen"
import { databaseURL } from "./config"

// Accepts the same connection config object that the "pg" package would take
const subscriber = createSubscriber({ connectionString: databaseURL })

subscriber.notifications.on("my-channel", (payload) => {
  // Payload as passed to subscriber.notify() (see below)
  console.log("Received notification in 'my-channel':", payload)
})

subscriber.events.on("error", (error) => {
  console.error("Fatal database connection error:", error)
  process.exit(1)
})

process.on("exit", () => {
  subscriber.close()
})

export async function connect () {
  await subscriber.connect()
  await subscriber.listenTo("my-channel")
}

export async function sendSampleMessage () {
  await subscriber.notify("my-channel", {
    greeting: "Hey, buddy.",
    timestamp: Date.now()
  })
}

API

For details see dist/index.d.ts.

Error & event handling

instance.events.on("connected", listener: () => void)

The connected event is emitted once after initially establishing the connection and later once after every successful reconnect. Reconnects happen automatically when pg-listen detects that the connection closed or became unresponsive.

instance.events.on("error", listener: (error: Error) => void)

An error event is emitted for fatal errors that affect the notification subscription. A standard way of handling those kinds of errors would be to console.error()-log the error and terminate the process with a non-zero exit code.

This error event is usually emitted after multiple attempts to reconnect have failed.

instance.events.on("notification", listener: ({ channel, payload }) => void)

Emitted whenever a notification is received. You must have subscribed to that channel before using instance.listenTo() in order to receive notifications.

A more convenient way of subscribing to notifications is the instance.notifications event emitter.

instance.events.on("reconnect", listener: (attempt: number) => void)

Emitted when a connection issue has been detected and an attempt to re-connect to the database is started.

instance.notifications.on(channelName: string, listener: (payload: any) => void)

The convenient way of subscribing to notifications. Don't forget to call .listenTo(channelName) to subscribe the Postgres client to this channel in order to receive notifications.

Why another package?

In one sentence: Because none of the existing packages was working reliably in production.

Using the NOTIFY and LISTEN features is not trivial using node-postgres (pg) directly, since you cannot use connection pools and even distinct client connections also tend to time out.

There are already a few packages out there, like pg-pubsub, but neither of them seems to work reliably. Errors are being swallowed, the code is hard to reason about, there is no type-safety, ...

This package aims to fix those shortcomings. Postgres LISTEN & NOTIFY in node that finally works.

Debugging

Set the DEBUG environment variable to pg-listen:* to enable debug logging.

License

MIT