Skip to content

Commit

Permalink
fix: ensure connect event is fired only once
Browse files Browse the repository at this point in the history
When connect() failed and it started reconnecting, it kept adding more
and more listeners to pgClient connect event, and when it finally
fired, all those listeners would also fire. So if it had to reconnect 5
times before succeeding, the connect event would have been fired 6
times.
  • Loading branch information
veyh committed Sep 7, 2021
1 parent 9643f27 commit 140761d
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
21 changes: 17 additions & 4 deletions src/PgPubSub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -330,14 +330,27 @@ export class PgPubSub extends EventEmitter {
*/
public async connect(): Promise<void> {
return new Promise((resolve, reject) => {
this.setOnceHandler(['end', 'error'], this.reconnect);
this.pgClient.once('connect', async () => {
const onConnect = async () => {
await this.setAppName();
await this.setProcessId();
this.emit('connect');
resolve();
});
this.once('error', reject);
cleanup();
};

const onError = (err: any) => {
reject(err);
cleanup();
};

const cleanup = () => {
this.pgClient.off('connect', onConnect);
this.pgClient.off('error', onError);
};

this.setOnceHandler(['end', 'error'], this.reconnect);
this.pgClient.once('connect', onConnect);
this.once('error', onError);

// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.pgClient.connect();
Expand Down
20 changes: 20 additions & 0 deletions test/src/PgPubSub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,26 @@ describe('PgPubSub', () => {

pubSub.connect().catch(() => { /**/ });
});
it('should fire connect event only once', done => {
let connectCalls = 0;

// emulate termination
(pgClient as any).connect = () => {
if (connectCalls < 1) {
pgClient.emit('error');
}

else {
pgClient.emit('connect');
}

connectCalls++;
};

// test will fail if done is called more than once
pubSub.on('connect', done);
pubSub.connect().catch(() => { /**/ });
});
it('should support automatic reconnect on errors', done => {
let counter = 0;

Expand Down

0 comments on commit 140761d

Please sign in to comment.