Load routes properly. its been a minute
This commit is contained in:
parent
1253db406e
commit
2fd2151f63
23
index.js
23
index.js
|
|
@ -34,26 +34,29 @@ app.use((req, res, next) => {
|
||||||
next();
|
next();
|
||||||
})
|
})
|
||||||
|
|
||||||
// Load routes dynamically from routes/**
|
// Load routes from routes/* recursively
|
||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
const routesPath = path.join(__dirname, 'routes');
|
|
||||||
// Load recursively
|
|
||||||
function loadRoutes(dir) {
|
function loadRoutes(dir) {
|
||||||
fs.readdirSync(dir).forEach(file => {
|
fs.readdirSync(dir).forEach(file => {
|
||||||
const fullPath = path.join(dir, file);
|
const fullPath = path.join(dir, file);
|
||||||
if (fs.lstatSync(fullPath).isDirectory()) {
|
const stat = fs.statSync(fullPath);
|
||||||
|
if (stat.isDirectory()) {
|
||||||
loadRoutes(fullPath);
|
loadRoutes(fullPath);
|
||||||
} else if (file.endsWith('.js')) {
|
} else if (stat.isFile() && file.endsWith('.js')) {
|
||||||
const route = require(fullPath);
|
const route = require(fullPath);
|
||||||
if (route.path && route.router) {
|
// Derive the route path from the file path
|
||||||
app.use(route.path, route.router);
|
const routePath = '/' + path.relative(path.join(__dirname, 'routes'), fullPath)
|
||||||
console.log(`Loaded route: ${route.path} from ${fullPath}`);
|
.replace(/\\/g, '/') // Windows compatibility
|
||||||
}
|
.replace('.js', '')
|
||||||
|
.replace(/index$/,'');
|
||||||
|
app.use(routePath, route);
|
||||||
|
console.log(`Loaded route: ${routePath} from ${fullPath}`);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
loadRoutes(routesPath);
|
|
||||||
|
loadRoutes(path.join(__dirname, 'routes'));
|
||||||
|
|
||||||
app.listen(port, () => {
|
app.listen(port, () => {
|
||||||
console.log(`Listening on ${port}`);
|
console.log(`Listening on ${port}`);
|
||||||
|
|
|
||||||
|
|
@ -19,3 +19,5 @@ router.post('/', async (req, res) => {
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
|
|
@ -18,3 +18,5 @@ router.post('/', async (req, res) => {
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
|
|
@ -20,3 +20,5 @@ router.post('/', async (req, res) => {
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
});
|
});
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
Loading…
Reference in a new issue