DEV Community

Discussion on: Advanced NestJS: Dynamic Providers

Collapse
 
dannyhuly profile image
Daniel Huly

Great article. I was looking for this kind of example.

I had only one issue with re-exporting the dynamic LoggerModule.
The prefixesForLoggers was not call in time (same issues as you explained in the article) due to other modules loading.

In my case I have a CoreModule that includes many base modules and services.

I was able to overcome the issue by making the LoggerModule an Asyc module (using Promise and setTimeout(..., 0)). This let all the files and @Logger(...) to be called and add all the prefixes to prefixesForLoggers array before resolving.

// logger.module.ts

export class LoggerModule {
  static forRoot(): Promise<DynamicModule> {

    return new Promise(resolve => {
      setTimeout(() => {
        const prefixedLoggerProviders = createLoggerProviders();
        resolve({
          module: LoggerModule,
          providers: [LoggerService, ...prefixedLoggerProviders],
          exports: [LoggerService, ...prefixedLoggerProviders],
        })
      }, 0);
    })

  }
}
Enter fullscreen mode Exit fullscreen mode

Thanks :)