Search code examples
javascriptapache-kafkanestjskafka-consumer-api

NestJS Kafka - Check for topics in health check


I'd like to check if my service is consuming a topic as part of my health check. I created a custom transport for Kafka:

export class KafkaCustomTransport extends ServerKafka {
  get kafkaClient(): Kafka {
    return this.client;
  }
}

And now I'd like to inject and access it in my health check module:

import { Controller, Get } from '@nestjs/common';
import { HealthCheckService, HttpHealthIndicator, HealthCheck } from '@nestjs/terminus';

@Controller('health')
export class HealthController {
  constructor(
    private health: HealthCheckService,
    private http: HttpHealthIndicator,
    private kafkaTransport: KafkaCustomTransport <- Something like this
  ) {}

  @Get()
  @HealthCheck()
  check() {
    return this.health.check([
      () => this.http.pingCheck('nestjs-docs', 'https://docs.nestjs.com'),
      () => this.kafkaTransport.client...........
    ]);
  }
}

Is there a way to do this? Is there a workaround?


Solution

  • Wrapped it in a provider which I can then get with @Inject:

    export const kafkaProvider = {
        provide: "KAFKA",
        useFactory: (): KafkaCustomTransport => {
      
          const kafkaOptions: KafkaOptions["options"] = {};
      
          return new KafkaCustomTransport(options);
        },
        inject: [],
      };
    
    

    In health check:

    @Controller('health')
    export class HealthController {
      constructor(
        private health: HealthCheckService,
        private http: HttpHealthIndicator,
        @Inject("KAFKA") private kafkaTransport: KafkaCustomTransport
      ) {}