Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

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

License

NotificationsYou must be signed in to change notification settings

andywer/pg-listen

Repository files navigation

Postgres LISTEN & NOTIFY that works

Build StatusNPM 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 PostgresNOTIFY statement and subscribes to notifications usingLISTEN.

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

importcreateSubscriberfrom"pg-listen"import{databaseURL}from"./config"// Accepts the same connection config object that the "pg" package would takeconstsubscriber=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()})exportasyncfunctionconnect(){awaitsubscriber.connect()awaitsubscriber.listenTo("my-channel")}exportasyncfunctionsendSampleMessage(){awaitsubscriber.notify("my-channel",{greeting:"Hey, buddy.",timestamp:Date.now()})}

API

For details seedist/index.d.ts.

Error & event handling

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

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

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

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

Thiserror 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 usinginstance.listenTo() in order to receive notifications.

A more convenient way of subscribing to notifications is theinstance.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 theNOTIFY andLISTEN features is not trivial usingnode-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, likepg-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 theDEBUG environment variable topg-listen:* to enable debug logging.

License

MIT


[8]ページ先頭

©2009-2025 Movatter.jp