#Dynamic Modules: forRoot and forFeature

3 messages · Page 1 of 1 (latest)

wooden cloak
#

Hello, I'm trying to make sense of the forRoot and forFeature approach for creating dynamic modules.

I've found very good explanations online but not too many code examples.

If I understand well (probably not) importing a module with forRoot from the App module would allow me to share providers from the forRoot module with the forFeature one.
Is that correct?

I'm trying to follow an example from this post

but I cannot make it work, here you have a reproduction link: https://stackblitz.com/~/github.com/dami2/nestjs-for-root-for-feature

The module created from forRoot exports a the baseUrlProvider that should be accessible by the module created from forFeature

@Module({})
export class ApiWrapperModule {
  static forRoot(options: BaseApiConfig): DynamicModule {
    const baseUrlProvider: Provider = {
      provide: 'BASE_API_URL',
      useValue: options.baseUrl,
    };
    return {
      module: ApiWrapperModule,
      providers: [baseUrlProvider],
      exports: [baseUrlProvider],
    };
  }

  static forFeature(options: EndpointConfig): DynamicModule {
    const featureConfigProvider: Provider = {
      provide: 'API_ENDPOINT',
      useFactory: (baseApiUrl: string) => {
        return `${baseApiUrl}/${options.endpoint}`;
      },
      inject: ['BASE_API_URL'],
    };

    return {
      module: ApiWrapperModule,
      providers: [featureConfigProvider],
      exports: [featureConfigProvider],
    };
  }
}

but it seems this is not happening as I get the classic dependency not found error

what I'm missing here?

thanks in advance

Medium

Ever worked with TypeORM in your NestJS application? If you have, then you’ve certainly used the forRoot and forFeature methods without…

candid ether
#

@wooden cloak Did you ever end up figuring this out?

wooden cloak
#

Well, yes somehow. From my perspective, the article I posted is misguided or just incomplete.

If you want to share an instance between injection scopes, you probably want to implement the "core module" pattern. Which is an intricate way of using globals (IMHO).

Follow this stack overflow question to find out more about it: https://stackoverflow.com/questions/75755269/how-to-share-dynamic-module-in-nestjs

Btw: thanks for asking, I was feeling pretty alone in this thread 🤭