# kostyak127-nestjs-kafka

> Library provides great nestjs and kafkajs integration.

Latest version **1.0.13** (published 2023-07-07) · UNLICENSED license · 0 weekly downloads

## Install

```sh
npm install kostyak127-nestjs-kafka
pnpm add kostyak127-nestjs-kafka
yarn add kostyak127-nestjs-kafka
bun add kostyak127-nestjs-kafka
```

## Health

**Score 25/100 (F)** — status: abandoned.

Positive: has types; no vulnerabilities; high quality score.

Warnings: low downloads; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.0.13 |
| Published | 2023-07-07 |
| First published | 2023-04-16 |
| Weekly downloads | 0 |
| License | UNLICENSED |
| TypeScript types | bundled |
| Module format | CommonJS |
| Dependencies | 19 |
| Unpacked size | 130.2 KB |
| Known vulnerabilities | 0 (+4 in 4 direct dependencies) |
| Install scripts | no |
| GitHub stars | 1 |
| Author | Korotchenkov Konstantin |
| Maintainers | kostyak127 |

## Links

- npm: https://www.npmjs.com/package/kostyak127-nestjs-kafka
- Repository: https://github.com/kostyak127/nestjs-kafka
- Homepage: https://github.com/kostyak127/nestjs-kafka#readme
- Issues: https://github.com/kostyak127/nestjs-kafka/issues
- npm.io page: https://npm.io/package/kostyak127-nestjs-kafka

## Dependencies (19)

