'How to init RouterModule with variable from ConfigService?

I want to use the RouterModule.register(arrayOfRoutes), but I need to build the arrayOfRoutes with a variable from the ConfigService.

What is the proper way to do that ?

Thanks for the help ! ;)

// current state, appRoutes is not customizable.

// app.routes.ts
export const appRoutes: Routes = [
  { path: RouteEnum.EndpointA, module: EndpointAModule },
  { path: RouteEnum.EndpointB, module: EndpointBModule },
];

// app.module.ts
@Module({
  imports: [
    ConfigModule.forRoot({ load: loadConfiguration(), cache: true, isGlobal: true }),
    RouterModule.register(appRoutes)
  ],
})
export class AppModule {}

I’d like to use some kind of service like this :

// routes.service.ts
@Injectable()
export class RoutesService {
  #routes: Routes = [
    { path: RouteEnum.EndpointA, module: EndpointAModule },
    { path: RouteEnum.EndpointB, module: EndpointBModule },
  ];

  constructor(private readonly configService: ConfigService) {
    if (this.configService.get('endpoint-c')?.enabled === true) {
      this.#routes.push({ path: RouteEnum.EndpointC, module: EndpointCModule });
    }
  }

  getRoutes(): RouteTree[] {
    return this.#routes;
  }
}


Solution 1:[1]

It ended like this :

  • stoping using the RouterModule
  • instead of RouterModule, using the @Controller('some_route') decorator directly in the controllers
  • modifying the default register method of the AppModule :
// app.module.ts
@Module({ imports: [...manyModules] })
export class AppModule {
  static register(configuration: Configuration): DynamicModule {
    const dynamicModule: DynamicModule = {
      module: AppModule,
      imports: [
        ConfigModule.forRoot({ load: [() => ({ configuration })], cache: true, isGlobal: true }),
      ],
    };
    if (configuration.myEndpointB.enabled) {
      // EndpointBModule contains a endpoint-b.controller, with the @Controller
      dynamicModule.imports?.push(EndpointBModule);
    }
    return dynamicModule;
  }
}
// main.ts
const app = await NestFactory.create<NestFastifyApplication>(
    AppModule.register(configuration),
    new FastifyAdapter()
  );

Handling the configuration before calling AppModule.register is what we wanted to do.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Seraf