-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
index.js
166 lines (136 loc) · 4.21 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
/* eslint-disable promise/prefer-await-to-then */
// @ts-check
/// <reference types="node" />
/// <reference types="pg" />
'use strict';
const EventEmitter = require('node:events');
const pgFormat = require('pg-format');
const { ErrorWithCause } = require('pony-cause');
const { pgClientRetry } = require('./lib/client');
// TODO: Move to an async generator approach rather than EventEmitter
/** @typedef {(payload: any) => void} PGPubsubCallback */
class PGPubsub extends EventEmitter {
/** @type {string[]} */
#channels = [];
/** @type {import('promised-retry')} */
#retry;
/**
* @param {string | import('pg').ClientConfig} [conString]
* @param {{ log?: typeof console.log, retryLimit?: number }} options
*/
// eslint-disable-next-line n/no-process-env
constructor (conString = process.env['DATABASE_URL'], { log, retryLimit } = {}) {
super();
this.setMaxListeners(0);
this.#retry = pgClientRetry({
clientOptions: typeof conString === 'object' ? conString : { connectionString: conString },
retryLimit,
log,
shouldReconnect: () => this.#channels.length !== 0,
successCallback: client => {
client.on('notification', msg => this.#processNotification(msg));
Promise.all(this.#channels.map(channel => client.query('LISTEN "' + channel + '"')))
.catch(/** @param {unknown} err */err => {
this.emit(
'error',
new ErrorWithCause('Failed to set up channels on new connection', { cause: err })
);
});
return client;
},
});
}
/**
* @protected
* @param {boolean} [noNewConnections]
* @returns {Promise<import('pg').Client>}
*/
async _getDB (noNewConnections) {
return this.#retry.try(!noNewConnections)
.catch(/** @param {unknown} err */err => {
throw new ErrorWithCause('Failed to establish database connection', { cause: err });
});
}
/**
* @param {import('pg').Notification} msg
* @returns {void}
*/
#processNotification (msg) {
let payload = msg.payload || '';
// If the payload is valid JSON, then replace it with such
try { payload = JSON.parse(payload); } catch {}
this.emit(msg.channel, payload);
}
/**
* @param {string} channel
* @param {PGPubsubCallback} [callback]
* @returns {Promise<void>}
*/
async addChannel (channel, callback) {
if (!this.#channels.includes(channel)) {
this.#channels.push(channel);
// TODO: Can't this possibly result in both the try() method and this method adding a LISTEN for it?
try {
const db = await this._getDB();
await db.query('LISTEN "' + channel + '"');
} catch (err) {
throw new ErrorWithCause('Failed to listen to channel', { cause: err });
}
}
if (callback) {
this.on(channel, callback);
}
}
/**
* @param {string} channel
* @param {PGPubsubCallback} [callback]
* @returns {this}
*/
removeChannel (channel, callback) {
const pos = this.#channels.indexOf(channel);
if (pos === -1) {
return this;
}
if (callback) {
this.removeListener(channel, callback);
} else {
this.removeAllListeners(channel);
}
if (this.listeners(channel).length === 0) {
this.#channels.splice(pos, 1);
this._getDB(true)
.then(db => db.query('UNLISTEN "' + channel + '"'))
.catch(/** @param {unknown} err */err => {
this.emit(
'error',
new ErrorWithCause('Failed to stop listening to channel', { cause: err })
);
});
}
return this;
}
/**
* @param {string} channel
* @param {any} [data]
* @returns {Promise<void>}
*/
async publish (channel, data) {
const payload = data ? ', ' + pgFormat.literal(JSON.stringify(data)) : '';
try {
const db = await this._getDB();
await db.query(`NOTIFY "${channel}"${payload}`);
} catch (err) {
throw new ErrorWithCause('Failed to publish to channel', { cause: err });
}
}
/** @returns {Promise<void>} */
async close () {
this.removeAllListeners();
this.#channels = [];
return this.#retry.end();
}
reset () {
return this.#retry.reset();
}
}
module.exports = PGPubsub;