Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/andywer/pg-listen
📡 PostgreSQL LISTEN & NOTIFY for node.js that finally works.
https://github.com/andywer/pg-listen
events message-passing nodejs notifications postgresql pubsub typescript
Last synced: 19 days ago
JSON representation
📡 PostgreSQL LISTEN & NOTIFY for node.js that finally works.
- Host: GitHub
- URL: https://github.com/andywer/pg-listen
- Owner: andywer
- License: mit
- Created: 2018-09-29T17:24:15.000Z (about 6 years ago)
- Default Branch: master
- Last Pushed: 2023-10-19T16:41:17.000Z (about 1 year ago)
- Last Synced: 2024-05-17T04:01:30.810Z (6 months ago)
- Topics: events, message-passing, nodejs, notifications, postgresql, pubsub, typescript
- Language: TypeScript
- Size: 378 KB
- Stars: 563
- Watchers: 12
- Forks: 33
- Open Issues: 13
-
Metadata Files:
- Readme: README.md
- Funding: .github/FUNDING.yml
- License: LICENSE
Awesome Lists containing this project
- jimsghstars - andywer/pg-listen - 📡 PostgreSQL LISTEN & NOTIFY for node.js that finally works. (TypeScript)
README
pg-listen
Postgres LISTEN & NOTIFY that works
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`](https://www.postgresql.org/docs/10/static/sql-notify.html) statement and subscribes to notifications using [`LISTEN`](https://www.postgresql.org/docs/10/static/sql-listen.html).
### Features
    📡  Send and subscribe to messages
    ⏳  Continuous connection health checks
    ♻️  Reconnects automatically
    ❗️  Proper error handling
    👌  Type-safe API
---
## Installation
```sh
# using npm:
npm install pg-listen# using yarn:
yarn add pg-listen
```## Usage
```js
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](./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`)](https://www.npmjs.com/package/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