Service import of the Dynamic Module

Having a global dynamic module with a KafkaService, I encountered an issue where NestJS was unable to inject the KafkaService into my AuthenticationService.

The KafkaModule is defined as a Dynamic and Global module.

import { DynamicModule, Global, Module } from '@nestjs/common';
import { KafkaService } from './kafka.service';
import { KafkaConfig } from './kafka.types';

@Global()
@Module({})
export class KafkaModule {
  static register(kafkaConfig: KafkaConfig): DynamicModule {
    return {
      module: KafkaModule,
      global: true,
      providers: [
        {
          provide: KafkaService,
          useValue: new KafkaService(kafkaConfig),
        },
      ],
      exports: [KafkaService],
    };
  }
}

This module is registered in AppModule.

import { Module } from '@nestjs/common';
import { KafkaModule } from './common/kafka/kafka.module';
import { AuthenticationModule } from './modules/authentication.module';

@Module({
  imports: [
    KafkaModule.register({
      clientId: 'abc',
      brokers: ['localhost:9092'],
      groupId: 'def',
    }),
    AuthenticationModule,
  ],
})
export class AppModule {}

I need to utilize KafkaService in my service.

import { Injectable } from '@nestjs/common';
import { SubscribeTo } from 'src/common/kafka/kafka.decorator';
import { KafkaService } from 'src/common/kafka/kafka.service';
import { Constant } from 'src/constant';

type LoginPayload = {
  username: string;
  password: string;
};

@Injectable()
export class AuthenticationService {
  constructor(private kafkaService: KafkaService) {}

  @SubscribeTo(Constant.TOPIC_LOGIN)
  async login(payload: LoginPayload) {
    console.log(this.kafkaService);
  }
}

UPDATE It appears that the decorator is being called before the service injection takes place.

The decorator

@SubscribeTo(Constant.TOPIC_LOGIN)
will store the function in a variable to be executed later, but at the time of execution, the service has not been injected into the class.

As a workaround, I have decided to forego using the decorator for topic subscription and instead made modifications to the Kafka module so that the consumer does not start during module initialization.

Answer №1

It seems that the decorator is triggered before injecting the service

By using the decorator

@SubscribeTo(Constant.TOPIC_LOGIN)
, the function is stored in a variable to be called later, but at this point the service has not been injected into the class yet

Therefore, I am opting not to use the decorator to subscribe to the topic and instead making adjustments to the Kafka module so that the consumer does not initialize upon module startup

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to easily printing a page in Angular 4 using TypeScript

When using my web app, there are certain pages where I need to print only a specific component without including the sidebar. I have written the following TypeScript code to achieve this: print() { window.print(); } The relevant HTML code begins with: & ...

Is it possible to create a phone mask with a desired 8 or 9 digit format including the area code using react imask

I have implemented lib react imask to apply masks to my input fields. When it comes to phone numbers, the requirement is to support numbers with either 8 or 9 digits. How can I dynamically resolve this issue? For 8 digits: mask will be '(00) 0000-000 ...

OCI: Predict expenses based on a selection of virtual machines

Seeking to determine the anticipated cost of a selection of instances within OCI utilizing the TypeScript SDK. Oracle offers a tool called Cloud Cost Estimator for configuring and dynamically displaying cost estimates. Is it possible to achieve this throug ...

