Skip to content

ClientsContainer

reference
1 min readUpdated

Kind: Class

Source: packages/microservices/container.ts

Part of: Microservices

ClientsContainer manages a collection of ClientProxy instances used by the microservices layer. It provides a central place to register clients, retrieve all registered clients, and clear the collection during cleanup or lifecycle transitions.

Methods

MethodSignatureReturns
getAllClientsgetAllClients()ClientProxy[]
addClientaddClient(client: ClientProxy)void
clearclear()void

Diagram

mermaid
graph LR
  A[ClientProxy] -->|addClient()| B[ClientsContainer]
  B -->|getAllClients()| C[ClientProxy[]]
  B -->|clear()| D[Empty client collection]

Usage

ts
import {
  ClientProxyFactory,
  ClientsContainer,
  Transport,
} from '@nestjs/microservices';

const clientsContainer = new ClientsContainer();

const ordersClient = ClientProxyFactory.create({
  transport: Transport.TCP,
  options: {
    host: 'localhost',
    port: 3001,
  },
});

clientsContainer.addClient(ordersClient);

const clients = clientsContainer.getAllClients();

for (const client of clients) {
  await client.connect();
}

// Remove registered client references during cleanup.
clientsContainer.clear();

AI Coding Instructions

  • Register each ClientProxy with addClient() before expecting it to be available through getAllClients().
  • Treat getAllClients() as the source of registered clients when implementing bulk connection, shutdown, or health-check behavior.
  • Ensure client lifecycle cleanup is handled explicitly; clearing the container removes registrations but may not close active client connections.
  • Avoid creating duplicate client registrations for the same logical service without first considering the intended replacement or cleanup behavior.
  • Keep ClientsContainer focused on client registration and lookup rather than transport-specific messaging logic.

Was this page helpful?

Download as PDF
ClientsContainer — NestJS head-to-head