Using NestJS to inject a Factory provider into another Factory

I've gone through various questions here, but none of them addressed my issue:

  • NestJS - Inject factory provider into another provider doesn't work

I'm trying to set up an async provider that retrieves configurations from a remote repository. Here's how I've implemented it:


import { Injectable, Provider } from '@nestjs/common';
@Injectable()
export class ApiConfigService {
  private config: any;

  public async init() {
    await new Promise((resolve) => setTimeout(resolve, 500));

    this.config = {
      data: 3,
    };
  }
}

export const API_CONFIG_FACTORY = 'API_CONFIG_FACTORY';

const createApiConfigFactory = () => {
  return {
    generate: async function () {
      const apiConfigService = new ApiConfigService();
      await apiConfigService.init();
      return apiConfigService;
    },
  };
};

export const ApiConfigFactory: Provider = {
  provide: API_CONFIG_FACTORY,
  useFactory: createApiConfigFactory,
};

api-config.module.ts:

import { Module } from '@nestjs/common';
import { ApiConfigFactory } from './api-config.service';

@Module({
  imports: [],
  providers: [ApiConfigFactory],
  exports: [ApiConfigFactory],
})
export class ApiConfigModule {}

I also want to use this module in the NestJS ThrottlerModule, but when attempting to do so:

import { Module } from '@nestjs/common';
import { ThrottlerModule } from '@nestjs/throttler';
import { ApiConfigModule } from './api-config/api-config.module';
import { ApiConfigFactory } from './api-config/api-config.service';

@Module({
  imports: [
    ApiConfigModule,
    ThrottlerModule.forRootAsync({
      imports: [ApiConfigModule],
      inject: [ApiConfigFactory],
      useFactory: (config: any) => {
        console.log('@config');
        console.log(config);

        return {
          ttl: config.get('throttle_api_ttl'),
          limit: config.get('throttle_api_limit'),
        };
      },
    }),
  ],
})
export class AppModule {}

This error is displayed:

Error: Nest can't resolve dependencies of the THROTTLER:MODULE_OPTIONS (?). Please make sure that the argument [object Object] at index [0] is available in the ThrottlerModule context.

Potential solutions:
- If [object Object] is a provider, ensure it's part of the current ThrottlerModule.
- If [object Object] is exported from a separate @Module, confirm that the module is imported within ThrottlerModule.
  @Module({
    imports: [ /* the Module containing [object Object] */ ]
  })

How can I successfully implement an async configuration provider that can be injected into ThrottlerModule?

Thank you for your assistance!

Answer №1

To ensure that your code runs accurately, simply replace instances of ApiConfigFactory with API_CONFIG_FACTORY, and specify the config service that is received:

ThrottlerModule.forRootAsync({
  imports: [ApiConfigModule],
  inject: [API_CONFIG_FACTORY],                // -> Enter Provider token HERE
  useFactory: (config: ApiConfigService) => {  // -> Use ApiConfigService HERE
    return {
      ttl: config.get('throttle_api_ttl'),
      limit: config.get('throttle_api_limit'),
    };
  },
}),

Alternatively, you can simplify your code with the following modifications:

api-config.module.ts:

@Module({
  imports: [],
  providers: [
    {
      provide: ApiConfigService,
      useFactory: async () => {
        const apiConfigService = new ApiConfigService();
        await apiConfigService.init();
        return apiConfigService;
      },
    },
  ],
  exports: [ApiConfigService],
})
export class ApiConfigModule {}

Then, in the app.module.ts file:

ThrottlerModule.forRootAsync({
  imports: [ApiConfigModule],
  inject: [ApiConfigService],
  useFactory: (config: ApiConfigService) => {
    return {
      ttl: config.get('throttle_api_ttl'),
      limit: config.get('throttle_api_limit'),
    };
  },
}),

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

Tips for organizing HTML logic in a separate document

I am faced with the task of displaying a list in HTML based on specific conditions: <!-- Display list if there are more than 5 results --> <div list.numberOfResults > 10"> <b>Name: </b>{{list.name}} <b>ID ...

Bring in all subdirectories dynamically and export them

Here is what I currently have: -main.js -routeDir -subfolder1 -index.js -subfolder2 -index.js ... -subfolderN -index.js Depending on a certain condition, the number of subfolders can vary. Is there a way to dynam ...

Maintain hook varieties during implementation of array deconstruction

