#Dependency Injection for a config token

1 messages · Page 1 of 1 (latest)

sonic mortar
#

I have a package inside a lerna project which has a dynamic module which contains a provider defined by a string. It's pretty much similar to the dynamic module described in nestjs docs.

import { DynamicModule, Module } from '@nestjs/common';
import { ConfigService } from './config.service';

@Module({})
export class ConfigModule {
  static register(options: Record<string, any>): DynamicModule {
    return {
      module: ConfigModule,
      providers: [
        {
          provide: 'CONFIG_OPTIONS',
          useValue: options,
        },
        ConfigService,
      ],
      exports: [ConfigService],
    };
  }
}

I'm facing a dependency issue when using generated package inside another repo because nest cannot resolve dependency for CONFIG_OPTIONS.

If I export the same JSON object that is in providers the issue disappears, but that change looks as a wrong way.

This is happening in nest 9.4.0, and it works in version 8(i'm migration from 8 to 9).

Can I get some guidance about the issue and accurate solution(s)? Thanks in advance.

rare lark
#

do you need to use the CONFIG_OPTIONS provider outside of ConfigModule, or just inside ConfigService? If the latter is the case, you shouldn't need to export it.

Another thing that comes to mind is whether you did not put ConfigService in another module's providers array, too, in which case it would look to the options there and wouldn't find them.

sonic mortar
proud egret
#

The issue is that the AuthInterceptor injects the options, but the options are only existent if AuthModule.forRoot() is called. What I would do is move the AuthInterceptor andthe APP_INTERCPETOR provider to the providers of the dynamic module (the forRoot) so that it only gets bound when .forRoot() is called and then the AuthServcie doesn't have to care about it

sonic mortar
#

AuthModule.forRoot() is being called in app.module.ts, should it work anyway?

proud egret
#

Should what work?

rare lark
#

Interceptors (and other enhancers) look for injected providers in the module that they're used in, that means if the intecepror is used on a controller in SomeModule, then the CONFIG_OPTIONS provider must be available there.

sonic mortar
#

What if I call AuthModule.forRoot({ isGlobal: true }) ? The module is now global, but error remains.

proud egret
#

Do you export the token in the exports array of the dynamic module?

sonic mortar
#

Yes

proud egret
#

What's the error? Do you have a reproduction?