Dealing with circular dependencies in NestJS by using ForwardRef

Hey everyone, I've been running into a circular dependency issue with NestJS. I tried using the forwardref method, but it hasn't resolved the problem for me.

// AuthModule 
@Module({
  imports: [
    forwardRef(() => UserModule),
    JwtModule.register({
      global: true,
      secret: process.env.TOKEN_SECRET,
      signOptions: { expiresIn: process.env.TOKEN_DURATION },
    }),
  ],
  providers: [AuthService, AuthGuard],
  controllers: [AuthController],
  exports: [AuthService],
})
export class AuthModule {}
// UserModule
@Module({
  imports: [forwardRef(() => AuthModule)],
  controllers: [UserController],
  providers: [UserService],
  exports: [UserService],
})
export class UserModule {}

Within the service, I am accessing another service like this:

private readonly authService: AuthService,

== CMD ERROR == [Nest] 2788 - 06/10/2023, 12:56:50 PM LOG [InjectorLogger] Nest encountered an undefined dependency. This may be due to a circular import or a missing dependency declaration. [Nest] 2788 - 06/10/2023, 12:56:50 PM ERROR [ExceptionHandler] Nest can't resolve dependencies of the UserService (PrismaService, ?, CONFIGURATION(app)). Please make sure that the argument dependency at index [1] is available in the UserModule context.

Potential solutions:

  • Is UserModule considered a valid NestJS module?

  • If the dependency is a provider, is it included in the current UserModule?

  • If the dependency is exported from a separate @Module, ensure that module is imported within UserModule.

    @Module({
      imports: [ /* the Module containing dependency */ ]
    })
    

How did I end up with a circular dependency situation?

Answer №1

If you're stuck on a problem, this answer may not provide a solution, but it will offer insights into the connections between modules

Consider incorporating nestjs-spelunker

At times, visualizing module inter-dependencies can aid in better understanding and decision-making. The SpelunkerModule features a graph method that enhances the explore method's output by creating a comprehensive graph with nodes representing modules and edges linking to their dependencies or dependents.

Answer №2

To resolve the issue, I utilized @Inject() within the constructor to properly import the necessary services. For further information, please refer to the documentation.

Answer №3

In the constructor, you have the option to use:

constructor(
  @Inject(forwardRef(() => TestService))
  private testService: TestService,
)

Alternatively, you can also utilize:

constructor(
  @Inject(REQUEST)
  private testService: TestService,
)

Although I personally prefer the first method, the choice between the two depends on your specific circumstances.

If you are working with pipes, it is advisable to take a look at this related issue: https://github.com/nestjs/nest/issues/4367

Answer №4

Minimize the reliance on service-to-service communication by focusing on streamlining intermodule connections within your system

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

Having trouble displaying real-time camera RTSP streaming using Angular

I am currently in the process of developing a web application using Angular and I need to incorporate a window that displays live RTSP streaming. Upon conducting research, I discovered that this can be achieved by utilizing the JSMpeg JavaScript library. ...

Generate app registration in Azure Active Directory by automatically setting up credentials using the administrator's username and password

I am encountering a challenge that I currently cannot comprehend. In my growing list of over 100 different tenants, I aim to automatically create an app registration for each tenant with specific API permissions granted. Upon my initial login to an Azure ...

Searching Local JSON Data in Ionic 4 with a Filter Input Bar

My current challenge involves filtering local JSON data in my Ionic project. Despite referencing other resources, I am unable to filter or display filtered items on the ngx-datatable. I suspect the issue may lie either in the filterItems function implement ...

Tips for storing an unmatched result in an array with a Regexp

Is it possible to extract the unmatched results from a Regexp and store them in an array (essentially reversing the match)? The following code partially addresses this issue using the replace method: str = 'Lorem ipsum dolor is amet <a id="2" css ...

Setting an expiry date for Firestore documents

Is it feasible to set a future date and time in a firestore document and trigger a function when that deadline is reached? Let's say, today I create a document and specify a date for the published field to be set to false fifteen days later. Can this ...

What's the best way to insert values into data binding within a Typescript/ Angular mat Table?

