Kind: Interface
Source: packages/microservices/interfaces/client-kafka-proxy.interface.ts
Part of: Microservices
ClientKafkaProxy defines the Kafka client resources managed by a microservice client proxy. It exposes nullable consumer and producer references so the proxy can create, reuse, and clean up Kafka connections during its lifecycle.
Properties
| Property | Type |
|---|---|
consumer | `Consumer |
producer | `Producer |
Diagram
mermaidgraph LR Proxy[Kafka Client Proxy] --> Interface[ClientKafkaProxy] Interface --> Consumer[consumer: Consumer | null] Interface --> Producer[producer: Producer | null] Consumer --> Kafka[Kafka Broker] Producer --> Kafka
Usage
tsimport type { Consumer, Producer } from 'kafkajs';
import type { ClientKafkaProxy } from './client-kafka-proxy.interface';
class KafkaClient implements ClientKafkaProxy {
consumer: Consumer | null = null;
producer: Producer | null = null;
async publish(topic: string, message: unknown) {
if (!this.producer) {
throw new Error('Kafka producer has not been initialized.');
}
await this.producer.send({
topic,
messages: [{ value: JSON.stringify(message) }],
});
}
async close() {
await this.consumer?.disconnect();
await this.producer?.disconnect();
this.consumer = null;
this.producer = null;
}
}
AI Coding Instructions
- Treat
consumerandproduceras optional lifecycle-managed resources; always handle thenullcase before calling Kafka methods. - Initialize Kafka clients before subscribing, consuming, or publishing messages, and reset references to
nullafter disconnecting. - Use the KafkaJS
ConsumerandProducertypes when implementing this interface. - Ensure shutdown logic disconnects both resources safely, using optional chaining or explicit null checks.
Was this page helpful?