Skip to content

Commit 7468810

Browse files
Merge pull request #13883 from nestjs/fix/nats-client-promise-13880
fix(microservices): hold nats client connection promise ref
2 parents e1f1aa9 + 0c84c7e commit 7468810

File tree

2 files changed

+7
-3
lines changed

2 files changed

+7
-3
lines changed

packages/microservices/client/client-nats.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ let natsPackage = {} as any;
1818
export class ClientNats extends ClientProxy {
1919
protected readonly logger = new Logger(ClientNats.name);
2020
protected natsClient: Client;
21+
protected clientConnectionPromise: Promise<Client>;
2122

2223
constructor(protected readonly options: NatsOptions['options']) {
2324
super();
@@ -30,13 +31,15 @@ export class ClientNats extends ClientProxy {
3031
public async close() {
3132
await this.natsClient?.close();
3233
this.natsClient = null;
34+
this.clientConnectionPromise = null;
3335
}
3436

3537
public async connect(): Promise<any> {
36-
if (this.natsClient) {
37-
return this.natsClient;
38+
if (this.clientConnectionPromise) {
39+
return this.clientConnectionPromise;
3840
}
39-
this.natsClient = await this.createClient();
41+
this.clientConnectionPromise = this.createClient();
42+
this.natsClient = await this.clientConnectionPromise;
4043
this.handleStatusUpdates(this.natsClient);
4144
return this.natsClient;
4245
}

packages/microservices/test/client/client-nats.spec.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,7 @@ describe('ClientNats', () => {
253253
describe('when is not connected', () => {
254254
beforeEach(async () => {
255255
client['natsClient'] = null;
256+
client['clientConnectionPromise'] = null;
256257
await client.connect();
257258
});
258259
it('should call "handleStatusUpdatesSpy" once', async () => {

0 commit comments

Comments
 (0)