I have been developing a straightforward hook to export animation helper and element reference. import { gsap } from 'gsap'; import { useRef } from 'react'; export function useTween<R extends gsap.TweenTarget>(vars: gsap.TweenVar ...

Having trouble sending posts to an API route with Angular's HTTP module

When attempting to send values via a POST request in the URL of an Angular5 Laravel API route, I encountered an issue. Despite not receiving any errors in the browser console, no network activity was recorded upon sending the request. It is perplexing as I ...

"Utilizing jQuery and Bootstrap 4 in TypeScript, attempting to close modal window using jQuery is not functioning

Trying to make use of jquery to close a bootstrap modal within an angular project using typescript code. The following is the code: function call in html: (click)="populaterfpfromsaved(i, createSaved, createProp)" createSaved and createProp are local ...

Convert Time: segment time devoted to the main content from the time dedicated to advertisements

Can anyone assist me with solving a math problem? Let's consider two lists or arrays: Content Array 0-50 = C1 50-100 = C2 AD Array 10-20 = A1 30-60 = A2 80-140 = A3 The desired output should be: 0-10 = C1 10-20 = A1 20-30 = C1 30-60 = A2 60-80 = C ...

Encountering a promise error when using TypeScript and React Lazy

I've been working with React and TypeScript, incorporating a higher order component to verify user authentication. However, after implementing the hoc, I encountered an error in my routes: /home/nidhin/Documents/Nidhinbackup/F/iot-remsys-demotwo/rem ...

Issue with Jest mock function failing to trigger axios instance function causing it to return undefined

I initially found a solution on this StackOverflow thread However, I wanted to add my own helper function that generates a fresh Axios instance with the user's authentication token. Here is what I came up with: import axios from "axios"; c ...

Facing the issue once more - Angular displaying "Http failure response for... 0 Unknown Error"

I have been researching extensively on this issue, particularly on Stack Overflow. Many of the responses point to it being a CORS problem, but I am uncertain if that is the case in my situation. Therefore, I am reaching out for help once again and would gr ...

How can you expand the class of a library object in Animate CC using Createjs?

I am currently in the process of migrating a large flash application to canvas using Typescript, and I'm facing challenges when it comes to utilizing classes to extend library objects. When working with a class library for buttons, class BtnClass { ...

Struggling to retrieve posted data using Angular with asp.net

I have encountered an issue while sending a post request from Angular to my ASP.NET server. I am trying to access the values of my custom model class (SchoolModel) and I can see that all the values are correct inside Angular. However, when I attempt to ret ...

Issue: Vue TypeScript module not foundDescription: When using

Is there anyone out there who can assist me with this issue regarding my tsconfig.json file? { "compilerOptions": { "target": "esnext", "module": "esnext", "moduleResolution": " ...

creating a JSON array within a function

I am currently developing an Angular application and working on a component with the following method: createPath(node, currentPath = []){ if(node.parent !==null) { return createPath(node.parent, [node.data.name, ...currentPath]) } else { retu ...

Identify the general type according to a boolean property for a React element

Currently, I am facing a scenario where I need to handle two different cases using the same component depending on a boolean value. The technologies I am working with include React, Typescript, and Formik. In one case, I have a simple select box where th ...

Having trouble retrieving information from a JSON object? Unable to retrieve property 'company_about' of an undefined object?

Here is the JSON data I have: [ { "id": 1, "job_id": 1, "company_profile": "Sales and Marketing", "company_about": "Established in 1992 , it is a renouned marketing company", "company_product": "Ford,Mustang,Beetle", "key_skills": ...

What makes Mathematics a unique object in JavaScript programming?

Recently, I've dived into learning Javascript, so pardon me if my doubts seem a bit illogical. I came across the definition for a Math object, and here is the code snippet: interface Math { /** The mathematical constant e. This is Euler's nu ...

Step-by-Step Tutorial: Displaying Loading Text in Child Components with Angular 4

Within my "event.component" file, I have a nested component (app-grouplist) <div class="group-list"> <app-grouplist [hasStarted]="started" [hasEnded]="ended" Displaying Loading Groups... </app-grouplist> </div> Upon the initial page ...

Tips for mock nesting a repository in TypeORM?

I'm struggling to figure out how to stub a nested Repository in TypeORM. Can anyone assist me in creating a sinon stub for the code snippet below? I attempted to use some code from another Stack Overflow post in my test file, but it's not working ...

In tsconfig.json, the compiler is not utilizing other tsconfig.json files when using the "extends"

I'm attempting to streamline my project by breaking up my tsconfig.json into separate files. I have one for the source files and another for the tests. However, when I utilize the extends field, it seems that only the base tsconfig.json is being utili ...

What is the best way to utilize a variable from a function when using ngClass in Angular?

Currently, using Angular 4, I'm attempting to utilize ngClass by comparing a variable called sender which is created within a function with an object from an array known as item.sender. Below is the snippet of HTML code: <ion-card *ngFor="let ite ...