Struggling with module dependencies in Nest.js

I have been diving into the documentation provided on the NestJs website, but I've noticed that it can be a bit scattered. My goal is to retrieve an RPG Character from a Mongo database using TypeORM. Unfortunately, I seem to be running into dependency issues along the way.

The specific error message that Nest is throwing at me reads:

[ExceptionHandler] Nest can't resolve dependencies of the CharacterModule (?). Please ensure that the argument dependency at index [0] is available within the CharacterModule context.

Here is a link to the Gist

The core snippet of code causing trouble is as follows:

character.module.ts

// tslint:disable: quotemark
import { Module, Inject } from '@nestjs/common';
import { TypeOrmModule } from "@nestjs/typeorm";
import { Connection } from 'typeorm';
import { ServeStaticModule } from '@nestjs/serve-static';
import { join } from 'path';

import { CharacterEntity } from "../entities/character.entity";
import { CharacterService } from './character.service';
import { CharacterController } from './character.controller';

@Module({
  imports: [
    TypeOrmModule
  ],
  controllers: [
    CharacterController
  ],
  providers: [
    CharacterService
  ],
  exports: [
    CharacterService,
  ]
})
export class CharacterModule {
  constructor() { }
}

In my attempts to troubleshoot, I have experimented with adding

TypeOrm.forFeature([CharacterEntity], 'default')
and exporting TypeOrmModule. Additionally, I included
@Inject() private connection: Connection
in my module's constructor.

Could you point out where I might be getting tripped up?

Update - 07/26/2020

new character.module.ts

// tslint:disable: quotemark
import { Module, Inject } from '@nestjs/common';
import { TypeOrmModule } from "@nestjs/typeorm";
import { Connection } from 'typeorm';
import { ServeStaticModule } from '@nestjs/serve-static';
import { join } from 'path';

import { CharacterEntity } from "../entities/character.entity";
import { CharacterService } from './character.service';
import { CharacterController } from './character.controller';

@Module({
  imports: [
    TypeOrmModule.forFeature([CharacterEntity])
  ],
  controllers: [
    CharacterController
  ],
  providers: [
    CharacterService
  ],
  exports: [
    CharacterService,
    TypeOrmModule
  ]
})
export class CharacterModule {
  constructor() { }
}

character.service.ts

// tslint:disable: quotemark
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Response as ExpressResponse } from 'express';

import {
 /* other imports */
    Character,
} from 'src/model';
import { CharacterEntity } from '../entities/character.entity';

@Injectable()
export class CharacterService {
    characterNotFound: NotFoundError = {
        errorType: 'Not Found',
        Event_Code: '404',
        Event_Id: '',
        Event_Message: 'The character was not found',
        Event_Subject: 'Character not found',
        Event_Timestamp: new Date().toString()
    } as NotFoundError;

    constructor(
        @InjectRepository(CharacterEntity)
        private characterRepo: Repository<CharacterEntity>
    ) { }
/* other actions */
}

app.module.ts

// tslint:disable: quotemark
// modules
import { Module } from '@nestjs/common';
import { CharacterModule } from './character/character.module';
import { CampaignModule } from './campaign/campaign.module';
import { PlayerModule } from './player/player.module';
import { SageModule } from './sage/sage.module';
import { TypeOrmModule } from "@nestjs/typeorm";
import { Connection } from 'typeorm';

// controllers
import { AppController } from './app.controller';
import { PlayerController } from './player/player.controller';
import { AuthController } from './auth/auth.controller';

// services
import { AppService } from './app.service';

// constants for everything else
import { SAGE_DB, SAGE_DB_HOST, SAGE_DB_PORT, ENTITIES_PATH } from './constants';
import { CharacterController } from './character/character.controller';
import { CharacterEntity } from './entities/character.entity';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      "name": "default",
      "type": "mongodb",
      "host": SAGE_DB_HOST,
      "port": SAGE_DB_PORT,
      "database": SAGE_DB,
      "keepConnectionAlive": true,
      "synchronize": true,
      "autoLoadEntities": true
    }),
    CharacterModule,
    SageModule,
    CampaignModule,
    PlayerModule,
  ],
  controllers: [
    AppController,
    PlayerController,
    AuthController
  ],
  providers: [AppService],
})
export class AppModule {
  constructor(private connection: Connection) {
    connection.connect().then(f => {
      console.log('fulfilled', f);
    }, r => {
      console.log('rejected', r);
    });
  }
}

The latest issue being thrown states

Nest can't resolve dependencies of the CharacterEntityRepository (?). Make certain that the argument Connection at index [0] is accessible in the TypeOrmModule context.
Note that TypeOrmModule.forRoot({...}) exists in the app.module.ts.

Answer №1

Ensure to include

TypeOrmModule.forFeature([CharacterEntity])
in your CharacterModule so that the Repository(CharacterEntity) injection token can be accessed within the scope of the module.

Answer №2

While incorporating the repository pattern into my project, I discovered that utilizing forRoot and forFeature was essential to accomplish my goals. ormconfig, as shown in this instance, essentially consists of your existing database connection settings. The arrayofentities represents an array containing each TypeScript entity class.

The current implementation of the repository pattern in your services should not necessitate the import of Connection.

