CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-nestjs--microservices

Nest microservices framework providing scalable distributed systems with multiple transport layers and communication patterns.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

client-proxies.mddocs/

Client Proxies

Client-side communication interface for sending messages and events to microservices with support for multiple transport protocols including TCP, Redis, NATS, MQTT, gRPC, RabbitMQ, and Kafka.

Capabilities

ClientProxy Base Class

Abstract base class for all microservice client implementations providing core communication methods.

/**
 * Abstract base class for all microservice client implementations
 */
abstract class ClientProxy<EventsMap = any, Status = any> {
  /** Current connection status as observable */
  readonly status: Observable<Status>;
  
  /** Establishes connection to the microservice server/broker */
  connect(): Promise<any>;
  
  /** Closes the underlying connection */
  close(): any;
  
  /** 
   * Send message with response expectation (request-response pattern)
   * @param pattern - Message pattern for routing
   * @param data - Payload data to send
   * @returns Observable with response data
   */
  send<TResult = any, TInput = any>(
    pattern: any,
    data: TInput
  ): Observable<TResult>;
  
  /** 
   * Emit event without response expectation (fire-and-forget pattern)
   * @param pattern - Event pattern for routing
   * @param data - Event data to emit
   * @returns Observable for completion tracking
   */
  emit<TResult = any, TInput = any>(
    pattern: any,
    data: TInput
  ): Observable<TResult>;
  
  /** 
   * Register event listener for client events
   * @param event - Event name to listen for
   * @param callback - Event callback function
   */
  on<EventKey, EventCallback>(
    event: EventKey,
    callback: EventCallback
  ): void;
  
  /** 
   * Returns the underlying server/broker instance
   * @returns Unwrapped transport-specific instance
   */
  unwrap<T = any>(): T;
}

Usage Examples:

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

// Create client
const client: ClientProxy = ClientProxyFactory.create({
  transport: Transport.TCP,
  options: { host: '127.0.0.1', port: 3001 }
});

// Connect to server
await client.connect();

// Send request-response message
const result = await client.send({ cmd: 'get_user' }, { id: 1 }).toPromise();

// Emit fire-and-forget event
client.emit('user_logged_in', { userId: 1, timestamp: Date.now() });

// Listen to connection events
client.on('connect', () => console.log('Connected to microservice'));

// Close connection
await client.close();

ClientProxyFactory

Factory class for creating client proxy instances based on transport configuration.

/**
 * Factory for creating client proxy instances
 */
class ClientProxyFactory {
  /**
   * Create a client proxy instance based on transport options
   * @param clientOptions - Configuration for the client transport
   * @returns ClientProxy instance for the specified transport
   */
  static create(clientOptions: ClientOptions): ClientProxy;
}

interface ClientOptions {
  transport: Transport | CustomTransportStrategy;
  options?: any;
}

Usage Examples:

// TCP client
const tcpClient = ClientProxyFactory.create({
  transport: Transport.TCP,
  options: { host: '127.0.0.1', port: 3001 }
});

// Redis client
const redisClient = ClientProxyFactory.create({
  transport: Transport.REDIS,
  options: { host: 'localhost', port: 6379 }
});

// NATS client
const natsClient = ClientProxyFactory.create({
  transport: Transport.NATS,
  options: { servers: ['nats://localhost:4222'] }
});

Transport-Specific Clients

ClientTCP

TCP transport client implementation with socket-based communication.

class ClientTCP extends ClientProxy<TcpEvents, TcpStatus> {
  constructor(options: TcpClientOptions);
}

interface TcpClientOptions {
  host?: string;
  port?: number;
  socketClass?: any;
  tlsOptions?: any;
}

enum TcpStatus {
  DISCONNECTED = 0,
  CONNECTED = 1
}

ClientRedis

Redis transport client implementation using pub/sub pattern.

class ClientRedis extends ClientProxy<RedisEvents, RedisStatus> {
  constructor(options: RedisOptions);
  
  /** Get request pattern for Redis pub/sub */
  getRequestPattern(pattern: string): string;
  
  /** Get reply pattern for Redis pub/sub */
  getReplyPattern(pattern: string): string;
}

enum RedisStatus {
  DISCONNECTED = 0,
  RECONNECTING = 1,
  CONNECTED = 2
}

ClientNats

NATS transport client implementation with subject-based messaging.

