Skip to content

Commit ddc791a

Browse files
committed
feat: recursively load routes
1 parent 2525f91 commit ddc791a

File tree

2 files changed

+36
-4
lines changed

2 files changed

+36
-4
lines changed

src/routes.ts

+36-4
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import { Router } from 'express'
2-
3-
import Hello from './routes/hello'
4-
2+
import path from 'path'
3+
import fs from 'fs'
54
export default class Routes {
65
private router: Router
76

@@ -11,7 +10,40 @@ export default class Routes {
1110
}
1211

1312
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+
})
1547
}
1648

1749
public getRouter() {
File renamed without changes.

0 commit comments

Comments
 (0)