Add a new class to the Custom Repository

In my project, I have developed a class called S3Service that handles the task of uploading and deleting objects (such as images) from S3. Since I intend to utilize this "service" in various modules, I decided to create a custom module named UtilsModule where I plan to house a collection of reusable shared classes. Subsequently, I successfully exported the S3Service class from my UtilsModule.

@Injectable()
export class S3Service {
  constructor(@InjectS3() private readonly client: S3) {}
  async removeObject(): Promise<S3.DeleteObjectOutput> {}
  async uploadObject(): Promise<S3.ManagedUpload.SendData> {}
}
@Module({
  providers: [S3Service],
  exports: [S3Service],
})
export class UtilsModule {}

I proceeded to import the UtilsModule into the app module.

@Module({
  imports: [
    // Other modules here
    UtilsModule,
  ],
})
export class AppModule {}

Then, I imported it into a module that requires functionalities to upload or remove objects from S3.

@Module({
  imports: [
    // Other modules
    TypeOrmModule.forFeature([ProfileRepository]),
    UtilsModule,
  ],
  controllers: [ProfileController],
  providers: [ProfileService],
})
export class ProfileModule {}

Subsequently, I injected it using the @Inject decorator into the desired repository.

@EntityRepository(Profile)
export class ProfileRepository extends Repository<Profile> {
  constructor(
    @Inject() private s3Service: S3Service,
  ) {
    super();
  }
}

Although there were no compilation errors with my application, I encountered an Internal Server Error when invoking this service via a Post request. Upon debugging, I noticed that the uploadObject function seems to be returning as undefined.

After doing some research online, I stumbled upon this thread which mentioned that TypeORM repositories may not support Dependency Injection. Is there a workaround for this issue? Should I consider instantiating this class within the repository instead?

Answer №1

After deciding against injecting a service into my repository due to it being deemed bad practice, I discovered that nest does not support injecting into a TypeORM repository class.

To resolve this issue, I decided to declare the S3Service (remembering to include the Injectable() decorator) as a provider in my UtilsModule and export it.

@Module({
  providers: [S3Service],
  exports: [S3Service],
})
export class UtilsModule {}

I then imported the module into the AppModule and any other modules where it was necessary.

@Module({
  imports: [
    // Other modules
    UtilsModule,
  ],
})
export class ProfileModule {}

Subsequently, I injected a repository into my service to directly access the database entity, resulting in cleaner code structure. I utilized it as a dependency in the constructor.

export class ProfileService {
  constructor(
    @InjectRepository(Profile)
    private profileRepository: Repository<Profile>,
    private s3Service: S3Service,
  ) {}
}

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 best way to display data retrieved through an HTTP service using ngFor?

I was attempting to inject a service (contact.service.ts) into a component (contact-list.component). The service contains data on employees defined in contacts.ts. While I was able to successfully receive the data, I encountered difficulty in rendering it ...

When using a Redux action type with an optional payload property, TypeScript may raise complaints within the reducer

In my react-ts project, I define the following redux action type: type DataItem = { id: string country: string population: number } type DataAction = { type: string, payload?: DataItem } I included an optional payload property because there are tim ...

What might be causing AngularJS to fail to display values when using TypeScript?

I have designed the layout for my introduction page in a file called introduction.html. <div ng-controller="IntroductionCtrl"> <h1>{{hello}}</h1> <h2>{{title}}</h2> </div> The controller responsible for handling th ...

A warning has been issued: CommonsChunkPlugin will now only accept one argument

I am currently working on building my Angular application using webpack. To help me with this process, I found a useful link here. In order to configure webpack, I created a webpack.config.js file at the package.json level and added the line "bundle": "web ...

What causes the form to consistently show as invalid once it has been submitted?

register.html : <form [formGroup]="signupForm" (submit)="onSubmit()" class="form-detail"> <h2>Registration Form</h2> <div class="form-row-total"> <div class="form-row"> <in ...

