1

I'm trying to publish (producer) a message onto Kafka. The code for receiving/consuming messages is simple enough, but I was hoping to be able to publish some of those back onto a second topic at some point. When I attempt to do that, I get the following error:

[Nest] 87277  - 07/08/2022, 2:45:34 PM   ERROR [RpcExceptionsHandler] Cannot read properties of null (reading 'emit')
TypeError: Cannot read properties of null (reading 'emit')
    at AppController.getHello (/path/src/app.controller.ts:31:17)
    at AppController.handleForeignData (/path/src/app.controller.ts:47:10)
    at /path/node_modules/@nestjs/microservices/context/rpc-context-creator.js:44:33
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at /path/node_modules/@nestjs/microservices/context/rpc-proxy.js:11:32
    at ServerKafka.handleEvent (/path/node_modules/@nestjs/microservices/server/server.js:71:32)
    at Runner.processEachMessage (/path/node_modules/kafkajs/src/consumer/runner.js:231:9)
    at onBatch (/path/node_modules/kafkajs/src/consumer/runner.js:447:9)
    at Runner.handleBatch (/path/node_modules/kafkajs/src/consumer/runner.js:461:5)
    at /path/node_modules/kafkajs/src/consumer/worker.js:29:9

The documents suggest that either of emit() or send() might work, but I get the same error for either. I'm not very familiar with Nest, but "properties of null" suggests that this.client is just out of context. On the other hand, I'm not entirely sure that I've got the Kafka configuration set up entirely. What's missing?

I have code that looks like the following:

import { Controller, Get, OnModuleInit } from '@nestjs/common';
import { AppService } from './app.service';
import { Client, ClientKafka, ClientProxy, EventPattern, MessagePattern, Payload } from '@nestjs/microservices'
import { microserviceConfig } from "./microserviceConfig";

@Controller()
export class AppController implements OnModuleInit {
  constructor(private readonly appService: AppService) {}

  @Client(microserviceConfig)
  client: ClientKafka;


  onModuleInit() {
    const requestPatterns = [
      'foreign-data',
      '-announcements'
    ];

    requestPatterns.forEach(pattern => {
      this.client.subscribeToResponseOf(pattern);
    });
  }


  @Get()
  getHello(): string {
    // fire event to kafka
    this.client.emit<string>('entity-created', 'some entity ' + new Date());
    return this.appService.getHello();
  }

  @EventPattern('foreign-data')
  async handleForeignData(payload: any) {
    // this.getHello();
    console.log(JSON.stringify(payload) + ' created');

  }

}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
John O
  • 4,863
  • 8
  • 45
  • 78

0 Answers0