Skip to content

Commit

Permalink
fix: throw an error when started listening before app is boostrapped
Browse files Browse the repository at this point in the history
  • Loading branch information
vglebovich-lmru committed Sep 3, 2024
1 parent f626db8 commit f468532
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions src/consumer/kafkaConsumer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

import vm from "vm";

import { Inject, Injectable } from "@nestjs/common";
import { Inject, Injectable, OnApplicationBootstrap } from "@nestjs/common";
import {
CustomTransportStrategy,
MessageHandler,
Expand All @@ -37,9 +37,14 @@ import { IKafkaConsumerSerializedOptions } from "./interfaces";
import { KafkaConsumerMessageHandler } from "./kafkaConsumerMessageHandler";

@Injectable()
export class KafkaConsumer extends Server implements CustomTransportStrategy {
export class KafkaConsumer
extends Server
implements CustomTransportStrategy, OnApplicationBootstrap
{
public readonly transportId = KafkaConsumerTransportId;

private applicationBootstrapped = false;

private readonly messageHandlersMap: Map<
string,
Map<string, MessageHandler>
Expand All @@ -62,9 +67,24 @@ export class KafkaConsumer extends Server implements CustomTransportStrategy {
}

public listen(callback: (error?: unknown) => void): void {
if (!this.applicationBootstrapped) {
const errorMessage =
"Application is not bootstrapped. " +
"Ensure that you have called app.listen() " +
"before calling app.startAllMicroservices(). " +
"The listen method was invoked before the application finished bootstrapping.";

this.logger.error(errorMessage);
return callback(new Error(errorMessage));
}

this.start().then(callback).catch(callback);
}

public onApplicationBootstrap(): void {
this.applicationBootstrapped = true;
}

private addMessageHandlerToMap(
connectionName: string,
topics: string[],
Expand Down

0 comments on commit f468532

Please sign in to comment.