class ClientNats extends ClientProxy<NatsEvents, NatsStatus> {
  constructor(options: NatsOptions);
  
  /** Create NATS client instance */
  createClient(): Promise<any>;
  
  /** Handle connection status updates */
  handleStatusUpdates(client: any): void;
}

enum NatsStatus {
  DISCONNECTED = 0,
  RECONNECTING = 1,
  CONNECTED = 2
}

ClientMqtt

MQTT transport client implementation for IoT and lightweight messaging.

class ClientMqtt extends ClientProxy<MqttEvents, MqttStatus> {
  constructor(options: MqttClientOptions);
  
  /** Get request pattern for MQTT topics */
  getRequestPattern(pattern: string): string;
  
  /** Get response pattern for MQTT topics */
  getResponsePattern(pattern: string): string;
}

enum MqttStatus {
  DISCONNECTED = 0,
  RECONNECTING = 1,
  CONNECTED = 2,
  CLOSED = 3
}

ClientRMQ

RabbitMQ transport client implementation with queue-based messaging.

class ClientRMQ extends ClientProxy<RmqEvents, RmqStatus> {
  constructor(options: RmqOptions);
  
  /** Create RabbitMQ channel */
  createChannel(): Promise<void>;
  
  /** Setup RabbitMQ channel with configuration */
  setupChannel(channel: any, resolve: Function): void;
}

enum RmqStatus {
  DISCONNECTED = 0,
  CONNECTED = 1
}

ClientKafka

Kafka transport client implementation with high-throughput streaming support.

class ClientKafka extends ClientProxy<any, KafkaStatus> {
  constructor(options: KafkaOptions);
  
  /** Subscribe to response topic for request-response pattern */
  subscribeToResponseOf(pattern: unknown): void;
  
  /** 
   * Emit batch of messages for high-throughput scenarios
   * @param pattern - Message pattern
   * @param data - Batch data with messages array
   * @returns Observable for batch processing results
   */
  emitBatch<TResult = any, TInput = any>(
    pattern: any,
    data: { messages: TInput[] }
  ): Observable<TResult>;
  
  /** 
   * Commit Kafka consumer offsets manually
   * @param topicPartitions - Topic partition offset data
   */
  commitOffsets(topicPartitions: TopicPartitionOffsetAndMetadata[]): Promise<void>;
}

enum KafkaStatus {
  DISCONNECTED = 0,
  CONNECTED = 1,
  CRASHED = 2,
  STOPPED = 3,
  REBALANCING = 4
}

ClientGrpcProxy

gRPC transport client implementation with protocol buffer support.

class ClientGrpcProxy extends ClientProxy implements ClientGrpc {
  constructor(options: GrpcOptions);
  
  /** 
   * Get gRPC service by name
   * @param name - Service name from proto definition
   * @returns Typed service interface
   */
  getService<T = any>(name: string): T;
  
  /** 
   * Get gRPC client by service name
   * @param name - Service name from proto definition  
   * @returns Typed client interface
   */
  getClientByServiceName<T = any>(name: string): T;
  
  /** Create unary gRPC service method */
  createUnaryServiceMethod(client: any, methodName: string): Function;
  
  /** Create streaming gRPC service method */
  createStreamServiceMethod(client: unknown, methodName: string): Function;
}

interface ClientGrpc {
  getService<T = any>(name: string): T;
  getClientByServiceName<T = any>(name: string): T;
}

Usage Examples:

// Kafka batch operations
const kafkaClient = ClientProxyFactory.create({
  transport: Transport.KAFKA,
  options: {
    client: { clientId: 'my-client', brokers: ['localhost:9092'] }
  }
});

await kafkaClient.emitBatch('user.events', {
  messages: [
    { userId: 1, action: 'login' },
    { userId: 2, action: 'logout' },
    { userId: 3, action: 'signup' }
  ]
}).toPromise();

// gRPC service usage
const grpcClient = ClientProxyFactory.create({
  transport: Transport.GRPC,
  options: {
    package: 'hero',
    protoPath: path.join(__dirname, 'hero.proto'),
    url: 'localhost:5000'
  }
}) as ClientGrpc;

const heroService = grpcClient.getService<HeroService>('HeroService');
const hero = await heroService.findOne({ id: 1 }).toPromise();

docs

client-proxies.md

context-objects.md

exceptions.md

grpc.md

index.md

message-patterns.md

modules.md

transports.md

tile.json