Created
June 8, 2025 23:04
-
-
Save dandean/6b5db30d3b2e59f261d9c03cf7385120 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Controller, Get, Module, OnApplicationBootstrap} from '@nestjs/common'; | |
import { | |
ModulesContainer, | |
NestFactory, | |
Reflector, | |
RouterModule, | |
} from '@nestjs/core'; | |
@Controller('controller-1') | |
class Controller1 { | |
@Get('index') | |
index() {} | |
} | |
@Module({ | |
imports: [], | |
controllers: [Controller1], | |
providers: [], | |
exports: [], | |
}) | |
class Module1 {} | |
@Controller('controller-2') | |
class Controller2 { | |
@Get('index') | |
index() {} | |
} | |
@Module({ | |
imports: [], | |
controllers: [Controller2], | |
providers: [], | |
exports: [], | |
}) | |
class Module2 {} | |
@Module({ | |
imports: [ | |
Module1, | |
RouterModule.register([{path: 'module-1', module: Module1}]), | |
Module2, | |
RouterModule.register([{path: 'module-2', module: Module2}]), | |
], | |
controllers: [], | |
providers: [], | |
exports: [], | |
}) | |
export class RouteDiscoveryAppModule implements OnApplicationBootstrap { | |
constructor( | |
private modulesContainer: ModulesContainer, | |
private reflector: Reflector | |
) {} | |
onApplicationBootstrap() { | |
const modules = Array.from(this.modulesContainer.values()); | |
const modulesWithPathPrefix = modules | |
.map((module) => { | |
const metadataKeys = Reflect.getMetadataKeys(module.metatype); | |
const pathKey = metadataKeys.find((key) => | |
String(key).startsWith('__module_path__') | |
); | |
const path = pathKey | |
? this.reflector.get(pathKey, module.metatype) | |
: undefined; | |
return {path, module}; | |
}) | |
.filter(({path}) => Boolean(path)); | |
console.log(modulesWithPathPrefix); | |
} | |
} | |
Promise.resolve().then(async () => { | |
const app = await NestFactory.create(RouteDiscoveryAppModule); | |
app.listen(3001); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment