Having difficulties incorporating a selected custom repository into a module

Issue with Dependency Injection in NestJS

Currently, I am working on implementing SOLID principles in my NestJS project by decoupling my service layer from TypeOrm. One of the benefits of this approach is the ability to switch between using an InMemoryRepository for testing and a TypeOrmRepository for production.

However, I have encountered a problem with injecting my custom TypeOrm repository as a provider. It seems that the @InjectRepository() decorator and TypeOrm are not behaving as expected in this specific scenario. Interestingly, I can inject my In Memory repositories without any issues in my unit tests.

[Nest] 12311   - 18/09/2021 at 06:22:43   [ExceptionHandler] Cannot read property 'save' of undefined
TypeError: Cannot read property 'save' of undefined
    at TypeOrmWorkoutRepository.Object.<anonymous>.Repository.save (/Users/arthurmehmetoglu/Development/CorpoSano/back/src/repository/Repository.ts:150:29)
    at WorkoutService.create (/Users/arthurmehmetoglu/Development/CorpoSano/back/src/workout/workout.service.ts:30:35)
    at WorkoutResolver.create (/Users/arthurmehmetoglu/Development/CorpoSano/back/src/workout/workout.resolver.ts:22:32)
   ...

For more information and code snippets, please refer to the sections below.

Code Samples

workout.module.ts

...

workout.service.ts

...

workout.service.spec.ts

...

workout-repository.interface.ts

...

in-memory-exercise.repository.ts

...

typeorm-workout.repository.ts

...

Environment

Nest version: 7.6.0

Node version: v14.16.1

Platform: Mac

Additional Resources:

Note: The provided code snippets have been condensed for clarity.

Answer №1

After some troubleshooting, I managed to resolve the issue using the useExisting method as shown below:

 import { Module } from '@nestjs/common'
 import { getRepositoryToken, TypeOrmModule } from '@nestjs/typeorm'
 import { WorkoutResolver } from './workout.resolver'
 import { WorkoutService } from './workout.service'
 import { TypeOrmExerciseTemplateRepository } from '../exercise/repositories/type-orm-exercise-template.repository'
 import { TypeOrmWorkoutRepository } from './repositories/workout.typeorm.repository'
 import { TypeOrmExerciseRepository } from '../exercise/repositories/type-orm-exercise.repository'
 import { WORKOUT_REPOSITORY } from './repositories/workout.repository.interface'
 import { EXERCISE_TEMPLATE_REPOSITORY } from '../exercise/repositories/exercise-template-repository.interface'
 import { EXERCISE_REPOSITORY } from '../exercise/repositories/exercise-repository.interface'
 import { TypeOrmSessionRepository } from '../session/repositories/session.typeorm.repository'
 import { FillWorkoutWithExercisesUseCase } from './use-cases/fill-workout-with-exercises.use-case'
 
 @Module({
   imports: [
     TypeOrmModule.forFeature([
       TypeOrmExerciseTemplateRepository,
       TypeOrmExerciseRepository,
       TypeOrmWorkoutRepository,
       TypeOrmSessionRepository,
     ]),
   ],
   providers: [
     {
       provide: WORKOUT_REPOSITORY,
       useExisting: getRepositoryToken(TypeOrmWorkoutRepository),
     },
     {
       provide: EXERCISE_REPOSITORY,
       useExisting: getRepositoryToken(TypeOrmExerciseRepository),
     },
     {
       provide: EXERCISE_TEMPLATE_REPOSITORY,
       useExisting: getRepositoryToken(TypeOrmExerciseTemplateRepository),
     },
     WorkoutResolver,
     WorkoutService,
     FillWorkoutWithExercisesUseCase,
   ],
 })
 export class WorkoutModule {}

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

What is the correct way to define functions within an object using Typescript in this situation?

Currently in the process of converting a JavaScript project to TypeScript, I encountered this error message (utilizing urql): A function whose declared type is neither 'void' nor 'any' must return a value. ts(2355) on line: playerCrea ...

What could be causing Angular to replace the original variable?

As a newcomer to Angular, I've been working on this code for hours now. Hopefully, it will all come together for someone out there who can make sense of it. export class QuizComponent implements OnInit { originalArray: IArray[] = []; tempArray: I ...

Improving the structure of a TypeScript switch statement

