npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@tawk.to/nestjs-batch-kafka

v0.1.1

Published

NestJS Kafka Batch Processor

Downloads

406

Readme

Description

Process and Publish Kafka message by batch in NestJS. Cross compatible with ServerKafka and ClientKafka from @nestjs/microservices package.

Installation

$ npm i --save @tawkto/nestjs-batch-kafka

Overview

To use the batch kafka consumer, initialize BatchKafkaServer in your main.ts file by connecting the microservice to your app.

const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {
	// The config is the same as the KafkaOptions from the @nestjs/microservices package
	strategy: new KafkaBatchServer({
		client: {
			brokers: ['localhost:52800', 'localhost:52801'],
        },
        consumer: {
          groupId: 'test',
          heartbeatInterval: 5000,
          sessionTimeout: 30000,
        },
        run: {
          autoCommitInterval: 5000,
          autoCommitThreshold: 100,
          partitionsConsumedConcurrently: 4,
        },
	})
})

Then you can start consuming the events in batches as follow

@BatchProcessor('test')
  async test(
    @Payload() data: any[],
    @Ctx() context: KafkaBatchContext,
  ) {
    const heartbeat = context.getHeartbeat();
    const resolveOffset = context.getResolveOffset();
    const commitOffsetsIfNecessary = context.getCommitOffsetsIfNecessary();

    await heartbeat();

    for (const message of data) {
      console.log(message);
    }

    resolveOffset(context.getMessages().at(-1).offset);
    console.log("Batch resolved");

    await heartbeat();
    await commitOffsetsIfNecessary();
  }

Context

The KafkaBatchContext object provides the necessary components from kafkajs's EachBatchPayload:

Client

The KafkaBatchClient is exactly the same as the KafkaClient from the @nestjs/microservices package, except that client.send method is removed from the client as batch messages should not be used for request-response communication. On top of that, KafkaBatchClient also have the capability to publish batch messages or publish to multiple topics just like in kafkajs.

@Module({
	imports: [
		ClientsModule.register([{
			name: 'KAFKA_BATCH_CLIENT',
			customClass: KafkaBatchClient,
			options: {
				client: {
				brokers: ['localhost:52800', 'localhost:52801'],
				},
				consumer: {
				groupId: 'test',
				heartbeatInterval: 5000,
				sessionTimeout: 30000,
				},
			},
		}]),
	],
})
export class AppModule {}

Then you can inject and use the KafkaBatchClient in your service as follow

@Injectable()
export class AppService {
	constructor(
		@Inject('KAFKA_BATCH_CLIENT')
		private kafkaClient: KafkaBatchClient,
	) {}

	async eventToBatch() {
		this.kafkaClient.emit('test', { example: 'data'});
	}

	async publishBatch() {
		// equivalent to kafkajs producer.send
		this.kafkaClient.emitBatch('test', [{
			example: 'data1'
		}, {
			example: 'data2'
		}])
	}

	async publishBatchTopics() {
		// will publish to two topics, topic1 and topic2
		// equivalent to kafkajs producer.publishBatch
		this.kafkaClient.emitBatchTopics([{
			pattern: 'topic1',
			data: [{ example: 'data11' }, { example: 'data12' }]
		}, {
			pattern: 'topic2',
			data: [{ example: 'data21' }, { example: 'data22' }]
		}])
	}
}

Calling send with the KafkaBatchClient will result in an error.

this.kafkaClient.send('send', { data: 'data'}); // Error