1
1
import { Router } from 'express'
2
-
3
- import Hello from './routes/hello'
4
-
2
+ import path from 'path'
3
+ import fs from 'fs'
5
4
export default class Routes {
6
5
private router : Router
7
6
@@ -11,7 +10,40 @@ export default class Routes {
11
10
}
12
11
13
12
private initRoutes ( ) {
14
- this . router . use ( '/' , Hello )
13
+ const routePath = path . join ( __dirname , 'routes' )
14
+ this . loadRoutes ( routePath )
15
+ }
16
+
17
+ private loadRoutes ( routePath ) {
18
+ const items = fs . readdirSync ( routePath )
19
+
20
+ items . forEach ( ( item ) => {
21
+ const itemPath = path . join ( routePath , item )
22
+ const stats = fs . statSync ( itemPath )
23
+
24
+ if ( stats . isDirectory ( ) ) {
25
+ this . loadRoutes ( itemPath )
26
+ } else if ( stats . isFile ( ) ) {
27
+ if ( item . endsWith ( '.js' ) || item . endsWith ( '.ts' ) ) {
28
+
29
+ if ( item . toLowerCase ( ) . startsWith ( 'root' ) ) {
30
+ this . router . use ( '/' , require ( itemPath ) . default )
31
+ return ;
32
+ }
33
+
34
+ const modulePath = itemPath . replace ( / \. [ A - z ] { 1 , 2 } / gm, '' )
35
+
36
+ const routeModule = require ( modulePath ) . default
37
+
38
+ const mountPath = path
39
+ . relative ( path . join ( __dirname , 'routes' ) , modulePath )
40
+ . replace ( / \\ / g, '/' )
41
+ . toLowerCase ( )
42
+
43
+ this . router . use ( `/${ mountPath } ` , routeModule )
44
+ }
45
+ }
46
+ } )
15
47
}
16
48
17
49
public getRouter ( ) {
0 commit comments