- [joi](https://npm.io/package/joi.md) ^17.7.1
- [zod](https://npm.io/package/zod.md) ^3.20.6
- [rxjs](https://npm.io/package/rxjs.md) ^7.8.0
- [uuid](https://npm.io/package/uuid.md) ^9.0.0
- [fp-ts](https://npm.io/package/fp-ts.md) ^2.13.1
- [io-ts](https://npm.io/package/io-ts.md) ^2.2.20
- [dotenv](https://npm.io/package/dotenv.md) ^16.0.3
- [kafkajs](https://npm.io/package/kafkajs.md) ^2.2.3
- [nodemon](https://npm.io/package/nodemon.md) ^2.0.20
- [ts-node](https://npm.io/package/ts-node.md) ^10.9.1
- [@types/uuid](https://npm.io/package/@types/uuid.md) ^9.0.0
- [@nestjs/core](https://npm.io/package/@nestjs/core.md) ^9.3.8
- [@types/lodash](https://npm.io/package/@types/lodash.md) ^4.14.191
- [@nestjs/common](https://npm.io/package/@nestjs/common.md) ^9.2.1
- [kafkajs-logger](https://npm.io/package/kafkajs-logger.md) ^1.0.0
- [joi-extract-type](https://npm.io/package/joi-extract-type.md) ^15.0.8
- [reflect-metadata](https://npm.io/package/reflect-metadata.md) ^0.1.13
- [@nestjs/event-emitter](https://npm.io/package/@nestjs/event-emitter.md) ^1.3.1
- [@nestjs/platform-express](https://npm.io/package/@nestjs/platform-express.md) ^9.3.9

## Recent versions

- 1.0.13 (latest) — 2023-07-07
- 1.0.12 — 2023-06-12
- 1.0.11 — 2023-06-12
- 1.0.10 — 2023-06-12
- 1.0.9 — 2023-06-12
- 1.0.8 — 2023-06-12
- 1.0.7 — 2023-06-12
- 1.0.6 — 2023-06-12
- 1.0.5 — 2023-05-24
- 1.0.4 — 2023-05-07
- 1.0.3 — 2023-05-07
- 1.0.2 — 2023-05-07
- 1.0.1 — 2023-04-16
- 1.0.0 — 2023-04-16

## README

# kostyak127-nestjs-kafka
Library provides great nestjs and kafkajs integration.

Functionality:
- send messages
- subscribe to topics (string and regexp) from your injectable classes
- subscribe to one topic from many classes or functions
- io-ts, joi, zod message validation
- skip messages rules
- getting message payload by property
- getting message context in function arguments
## Installation
### npm
`npm install kostyak127-nestjs-kafka`
### yarn
`yarn add kostyak127-nestjs-kafka`

## Usage
#### Register module
```javascript
import { KafkaModule } from 'kostyak127-nestjs-kafka';
import { KafkaModuleOption } from '@app/modules/kafka/interfaces';

// put your options here (it is kafkajs options)
let options: KafkaModuleOption;

@Module({
  imports: [KafkaModule.register(options)],
})
export class AppModule {}
```

#### Sending messages
```javascript
import { Injectable } from '@nestjs/common';
import { KafkaClient } from 'kostyak127-nestjs-kafka';

@Injectable()
export class SendMessageService {
  public constructor(private readonly kafkaClient: KafkaClient) {}
  public async sendMessage(message: { foo: 'bar' }, topic: string) {
    await this.kafkaClient.send({
      messages: [{ key: 'myKey', value: JSON.stringify({ message }],
      topic: topic,
    });
  }
}
```

#### Subscripe to topic handler
```javascript
@Injectable()
export class MessageHandlerService {
  @SubscribeToTopic('TOPIC')
  async onMessage() {
    console.log('message handled');
  }
  @SubscribeToTopic(/.*_customers/)
  async onMessage() {
    console.log('regexp message handled');
  }
}
```
#### Message pattern and payload
```javascript
import { Injectable } from '@nestjs/common';
import { KafkaPayload, SubscribeToTopic } from 'kostyak127-nestjs-kafka';

// specify your path to message payload by messagePattern property
// @KafkaPayload returns payload from message
//
// message from kafka : 
//  {
//     "author": "Author",
//     "message": {
//     "object": { "foo": "bar" }
//  }
// }
// messagePattern:  'message.object'
// @KafkaPayload() messagePayload: { foo: 'bar' }
//
@Injectable()
export class MessageHandlerService {
  @SubscribeToTopic('TOPIC', { messagePattern: 'message.object' })
  async onMessage(@KafkaPayload() messagePayload: { foo: 'bar' }) {
    // logs { foo: 'bar' }
    console.log(messagePayload);
  }
}

```

#### Validation
```javascript
import { Injectable } from '@nestjs/common';
import {
  IoTsValidator,
  JoiValidator,
  SubscribeToTopic,
  ZodValidator,
} from 'kostyak127-nestjs-kafka';

// use your favourite validation library. specify it with schema

@Injectable()
export class MessageHandlerService {
  // export const ZodUser = z.object({
  //    userId: z.number(),
  //    name: z.string(),
  //});
  @SubscribeToTopic('zod_validation', { messagePattern: 'message.object' })
  async validateZod(@ZodValidator(ZodUser) user: ZodTypeOf<typeof ZodUser>) {}


  // export const JoiUser = joi.object({
  //    userId: joi.number(),
  //    name: joi.string(),
  //});
  @SubscribeToTopic('joi_validation', { messagePattern: 'message.object' })
  async validateJoi(
    @JoiValidator(JoiUser) user: joi.extractType<typeof JoiUser>,
  ) {}


  // export const IoTsUser = t.type({
  //    userId: t.number,
  //    name: t.string,
  //});
  @SubscribeToTopic('io-ts_validation', { messagePattern: 'message.object' })
  async validateIoTs(
    @IoTsValidator(IoTsUser) user: IoTsTypeOf<typeof IoTsUser>,
  ) {}
}
```

#### Skip messages
```javascript
import { Injectable } from '@nestjs/common';
import { SkipMessage, SubscribeToTopic } from 'kostyak127-nestjs-kafka';

// skip your messages by some value in message
// here is example how to skip message { author: 'THIS_AUTHOR', data: { foo: 'bar' } }

// you can access nested properties using '.' as wildcard
// use field: 'options.author' for message { message: { author: 'THIS_AUTHOR'} }
@Injectable()
export class MessageHandlerService {
  @SkipMessage([{field: 'author', rule: (author) => author === 'THIS_AUTHOR'}])
  @SubscribeToTopic('TOPIC')
  async onMessage() {
    console.log('messages from author would be skipped by this handler');
  }
}
```

#### Kafka context
```javascript
import { Injectable } from '@nestjs/common';
import { KafkaPayload, SubscribeToTopic, KafkaContext } from 'kostyak127-nestjs-kafka';
import { KafkaMessageContext } from 'kostyak127-nestjs-kafka/src/kafka/kafka.types';

@Injectable()
export class MessageHandlerService {
  @SubscribeToTopic('TOPIC', { messagePattern: 'message.object' })
  async onMessage(@KafkaContext() context: KafkaMessageContext) {
    /// full info message info like topic, offset and other
    console.log(context)
  }
}
```

---
_Source: https://npm.io/package/kostyak127-nestjs-kafka · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