Objective: Create a dynamic table using JSON data <mat-table class="mat-elevation-z8" *ngIf="carrierRates" [dataSource]="carrierRates"> <ng-container *ngFor="let columnName of columnsList" matColumn ...

I can't seem to catch my Zod error, even though 'express-async-errors' is already installed. What could be causing this issue?

I've been working on developing an API, but I'm facing issues with setting up a global error controller using Zod. It seems that the global error handler is not being called even though I'm using express-async-errors. Below is my error mana ...

Is it possible to implement a redirect in Angular's Resolve Navigation Guard when an error is encountered from a resolved promise?

I have integrated Angularfire into my Angular project and am utilizing the authentication feature. Everything is functioning properly, however, my Resolve Navigation Guard is preventing the activation of the component in case of an error during the resolve ...

Substitute a value in a list with a distinctive identification code

I have a list of dailyEntries. Each entry has a unique identifier called id. I am given an external dailyEntry that I want to use to replace the existing one in the array. To achieve this, I can use the following code: this.dailyEntries = this.dailyEntri ...

Is there a way to simultaneously filter by two attributes using mat-select-filter in Angular?

I have integrated the mat-select-filter library in my Angular project, but I am facing an issue with the displayMember filter. Currently, it only filters by code, but I would like it to also filter by name simultaneously. Is there a way to achieve this u ...

Serialising and deserialising TypeScript types in local storage

I'm currently working on a Typescript application where I store objects using local storage for development purposes. However, I've run into some trouble with deserialization. Specifically, I have an object called meeting of type MeetingModel: ...

Creating a concise TypeScript declaration file for an established JavaScript library

I'm interested in utilizing the neat-csv library, however, I have encountered an issue with it not having a typescript definition file available. Various blogs suggest creating a basic definition file as a starting point: declare var neatCsv: any; M ...

Encountered 'DatePickerProps<unknown>' error while attempting to develop a custom component using Material-UI and react-hook-form

Currently, I'm attempting to create a reusable component using MUI Datepicker and React Hook Form However, the parent component is throwing an error Type '{ control: Control<FieldValues, object>; name: string; }' is missing the follow ...

Utilize useState and useEffect to efficiently sort through an item list based on its current state

I am currently working on an application where I have a list of items and I need to create a details page for each item when clicked. I am facing some challenges in implementing this functionality using useState, useEffect, and typescript. I have previousl ...

Struggling with the @typescript-eslint/no-var-requires error when trying to include @axe-core/react? Here's a step-by

I have integrated axe-core/react into my project by: npm install --save-dev @axe-core/react Now, to make it work, I included the following code snippet in my index.tsx file: if (process.env.NODE_ENV !== 'production') { const axe = require(&a ...

Type Error TS2322: Cannot assign type 'Object[]' to type '[Object]'

I'm facing an issue with a code snippet that looks like this: export class TagCloud { tags: [Tag]; locations: [Location]; constructor() { this.tags = new Array<Tag>(); this.locations = new Array<Location>(); ...

What could be causing the primeng dialog to appear blank when conducting Jasmine tests on this Angular TypeScript application?

Having trouble testing a component due to rendering issues? Check out the code snippet below: import {ChangeDetectionStrategy, Component, EventEmitter, Input, Output} from '@angular/core'; @Component({ selector: 'app-help', cha ...

A: TypeScript Error TS7006: Parameter implicitly has an 'any' type

TS7006: The parameter 'port' is implicitly assigned an 'any' type. constructor(port) { TS7006: The parameter 'message' is implicitly assigned an 'any' type. Emit(message) { I'm confused because all the other r ...

Working with undefined covariance in TypeScript

Despite enabling strict, strictNullChecks, and strictFunctionTypes in TypeScript, the following code remains error-free. It seems that TypeScript is not catching the issue, even though it appears to be incorrectly typed. abstract class A { // You can p ...

Tips for specifying the return type of app.mount()

Can I specify the return value type of app.mount()? I have a component and I want to create Multiple application instances. However, when I try to use the return value of mount() to update variables associated with the component, TypeScript shows an error ...