Creating a Zero to Many Relationship in Prisma: A Step-by-Step Guide for Establishing a (0

While following the Prisma.io documentation, I did not come across any information regarding zero to many relationships. Currently, I am working on developing a daily nutrition system. In this system, I have a model called InfoNutriDay where I intend for ...

Customizing Dropdown Selections by Index in React Native

I am trying to achieve the functionality where each dropdown in the flatlist opens individually based on the index selected. For example, when you choose section 1, only that section should expand, while the others remain closed. Unfortunately, I have been ...

Modifying the output directory structure in Typescript to incorporate the src directory

There seems to be a problem with the Typescript compiler constantly altering the structure of the output directory, causing issues with linked dependents. Previously, it looked like this: +- dist +- index.d.ts +- index.js Now, unexpectedly it looks l ...

Implementing Asynchronous context tracking within a Remix application utilizing Express as the server

Utilizing Remix with Express as the server, I aim to develop an Express middleware that establishes an async context to grant all downstream functions (especially those in the "backend" Remix code) access to this context within the scope of a single reques ...

How come a number can be assigned to an Object reference in TypeScript?

Is TypeScript bending the rules? var x: number = 5 var y: Object = x It seems strange that a number is being assigned to an Object. Maybe x is being automatically converted to an object, but a simple check reveals otherwise: if (!(y instanceof Object)) ...

Access the system by authenticating with the Firestore database collection

My goal is to develop a function that retrieves information from my collection in order to log into my application. With the help of this service, I am able to fetch all the necessary data: getUsersLocal(): Observable<AdminUser[]> { const bo ...

What is the method for accessing an anonymous function within a JavaScript Object?

Currently facing an issue with a Node.js package called Telegraf, which is a bot framework. The problem arises when trying to create typings for it in TypeScript. The package exports the following: module.exports = Object.assign(Telegraf, { Composer, ...

What strategies can be used to address inconsistencies between the type system and runtime behavior?

I have created a unique TypeScript type called Awaitable<T> with the goal of ensuring that Awaited<Awaitable<T>> is always equal to T. export type Awaitable<T> = | (T extends Record<'then', Function> ? never : T) ...

Typescript Error: Issue encountered while passing props. Unable to access properties as they are undefined

I encountered an issue where I created an object of a certain type and attempted to pass it to a component. However, when passing the props, I received an error message stating that it cannot read properties of undefined ('stepOne'). The error sp ...

Creating dynamic form groups in Angular 4

I am currently working on a dynamic form group and I am facing a particular challenge. https://i.sstatic.net/m20IO.png Whenever I click on "add more," it should add 2 dynamic fields. Here is the function I am using: onAddSurgeries(){ const control = ...

What is the best way to divide a string into an array containing both linked and non-linked elements?

I'm struggling to find the right solution to my problem. I need to create a view that is enclosed in a clickable div. The content will consist of plain text mixed with clickable URLs - the issue arises when clicking on a link also triggers the method ...

The placeholder within my input moves up and down when switching the input type from password to text

Currently, I am encountering an issue with the styling of a standard input element in React. Specifically, the placeholder text moves up and down by about 2px when viewed on Chrome, while there are no problems on Safari. How can I go about resolving this i ...

Convert an array with three dimensions into a two-dimensional array that includes tuples with two immutable string values

Consider the array below with multiple dimensions: type ParsedLine = [string, string]; type ParsedLines = [ParsedLine, ParsedLine] const myArray: (ParsedLine | ParsedLines)[] = [ ['something', 'somethingElse'], [['foo', & ...

Utilizing Arrow Functions with Parameters in Angular

I am currently working on an Angular 4 app and I am attempting to create a queue of actions. Each action should only be executed after the previous one has finished, and each action should receive its own set of parameters. public activeRegistrationAndS ...

What is the technique for obtaining a complete AST representation of a union type in TypeScript?

Although I am familiar with ts-ast-viewer, I am unsure of how they extract a list of elements from the union. I have experimented with different existing solutions, such as this one, but it appears that most of them are outdated. Some ts.[methods] have be ...

Utilizing nested form arrays within Angular 8 for increased data manipulation

I am looking to develop a dynamic form builder using Angular 8. In this form builder, I want to create inputs with dynamic validations. The input and validation fields must be customizable and dynamic. Check out the Demo This is how I initialized the fo ...

Nativescript encountered an error due to an undefined variable called FIRAuth

I'm currently working on a project using Nativescript. While everything runs smoothly with Firebase on the local emulator, I encounter errors when testing the application on my iPhone. The specific error message is: CONSOLE LOG file:///app/vendor.js ...