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!