Skip to content

Commit

Permalink
Merge 140761d into 9643f27
Browse files Browse the repository at this point in the history
  • Loading branch information
veyh committed Sep 7, 2021
2 parents 9643f27 + 140761d commit ab9f62f
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 ab9f62f

Please sign in to comment.