Using NestJS to import and inject a TypeORM repository for database operations

This is really puzzling me!

I'm working on a nestjs project that uses typeorm, and the structure looks like this:

+ src
   + dal
        + entities
             login.entity.ts
             password.entity.ts             
        + repositories
             login.repository.ts
             password.repository.ts
        dal.module.ts
   + modules
        + security
             + services
                  login.service.ts
                  security.service.ts
             security.module.ts
   app.module.ts
   main.ts

The custom repositories in `dal` are defined as follows:

@EntityRepository(Login)
export class LoginRepository extends AbstractRepository<Login> implements ILoginRepository { }

@EntityRepository(Password)
export class PasswordRepository extends AbstractRepository<Password> implements IPasswordRepository { }

`dal.module.ts` content:

@Module({
    imports: [TypeOrmModule.forFeature([Entity1, Entity2, Entity3])],
    controllers: [],
    providers: [PasswordRepository, LoginRepository],
})
export class DalModule { }

`security.module.ts` content:

@Module({
    imports: [TypeOrmModule.forFeature([PasswordRepository, LoginRepository])],
    controllers: [SecurityController],
    providers: [LoginService, SecurityService],
})
export class SecurityModule { }

`app.module.ts` content:

@Module({
   imports: [
      DalModule,
      SecurityModule,
      TypeOrmModule.forRoot({
         type: 'mysql',
         port: Number(process.env.DB_PORT),
         host: process.env.DB_SERVER,
         username: process.env.DB_USERNAME,
         password: process.env.DB_PASSWORD,
         database: process.env.DB_NAME,
         entities: [__dirname + '/**/*.entity{.ts,.js}'],
         synchronize: false
      })
   ]
})
export class AppModule {}

Content of `login.service.ts`:

export class LoginService {
   constructor(
      private readonly passwordRepository: PasswordRepository,
      @InjectRepository(Login) private readonly loginRepository: LoginRepository
   ) {
       console.log(this.passwordRepository.f1);
       console.log(this.loginRepository.f2);
   }

And here's the issue:

Currently, I'm getting `[AsyncFunction: f1]` and `[AsyncFunction: f2]` logged as expected in the `LoginService` constructor.

But if I remove `@InjectRepository(Login)` from the second argument, I get a `Cannot read property 'f1' of undefined` error. And if I comment out the first `console.log`, I get a `Cannot read property 'f2' of undefined` error from the second `console.log`.

On the other hand, if I add `@InjectRepository(Password)` to the first argument, I receive a `Nest can't resolve dependencies of the LoginService (?, LoginRepository). Please make sure that the argument PasswordRepository at index [0] is available in the SecurityModule context` error.

What could be causing this unexpected behavior?

Answer №1

I faced a similar issue, but I was able to resolve it in the end.

To solve your problem, simply include Repository classes within the TypeOrmModule, and export the TypeOrmModule.

@Module({
    imports: [TypeOrmModule.forFeature([PasswordRepository, LoginRepository])],
    exports: [TypeOrmModule],
    controllers: [SecurityController],
    providers: [LoginService, SecurityService],
})
export class SecurityModule { }

By importing the SecurityModule in other modules, the LoginRepository will be accessible for injection.

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

Transfer Typescript Project to Visual Studio Code

When I first started my project, I used the Typescript HTML Application Template project template. It worked well and set up a project for me. However, now I want to transition to using VSCode. The issue I'm facing is figuring out which switches and c ...

Tips for accurately implementing the onHoverIn TS type in the React Native Web Pressable component

I'm working with React Native Web and Typescript, and I want to integrate the React Native Web Pressable component into my project. However, I encountered an issue where VSCode is showing errors for React Native Web prop types like onHoverIn. The pro ...

What is the best way to manage tables with a ManyToOne relationship in TypeORM when it comes

I have a scenario where I am working with two entities that have a ManytoOne relationship between them: The entities involved are: PersonalProfile Language Their relationship is defined in the code snippet below: import BaseModel from "@models/Base ...

The TypeScript datatype 'string | null' cannot be assigned to the datatype 'string'

Within this excerpt, I've encountered the following error: Type 'string | null' cannot be assigned to type 'string'. Type 'null' cannot be assigned to type 'string'. TS2322 async function FetchSpecificCoinBy ...

Getting the item that was clicked on a Chart in a PrimeNG chart within an Angular application can be achieved by following these

I am trying to implement a bubble chart and I would like the function to be called when a user clicks on one of the bubbles. What is the best way for me to pass the data to this function? https://i.stack.imgur.com/FYiSP.png <p-chart type="bubble" [da ...

Is it possible to make the 'keyof' property optional?

Illustrate an interface in the following way interface Properties { apple?: string banana?: string cherry?: string date: string } Executing this code works as expected type Sample1 = { [P in keyof Properties]: Properties[P] } const s1: Sample1 ...

Dynamically incorporate new methods into a class

Currently, I am in the process of implementing setters and getters for items that will be stored in session storage. These methods are being written within a service. However, upon attempting to call these functions in my component, I am encountering a tra ...

Utilizing SCSS variables

Currently, I am in the process of developing an Angular 4 application using angular-cli and have encountered a minor issue. I am attempting to create a component that has the ability to dynamically load styling. The ComponentX component needs to utilize a ...

Convert checkbox choices to strings stored in an array within an object

I have a intricate object structure JSON{ alpha{ array1[ obj1{}, obj2{} ] } } In addition to array1, I need to include another array: array2 that will only consist of strin ...

In Typescript, it is not possible to assign the type 'any' to a string, but I am attempting to assign a value that is

I'm new to TypeScript and currently learning about how types function in this language. Additionally, I'm utilizing MaterialUI for this particular project. The issue I'm encountering involves attempting to assign an any value to a variable ...

I'm encountering an error in TestCafe that says "TypeError: Cannot read properties of undefined (reading 'match')". Which specific segment of my code is causing this issue?

retrieveUrlFromEmailData(emailData:any){ const emailContent = emailData.email_text; const urlPattern = /(https?:\/\/[^\n]*)/; const foundUrl = emailContent.match(urlPattern)[0]; return foundUrl } ...

Check out the attributes of a class

I have a TypeScript class that is defined like this: export class MyModel { ID: number; TYPE_ID: number; RECOMMENDED_HOURS: number; UNASSIGNED_HOURS: number; } In a different .ts file, I instantiate this class within a component: export class My ...

Using Angular BehaviorSubject in different routed components always results in null values when accessing with .getValue or .subscribe

I am facing an issue in my Angular application where the JSON object saved in the service is not being retrieved properly. When I navigate to another page, the BehaviorSubject .getValue() always returns empty. I have tried using .subscribe but without succ ...

Metronome in TypeScript

I am currently working on developing a metronome using Typescript within the Angular 2 framework. Many thanks to @Nitzan-Tomer for assisting me with the foundational concepts, as discussed in this Stack Overflow post: Typescript Loop with Delay. My curren ...

I can't find my unit test in the Test Explorer

I'm currently working on configuring a unit test in Typescript using tsUnit. To ensure that everything is set up correctly, I've created a simple test. However, whenever I try to run all tests in Test Explorer, no results are displayed! It appear ...

Collaborating on data through module federation

Currently, I am in the process of developing a Vue.js and TypeScript application using Vite. In addition, I am utilizing the vite-module-federation-plugin for sharing code across different applications. My main inquiry revolves around whether it is possibl ...

The error at core.js:4002 is a NullInjectorError with a StaticInjectorError in AppModule when trying to inject FilterService into Table

While exploring PrimeNg Table control in my application - as a beginner in PrimeNg & Angular, I encountered an error No provider for FilterService! shown below: core.js:4002 ERROR Error: Uncaught (in promise): NullInjectorError: StaticInjectorError(AppMo ...

How to configure mat-sort-header in Angular Material for mat-table

My current table is created using Angular Material: <mat-table *ngIf="!waiting" class="table-general table-summary" #table [dataSource]="dataSource" matSort> <mat-header-row class="header_row" *matHeaderRowDef="headerKeys"></mat-header ...

Trigger a class method in an event using Angular with Typescript

I am completely new to TypeScript and Angular, and I am attempting to create a basic drawing component on a canvas. However, I have reached a point where I feel lost and confused about my code. The concept of "this" in TypeScript has been a major stumbling ...

Is it possible to derive a TypeScript interface from a Mongoose schema without including the 'Document' type?

Using ts-mongoose allows me to define interfaces and schemas for my data in one place. I then export them as a mongoose schema along with the actual interface. The challenge I'm facing is finding a simple way to extract that interface without includi ...