1
1
import { Module , DynamicModule } from '@nestjs/common' ;
2
- import { MODULE_PATH } from '@nestjs/common/constants' ;
2
+ import { MODULE_PATH , PATH_METADATA } from '@nestjs/common/constants' ;
3
+ import { ModulesContainer } from '@nestjs/core/injector/modules-container' ;
4
+ import { Controller , Type } from '@nestjs/common/interfaces' ;
5
+ import { UnknownElementException } from '@nestjs/core/errors/exceptions/unknown-element.exception' ;
3
6
import { validatePath } from './utils/validate-path.util' ;
4
7
import { flatRoutes } from './utils/flat-routes.util' ;
5
8
import { Routes } from './routes.interface' ;
@@ -10,6 +13,17 @@ import { Routes } from './routes.interface';
10
13
*/
11
14
@Module ( { } )
12
15
export class RouterModule {
16
+ private static readonly routesContainer : Map < string , string > = new Map ( ) ;
17
+ constructor ( readonly modulesContainer : ModulesContainer ) {
18
+ const modules = [ ...modulesContainer . values ( ) ] ;
19
+ for ( const nestModule of modules ) {
20
+ const modulePath : string = Reflect . getMetadata ( MODULE_PATH , nestModule . metatype ) ;
21
+ for ( const route of nestModule . routes . values ( ) ) {
22
+ RouterModule . routesContainer . set ( route . name , validatePath ( modulePath ) ) ;
23
+ }
24
+ }
25
+ }
26
+
13
27
/**
14
28
* takes an array of modules and organize them in hierarchy way
15
29
* @param {Routes } routes Array of Routes
@@ -20,6 +34,21 @@ export class RouterModule {
20
34
module : RouterModule ,
21
35
} ;
22
36
}
37
+
38
+ /**
39
+ * get the controller full route path eg: (controller's module prefix + controller's path).
40
+ * @param {Type<Controller> } controller the controller you need to get it's full path
41
+ */
42
+ public static resolvePath ( controller : Type < Controller > ) : string {
43
+ const controllerPath : string = Reflect . getMetadata ( PATH_METADATA , controller ) ;
44
+ const modulePath = RouterModule . routesContainer . get ( controller . name ) ;
45
+ if ( modulePath && controllerPath ) {
46
+ return validatePath ( modulePath + controllerPath ) ;
47
+ } else {
48
+ throw new UnknownElementException ( ) ;
49
+ }
50
+ }
51
+
23
52
private static buildPathMap ( routes : Routes ) {
24
53
const flattenRoutes = flatRoutes ( routes ) ;
25
54
flattenRoutes . forEach ( route => {
0 commit comments