1.0.9 • Published 7 months ago
kafka-common-lib v1.0.9
Kafka Common Library
A common library for sending and receiving Kafka messages using NestJS. This package encapsulates Kafka connection handling and provides an interface for sending and receiving messages. It also supports optional message validation.
Installation
To use this package, you need to install it from npm:
npm install kafka-common-library
You can configure Kafka by passing an object with `clientId`, `brokers`, and `groupId` to the `KafkaModule.register()` method:
```typescript
KafkaModule.register({
clientId: 'my-app',
brokers: ['localhost:9092'],
groupId: 'my-group',
});
Usage
1. Import the Module
In your NestJS application, import the KafkaModule into your module:
import { Module } from '@nestjs/common';
import { KafkaModule } from 'kafka-common-library';
@Module({
imports: [KafkaModule],
providers: [AppService],
})
export class AppModule {}
2. Use the Kafka Service
Inject the KafkaService into your service or controller:
import { Injectable, OnModuleInit } from '@nestjs/common';
import { KafkaService, MessageDto } from 'kafka-common-library';
@Injectable()
export class AppService implements OnModuleInit {
constructor(private readonly kafkaService: KafkaService) {}
async onModuleInit() {
// Example of sending a message
const message: MessageDto = { key: 'exampleKey', value: 123 };
const isValid = await this.kafkaService.validateMessage(MessageDto, message);
if (isValid) {
await this.kafkaService.sendMessage('example-topic', message);
}
// Example of receiving messages
await this.kafkaService.receiveMessages('example-topic', async (payload) => {
console.log('Received message:', payload.message.value.toString());
});
}
}