Skip to content

feat(ConditionalModule): Add ConditionalModule for async config-based module registrationΒ #1968

@loss-and-quick

Description

@loss-and-quick

Is there an existing issue that is already proposing this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe it

The current implementation is completely tied to environment variables, I was able to implement a test variant of dynamic loading of modules based on the config settings

Describe the solution you'd like

Implement a ConditionalModule utility that enables asynchronous, environment-driven module registration in NestJS. This module would allow developers to conditionally load other modules based on dynamic variables( like env or configs)

import { DynamicModule, Logger, Module, Provider } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

@Module({})
export class ConditionalModule {
    static registerWhenAsync(
        targetModule: DynamicModule,
        options: {
            useFactory: (config: ConfigService) => boolean | Promise<boolean>;
            inject?: any[];
            debug?: boolean;
        },
    ): DynamicModule {
        const CONDITION_TOKEN = 'CONDITION_PROVIDER';
        const logger = new Logger('ConditionalModule');

        const conditionProvider: Provider = {
            provide: CONDITION_TOKEN,
            useFactory: async (config: ConfigService) => {
                try {
                    const result = await options.useFactory(config);
                    if (options.debug) {
                        logger.log(`Condition result: ${result}`);
                    }
                    return result;
                } catch (error) {
                    if (options.debug) {
                        logger.error(`Condition check failed: ${error.message}`);
                    }
                    return false;
                }
            },
            inject: [ConfigService, ...(options.inject || [])],
        };

        // The module that provides the condition
        const conditionalLoaderModule = {
            module: class ConditionalLoaderModule { },
            providers: [conditionProvider],
            exports: [CONDITION_TOKEN],
        };

        return {
            module: ConditionalModule,
            imports: [
                {
                    module: class DynamicImportModule { },
                    imports: [conditionalLoaderModule, targetModule],
                    providers: [
                        {
                            provide: 'DYNAMIC_IMPORT',
                            useFactory: (condition: boolean) => {
                                return condition ? targetModule : null;
                            },
                            inject: [CONDITION_TOKEN],
                        },
                    ],
                },
            ],
        };
    }
}

Teachability, documentation, adoption, migration strategy

@Module({
imports: [  
        ConditionalModule.registerWhenAsync(  
          FeatureModule,  
          {  
            useFactory: (config: ConfigService) =>  
              config.get('ENABLE_FEATURE') === 'true',  
            inject: [ConfigService],  
            debug: true,  
          },  
        ),  
      ],  
})  
class AppModule {}  

What is the motivation / use case for changing the behavior?

Customization of module loading behavior based on settings from any environment (files, env variables)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions