Message batcher
npm install @raphaabreu/message-batcherMessageBatcher class is a utility that helps you batch messages and process them in groups. It is useful when you want to reduce the number of operations or API calls by aggregating messages and processing them together.
bash
npm i @raphaabreu/message-batcher
`
Then import the MessageBatcher class:
`typescript
import { MessageBatcher } from '@raphaabreu/message-batcher';
`
$3
To create a new MessageBatcher instance, you need to specify the batchSize and a callback function. The batchSize determines the maximum number of messages that can be processed in one batch. The callback function is called with an array of messages when the batch is ready to be processed.
`typescript
const batchSize = 5;
const callback = async (messages: string[]) => {
// Process messages here
};
const messageBatcher = new MessageBatcher(batchSize, callback);
`
$3
You can add messages to the queue using the add method:
`typescript
messageBatcher.add('message1');
messageBatcher.add(['message2', 'message3']);
`
The add method accepts a single message or an array of messages.
$3
To start the interval timer, call the start method and pass the maxBatchIntervalMs parameter:
`typescript
const maxBatchIntervalMs = 10000; // 10 seconds
messageBatcher.start(maxBatchIntervalMs);
`
The maxBatchIntervalMs determines the maximum interval between message batch processing.
$3
To stop the interval timer, call the stop method:
`typescript
messageBatcher.stop();
`
$3
To stop the interval timer and flush any remaining messages in the queue, call the stopAndFlush method:
`typescript
await messageBatcher.stopAndFlush();
`
$3
You can also manually flush messages using the flush method:
`typescript
await messageBatcher.flush();
`
This can be useful if you want to process messages immediately, without waiting for the interval timer to trigger.
Tests
To run the provided unit tests just execute npm run tests`.