• Stars
    star
    540
  • Rank 79,035 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 5 years ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

📡 PostgreSQL LISTEN & NOTIFY for node.js that finally works.

pg-listen

Postgres LISTEN & NOTIFY that works

Build Status NPM Version


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

More Repositories

1

webpack-blocks

📦 Configure webpack using functional feature blocks.
JavaScript
2,979
star
2

threads.js

🧵 Make web workers & worker threads as simple as a function call.
TypeScript
2,942
star
3

leakage

🐛 Memory leak testing for node.
JavaScript
1,583
star
4

typed-emitter

🔩 Type-safe event emitter interface for TypeScript
JavaScript
250
star
5

use-inline-memo

⚛️ React hook for memoizing values inline anywhere in a component
TypeScript
163
star
6

postguard

🐛 Statically validate Postgres SQL queries in JS / TS code and derive schemas.
TypeScript
161
star
7

laravel-js-localization

Simple, ease-to-use and flexible package for the Laravel web framework. Allows you to use localized messages of the Laravel webapp (see `resources/lang` directory) in your Javascript code.
PHP
143
star
8

squid

🦑 Provides SQL tagged template strings and schema definition functions.
TypeScript
124
star
9

ava-ts

🚀 Fork of the AVA test runner with native typescript support
JavaScript
116
star
10

postcss-debug

Debug your postcss workflow with ease! Creates snapshots of your CSS files before/after each postcss plugin is run.
JavaScript
94
star
11

react-usestyles

🖍 Style components using React hooks. Abstracts the styling library away.
JavaScript
87
star
12

postcss-theme

PostCSS plugin to enable versatile theming.
JavaScript
87
star
13

react-stateful-fn

⚛ Stateful functional components for React.
JavaScript
57
star
14

puppet-run

🤖 Run anything JavaScript in a headless Chrome from your command line
TypeScript
53
star
15

threadpool-js

Javascript thread pool implementation using web workers.
JavaScript
47
star
16

jquery-dim-background

jQuery plugin to dim the current page except for some user-defined top elements.
JavaScript
43
star
17

observable-fns

🕵️‍♀️ Light-weight observable implementation and functional utilities in TypeScript
TypeScript
41
star
18

npm-launch

🚀 Minimalistic task runner on steroids!
JavaScript
39
star
19

drag-mock

Trigger HTML5 drag & drop events for testing
JavaScript
35
star
20

gear

🛠 Experimental tool to bootstrap typed JavaScript code.
JavaScript
33
star
21

proposal-double-colon-types

🤓 JS / Flow syntax proposal. Types à la Hindley-Milner.
20
star
22

http-event-stream

📡 Modern spec-compliant Server Sent Events stream implementation.
TypeScript
19
star
23

ts

⚙️ The CLI that TypeScript deserves.
TypeScript
18
star
24

key-store

🔐 Isomorphic encrypted key store written in TypeScript.
TypeScript
17
star
25

plow

👨‍🌾 Postgres migrations and seeding made easy
TypeScript
14
star
26

isomorphic-crypto

🔒 Isomorphic crypto package for node and the browser.
JavaScript
12
star
27

type-reflect

☝️ TypeScript plugin providing access to type information at runtime
TypeScript
11
star
28

srv

📡 Functional node server. Composable routing. Take a request, return a response.
TypeScript
9
star
29

rungpt

GPT client with local plugin framework, built by GPT-4
TypeScript
9
star
30

php-easygit

Manage Git repositories from within your PHP webapp. Commit, branch, clone, checkout, ...
PHP
7
star
31

zaster

💸 Headless multi-blockchain wallet and SDK.
TypeScript
7
star
32

react-commandments

📖 Thou shalt honor thy reactive code and keep it holy.
6
star
33

koa-router-index

Koa v2 middleware to create an index page for API servers.
JavaScript
5
star
34

gulp-elixir-modules

Elixir extension for handling frontend modules easily.
JavaScript
5
star
35

json-sql-import

Small PHP tool to import JSON data into database tables using transformation rules.
PHP
4
star
36

puppet-run-plugins

🧩 Plugins for puppet-run.
TypeScript
4
star
37

shutter-legacy

📸 Visual snapshot testing with no effort.
TypeScript
3
star
38

deep-assert

🔍 Better deep-equals comparison, supporting custom property assertions and pretty diffs.
TypeScript
3
star
39

ideabox

Place to collect techy ideas and get feedback.
1
star
40

bundle-decomposition-research

JavaScript
1
star
41

stellar-wallet

With the new Stellar wallet to the moon 🚀
JavaScript
1
star