(It's worth noting that all of this code is within app.module.ts; you could move the for feature segment into your specific module)

imports:[
        TypeOrmModule.forRoot(ormconfig),
        TypeOrmModule.forFeature(arrayofentities)
    ]

Answer №3

My recent experience involved encountering a similar error due to my approach of importing Repository and another service using the "type" keyword at the beginning.

Mistaken Method:

import type { Repository } from 'typeorm';
import type { FileUtilsService } from "../file-utils";

The Correct Way:

import { Repository } from 'typeorm';
import { FileUtilsService } from "../file-utils";

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

Issue with Formik compatibility in Next JS 14 Application Structure

I attempted to create a basic validation form using Formik. I meticulously followed their tutorial and example, but unfortunately, the form is not functioning correctly. Despite my efforts, I have been unable to identify a solution (Please correct me if I& ...

Having trouble with Typescript subtraction yielding unexpected results?

If I have a total amount including VAT and want to separate the net price and the VAT value, how can this be done? For example, if the final price is $80.60 with a VAT rate of 24%, what would be the net price and the VAT value? The correct answer should ...

Using the className prop in React with TypeScript

How can the className prop be properly typed and utilized in a custom component? In the past, it was possible to do the following: class MyComponent extends React.Component<MyProps, {}> { ... } and then include the component using: <MyCompone ...

After triggering an action, I am eager to make a selection from the store

To accomplish my task, I must first select from the store and verify if there is no data available. If no data is found, I need to dispatch an action and then re-select from the store once again. Here is the code snippet that I am currently using: t ...

What steps are needed to generate a production version of a TypeScript monorepo application that can be deployed to an Azure Function App?

I've been grappling with understanding Typescript project references and their intended use in a production build, especially for an Azure Function App. I'm not utilizing any monorepo functionality at the package manager level, such as npm worksp ...

Resolving TypeScript error: Property 'Error' does not exist on type 'Angular2 and Objects'

One of the models I am working with is called "opcionesautocomplete.model.ts" interface IOpcionesAutocomplete { opcionesStyle: OpcionStyle; pcionPropiedades: OpcionPropiedades; } export class OpcionesAutocomplete implements IOpcionesAutocomplet ...

Updating a subscribed observable does not occur when pushing or nexting a value from an observable subject

Help needed! I've created a simple example that should be working, but unfortunately it's not :( My onClick() function doesn't seem to trigger the console.log as expected. Can someone help me figure out what I'm doing wrong? @Component ...

A guide on effectively utilizing ref forwarding in compound component typing

I am currently working on customizing the tab components in Chakra-ui. As per their documentation, it needs to be enclosed within React.forwardRef because they utilize cloneElement to internally pass state. However, TypeScript is throwing an error: [tsserv ...

Retrieving Identifiers with Typescript from an object

I'm a newcomer to Typescript and I'm looking to extract ids from an observable Here's the observable data: let myObj = [{ "id": 1, "text": "Mary" }, { "id": 2, "text": "Nancy" }, { "id": 3, "text": "Paul" }, { "id": 4, "tex ...

Error message in Angular when promises are not defined

Recently, I started working with promises for the first time. I have a function that returns a promise: public DatesGenerator(futercampaign: ICampaign, searchparam: any, i: number): ng.IPromise<any> { return this.$q((resolve, reject) => { ...

I need to explicitly tell TypeScript that there are optional numeric properties on two objects that need to be compared

I am faced with the challenge of sorting an array of objects based on an optional integer property called order, which falls within the range of [0, n]. To achieve this task, I am utilizing JavaScript's Array.prototype.sort() method. Given that the p ...

Protobuf.js: The Writer is not completing the operation

I have recently come across an unusual issue while incorporating Protobuf into my TypeScript frontend. My approach involves using Axios to communicate with my REST API and leveraging the protobuf.js library for handling Protobuf in the frontend. Since I am ...

Struggling to use the bind method for the loadScene callback function in cocosCreator or cocos2d-x?

When the loadScene() callback function is bound, the information retrieved from getScene() becomes inaccurate. Upon transitioning from the Entry Scene to the Lobby Scene, I perform post-processing tasks. The implementation was done in TypeScript. Entry. ...

Encountering an issue with Nuxt 3.5.1 during the build process: "ERROR Cannot read properties of undefined (reading 'sys') (x4)"

I am currently working on an application built with Nuxt version 3.5.1. Here is a snippet of the script code: <script lang="ts" setup> import { IProduct } from './types'; const p = defineProps<IProduct>(); < ...

The error message "Unable to access property 'open' of an undefined menu" is being displayed in a TypeScript code

I am facing an issue with the action in my menu. For this project, I am using a material menu and icons. The main menu code appears as follows: <mat-menu #rootMenu="matMenu" [overlapTrigger]="false"> <ng-template matMenuContent let-element="ele ...

Ways to properly exit a function

What is the best way to pass the apiKey from the createUser function in User.ts to Test.ts in my specific scenario? User.ts interface User { url: string, name: string, } class User{ async createUser( user: User ):Promise<void> { le ...

Developing a React-based UI library that combines both client-side and server-side components: A step-by-step

I'm working on developing a library that will export both server components and client components. The goal is to have it compatible with the Next.js app router, but I've run into a problem. It seems like when I build the library, the client comp ...

Tips for updating a component's state from another component in a React Native application

I have a map displaying a specific region based on the user's location. I am trying to implement a button in a separate file that will reset the map back to the user's current location while maintaining modularity. Can someone guide me on how to ...

Exploring ways to pass props in functional components in React Native

I am currently exploring how to create an API in React Native with TypeScript without using the class extends component. However, I am struggling to figure out how to access and send props from one const view to another function: App.tsx import React, {us ...

Executing asynchronous methods in a Playwright implementation: A guide on constructor assignment

My current implementation uses a Page Object Model to handle browser specification. However, I encountered an issue where assigning a new context from the browser and then assigning it to the page does not work as expected due to the asynchronous nature of ...