Skip to content

Commit

Permalink
Merge pull request #13883 from nestjs/fix/nats-client-promise-13880
Browse files Browse the repository at this point in the history
fix(microservices): hold nats client connection promise ref
  • Loading branch information
kamilmysliwiec authored Aug 13, 2024
2 parents e1f1aa9 + 0c84c7e commit 7468810
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 3 deletions.
9 changes: 6 additions & 3 deletions packages/microservices/client/client-nats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ let natsPackage = {} as any;
export class ClientNats extends ClientProxy {
protected readonly logger = new Logger(ClientNats.name);
protected natsClient: Client;
protected clientConnectionPromise: Promise<Client>;

constructor(protected readonly options: NatsOptions['options']) {
super();
Expand All @@ -30,13 +31,15 @@ export class ClientNats extends ClientProxy {
public async close() {
await this.natsClient?.close();
this.natsClient = null;
this.clientConnectionPromise = null;
}

public async connect(): Promise<any> {
if (this.natsClient) {
return this.natsClient;
if (this.clientConnectionPromise) {
return this.clientConnectionPromise;
}
this.natsClient = await this.createClient();
this.clientConnectionPromise = this.createClient();
this.natsClient = await this.clientConnectionPromise;
this.handleStatusUpdates(this.natsClient);
return this.natsClient;
}
Expand Down
1 change: 1 addition & 0 deletions packages/microservices/test/client/client-nats.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,7 @@ describe('ClientNats', () => {
describe('when is not connected', () => {
beforeEach(async () => {
client['natsClient'] = null;
client['clientConnectionPromise'] = null;
await client.connect();
});
it('should call "handleStatusUpdatesSpy" once', async () => {
Expand Down

0 comments on commit 7468810

Please sign in to comment.