Looking for a more efficient way to implement a switch statement in TypeScript? Here is the current code snippet from a component: switch (actionType) { case Type.Cancel { this.cancel(); break; } case Type.Discard { thi ...

The type definition file for 'jest' cannot be located, despite the fact that jest has been successfully installed

SOLUTION STRATEGY: If you encounter a similar issue and are looking for a more comprehensive solution rather than quick fixes, consider recreating the repository. While it involves more effort initially, it can prevent future issues. In my case, the repos ...

Refreshing the Mat Dialog content when removing items in Angular Material

I have successfully implemented a mat dialog table with 3 columns - name, email, and delete icon. When the user clicks on the delete icon, it prompts a confirmation message to confirm the deletion. Upon confirming, the item is removed from the database. Ho ...

Utilize TypeScript to re-export lodash modules for enhanced functionality

In my TypeScript project, I am utilizing lodash along with typings for it. Additionally, I have a private npm module containing utilities that are utilized in various projects. This module exports methods such as: export * from './src/stringStuff&apo ...

What is the best way to choose a particular radio button from a group of radio buttons using typescript?

Is there a way to automatically select a specific radio button when an item is chosen from a dropdown menu on the webpage using a TypeScript function that is triggered by the dropdown selection? ...

"Implementing a Filter for Selecting Multiple Options in Ionic Framework

I need help with filtering books in an online library project using a modal page. The modal has 3 input fields for title, author, and year. How can I filter the books based on these inputs? Here is a snippet of my modal.html code: <ion-content pa ...

node-ts displays an error message stating, "Unable to locate the name '__DEV__' (TS2304)."

I recently inserted __DEBUG__ into a TypeScript file within my NodeJS project. Interestingly, in VSCode, no error is displayed. However, upon running the project, I encounter an immediate error: error TS2304: Cannot find name '__DEBUG__'. I att ...

I am looking for a guideline that permits me to restrict the use of a form validation tool

We have developed our own version of the Validators.required form-validator that comes with Angular 7, but now we need to switch to using CustomValidators.required. To enforce this change, we are considering banning the use of the old Validators.required b ...

Angular HTML Component Refactor causes compatibility issues with BS4 classes

Currently, I am working on Angular components and I have a specific section that I would like to refactor into a separate component for reusability. Initially, when the HTML block with only Bootstrap 4 classes is placed in the parent component, the user in ...

Instead of leaving an Enum value as undefined, using a NONE value provides a more explicit

I've noticed this pattern in code a few times and it's got me thinking. When you check for undefined in a typescript enum, it can lead to unexpected behavior like the example below. enum DoSomething { VALUE1, VALUE2, VALUE3, } f ...

Utilizing References in React Components

One of the challenges I am facing involves a Container that needs references to some of its child components: const Container = () => { const blocks: HTMLDivElement[] = []; return ( <div> <Navigation currentBlock={currentBlock} ...

Exploring how enums can be utilized to store categories in Angular applications

My application has enums for category names on both the back- and front-end: export enum CategoryEnum { All = 'All', Category1 = 'Category1', Category2 = 'Category2', Category3 = 'Category3', Cate ...

Guide to Validating Fields in Angular's Reactive Forms After Using patchValue

I am working on a form that consists of sub-forms using ControlValueAccessor profile-form.component.ts form: FormGroup; this.form = this.formBuilder.group({ firstName: [], lastName: ["", Validators.maxLength(10)], email: ["", Valid ...

The `react-router-dom` in React consistently displays the `NotFound` page, but strangely, the active class for the home page does not get

Currently, I am utilizing "react-router-dom": "^6.4.1" in my application and encountering two main issues: Upon navigating to another page, the home page retains the active class, resulting in both the new page and the home page disp ...

Issue with dynamic HTML preventing Bootstrap tooltip functionality

There's an HTML page where a section is dynamically generated through HTML injection from a typescript angularjs controller using $sce and ng-bind-html. The issue is that the custom bootstrap tooltip style doesn't seem to be applied, and only t ...

Tips for dragging a column in ngx-datatable to scroll the horizontal scroll bar in Angular 4

Is there a way to make the horizontal scroll bar move when dragging the column header of ngx-datatable in Angular 4? I have a situation where the first column should trigger the movement of the horizontal scroll bar when dragged from left to right. Any s ...

Overloading TypeScript functions with Observable<T | T[]>

Looking for some guidance from the experts: Is there a way to simplify the function overload in the example below by removing as Observable<string[]> and using T and T[] instead? Here's a basic example to illustrate: import { Observable } from ...

Deleting a key from a type in TypeScript using subtraction type

I am looking to create a type in TypeScript called ExcludeCart<T>, which essentially removes a specified key (in this case, cart) from the given type T. For example, if we have ExcludeCart<{foo: number, bar: string, cart: number}>, it should re ...