Angular - Enhance User Experience with Persistent Autocomplete Suggestions Displayed

Is there a way to keep the autocomplete panel constantly enabled without needing to specifically focus on the input field? I attempted to set autofocus on the input, but found it to be clunky and the panel could still disappear if I hit escape. I also ...

Lazy-loaded modules in Angular that contain services provided within the module

Currently, I am facing a challenge with lazy-loaded modules and services that are provided in these modules. My folder structure looks like this: app -> featureModule1 (lazy loaded) -> featureModule2 (lazy loaded) -->services --->servi ...

What is the method for adding pages to the ion-nav component in Ionic with Angular?

How can I implement a UINavigationController-like functionality in iOS using an ion-nav element? The example provided here is in Javascript, but I need assistance with implementing it in Angular. Specifically, I'm unsure of how to programmatically add ...

Angular: Creating an instance of a class with StaticProvider passed as a parameter

Having trouble instantiating a class with a StaticProvider. Here's the code snippet: main.ts export function createProvider() { // some implementation return result; // result is a string } const providers = [ { provide: 'TEST' ...

Tips for preserving shopping cart in Angular?

As I delve into Angular, my goal is to create a straightforward ecommerce platform that allows users to add items to their cart, view them, and complete a checkout process. To accomplish this, I have set up three components: the products list, cart, and c ...

Guide to configuring a function to display the maximum value on a boxplot in Highcharts

I'm currently using Angular in combination with the highcharts boxplot API. While I am aware that I can manually set the max value of the y-axis in the chart configuration, such as: max: 100, tickInterval: 10. There's now a need for me to dynami ...

Tips for displaying the date of a JSON response in Angular HTML format?

When working with Angular HTML, I am looping through a JSON array using ngFor and accessing the birth date data like this: <td>{{item.customer_info.birth_date}}</td> The data is being displayed as ddMMyyyy format, but I would like to change it ...

The error message "Cannot find property 'email' in type '{setup():{email : Ref<string>; password: Ref<string> }}'" is being displayed

Currently experimenting with vue js 3 and typescript in the composition API while utilizing firebase for authentication <template> <input placeholder="Password" @input="this.password"/> </template> <script lan ...

Using Angular's ngFor directive to iterate over a collection based on a true

I am currently attempting to resolve the following condition: if the condition is true, display a button, otherwise hide the button. OfferMatching() { this.getmatchoffer.filter(obj => { debugger for (let i = 0; i < this.applicationJobList.length; i+ ...

Angular: A module in the library declares an HttpInterceptor that intercepts requests that are made outside of the

I am encountering an issue with Angular where a custom instance of HttpInterceptors within an Angular library is intercepting requests for HttpClient calls made outside the library (i.e. in the consuming application). I'm finding it difficult to gras ...

The functionality of arguments in the whenAllDone promise/deferred javascript helper seems to fail when attempting to encapsulate existing code within a Deferred

My goal is to implement the solution provided in TypeScript from Stack Overflow: UPDATE 2 - The issue with the original answer is that it does not support a single deferred. I have made modifications to reproduce the error in his fiddle. http://jsfiddle.n ...

Activate TypeScript EMCAScript 6 support for Cordova projects in Visual Studio

I am interested in utilizing the async/await feature of TypeScript in my VS2015 Cordova project. I have updated "target": "es6" in tsconfig.json Although there are no errors shown in intellisense, I encounter the following error while building the project ...

Using TypeScript to create a function with an argument that is optional based on a condition

I need a function that will only take a second argument when certain conditions are met. let func = <T extends boolean>(arg1: T, arg2: T extends true ? void : string) => {}; func(true); // ERROR Expected 2 arguments, but got 1 func(true, undefin ...

Adjusting canvas height in Storybook - Component does not fit properly due to low canvas height

I had a component that I needed to add to Storybook. It was working fine, but the styling was slightly off. I managed to resolve this by adding inline styling with position: absolute. Here is how it looks now: const Template: any = (args: any): any => ( ...