0
0
NestJSframework~20 mins

Dynamic modules in NestJS - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Dynamic Module Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this dynamic module registration?
Consider this NestJS dynamic module code. What will be the value of ConfigService.get('mode') after importing ConfigModule.forRoot({ mode: 'production' }) in the root module?
NestJS
import { Module, DynamicModule } from '@nestjs/common';

@Module({})
export class ConfigModule {
  static forRoot(options: { mode: string }): DynamicModule {
    return {
      module: ConfigModule,
      providers: [
        {
          provide: 'CONFIG_OPTIONS',
          useValue: options,
        },
        {
          provide: ConfigService,
          useFactory: (opts) => new ConfigService(opts.mode),
          inject: ['CONFIG_OPTIONS'],
        },
      ],
      exports: [ConfigService],
    };
  }
}

export class ConfigService {
  constructor(private mode: string) {}
  get(key: string) {
    if (key === 'mode') return this.mode;
    return null;
  }
}
A'production'
B'development'
Cundefined
Dnull
Attempts:
2 left
💡 Hint
Look at how the ConfigService is created using the useFactory and what value is passed from forRoot.
📝 Syntax
intermediate
2:00remaining
Which option correctly defines a dynamic module with async configuration?
You want to create a dynamic module that loads configuration asynchronously. Which code snippet correctly implements forRootAsync in NestJS?
A
static forRootAsync(options: { useFactory: () => Promise<{ apiKey: string }> }): DynamicModule {
  return {
    module: ConfigModule,
    providers: [
      {
        provide: 'CONFIG_OPTIONS',
        useFactory: options.useFactory,
        inject: ['CONFIG_OPTIONS'],
      },
      ConfigService,
    ],
    exports: [ConfigService],
  };
}
B
static forRootAsync(options: { useFactory: () => Promise<{ apiKey: string }> }): DynamicModule {
  return {
    module: ConfigModule,
    providers: [
      {
        provide: 'CONFIG_OPTIONS',
        useFactory: options.useFactory,
      },
      ConfigService,
    ],
    exports: [ConfigService],
  };
}
C
static forRootAsync(options: { useFactory: () => Promise<{ apiKey: string }> }): DynamicModule {
  return {
    module: ConfigModule,
    providers: [
      {
        provide: 'CONFIG_OPTIONS',
        useValue: options.useFactory(),
      },
      ConfigService,
    ],
    exports: [ConfigService],
  };
}
D
static forRootAsync(options: { useFactory: () => Promise<{ apiKey: string }> }): DynamicModule {
  return {
    module: ConfigModule,
    providers: [
      {
        provide: 'CONFIG_OPTIONS',
        useFactory: options.useFactory,
        inject: [],
      },
      {
        provide: ConfigService,
        useFactory: async (opts) => new ConfigService((await opts).apiKey),
        inject: ['CONFIG_OPTIONS'],
      },
    ],
    exports: [ConfigService],
  };
}
Attempts:
2 left
💡 Hint
Remember that async factories require useFactory with async and proper injection.
🔧 Debug
advanced
2:00remaining
Why does this dynamic module cause a runtime error?
Given this dynamic module code, why does NestJS throw a runtime error about missing provider for 'API_KEY'?
NestJS
import { Module, DynamicModule, Injectable, Inject } from '@nestjs/common';

@Module({})
export class ApiModule {
  static forRoot(apiKey: string): DynamicModule {
    return {
      module: ApiModule,
      providers: [
        {
          provide: 'API_KEY',
          useValue: apiKey,
        },
        ApiService,
      ],
      exports: [ApiService],
    };
  }
}

@Injectable()
export class ApiService {
  constructor(@Inject('API_KEY') private readonly key: string) {}
}
AThe 'API_KEY' provider is missing from the providers array.
BThe ApiService constructor parameter is not decorated with @Inject('API_KEY'), so Nest cannot inject the value.
CThe dynamic module does not export 'API_KEY', so it cannot be injected.
DThe ApiService class is not decorated with @Injectable(), so it cannot be instantiated.
Attempts:
2 left
💡 Hint
Check how NestJS matches constructor parameters to providers.
🧠 Conceptual
advanced
1:30remaining
What is the main benefit of using dynamic modules in NestJS?
Why would a developer choose to use dynamic modules instead of static modules in NestJS?
ATo automatically generate REST endpoints without writing controllers.
BTo improve runtime performance by compiling modules ahead of time.
CTo allow modules to be configured with different parameters at import time, enabling reusable and customizable modules.
DTo enable modules to be lazy-loaded only when needed by the application.
Attempts:
2 left
💡 Hint
Think about how dynamic modules accept parameters and change behavior.
state_output
expert
2:30remaining
What is the value of service.getValue() after this dynamic module setup?
Given the following NestJS dynamic module and service, what will service.getValue() return after importing ExampleModule.forFeature({ value: 42 })?
NestJS
import { Module, DynamicModule, Injectable, Inject } from '@nestjs/common';

@Injectable()
export class ExampleService {
  constructor(@Inject('FEATURE_OPTIONS') private options: { value: number }) {}
  getValue() {
    return this.options.value;
  }
}

@Module({})
export class ExampleModule {
  static forFeature(options: { value: number }): DynamicModule {
    return {
      module: ExampleModule,
      providers: [
        {
          provide: 'FEATURE_OPTIONS',
          useValue: options,
        },
        ExampleService,
      ],
      exports: [ExampleService],
    };
  }
}
A42
BThrows a runtime error due to missing provider
Cnull
Dundefined
Attempts:
2 left
💡 Hint
Check how the service receives the injected options and what value is passed.