So I've got a NestJS project with a CustomConfigService which extends @nestjs/config and overrides some of it's methods to deal with environment variables and I've got a myApp.config.ts that contains a dozen of exported consts that return config blocks, like this:
export const deviConfig = () => {
return {
secret: config.get('SECRET_KEY'),
auth: config.get('AUTH_OPTION'),
steps: config.get('STEPS_OPTIONS'),
active: config.get('ENABLE_DEVI'),
};
};
That config.get is coming from my custom class with the overwritten .get() from ConfigService.
The main thing here is: If I'm going to use my CustomConfigService on my main, my app.module and maybe on some other providers, should I use dependency injection?
If I was about to use the actual ConfigService methods, I suppose I should, since that's how the NestJS docs tell us to do, but since it's a custom class that overrides the actual ConfigService, should I?
The way I'm doing currently is:
main.ts: const configService = app.get(CustomConfigService);
configService.get('VAR') // this is my custom method
app.module.ts: const configService = new(CustomConfigService);
configService.get('VAR') // also my custom method
Also... I'm not really sure when should I use DI and when it's okay to just use the new(MyService), could you please enlighten me?
I believe you should always use DI when you are within the NestJS app context, that mean within any module/service/controller or resolver.
for .module, normally when importing module there is a way to inject ConfigService to be used within forRootAsync. For example the following code retrieved from nestjs documentation
MongooseModule.forRootAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({
uri: configService.get<string>('MONGODB_URI'),
}),
inject: [ConfigService],
});
the only time when there is no way of doing DI is when you are outside of the NestJS context on main.ts, then you need to get the ConfigService from the initiated app (like the example you have shown for the main.ts)