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();
|
||||
})
|
||||
|
||||
// Load routes dynamically from routes/**
|
||||
// Load routes from routes/* recursively
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const routesPath = path.join(__dirname, 'routes');
|
||||
// Load recursively
|
||||
function loadRoutes(dir) {
|
||||
fs.readdirSync(dir).forEach(file => {
|
||||
const fullPath = path.join(dir, file);
|
||||
if (fs.lstatSync(fullPath).isDirectory()) {
|
||||
const stat = fs.statSync(fullPath);
|
||||
if (stat.isDirectory()) {
|
||||
loadRoutes(fullPath);
|
||||
} else if (file.endsWith('.js')) {
|
||||
} else if (stat.isFile() && file.endsWith('.js')) {
|
||||
const route = require(fullPath);
|
||||
if (route.path && route.router) {
|
||||
app.use(route.path, route.router);
|
||||
console.log(`Loaded route: ${route.path} from ${fullPath}`);
|
||||
}
|
||||
// Derive the route path from the file path
|
||||
const routePath = '/' + path.relative(path.join(__dirname, 'routes'), 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, () => {
|
||||
console.log(`Listening on ${port}`);
|
||||
|
|
|
|||
|
|
@ -18,4 +18,6 @@ router.post('/', async (req, res) => {
|
|||
return res.status(200).json({ message: 'Heartbeat data recorded' });
|
||||
}
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
|
|
@ -17,4 +17,6 @@ router.post('/', async (req, res) => {
|
|||
return res.status(200).json({ message: 'Shutdown data recorded' });
|
||||
}
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
|
|
@ -19,4 +19,6 @@ router.post('/', async (req, res) => {
|
|||
return res.status(200).json({ message: 'Startup data recorded' });
|
||||
}
|
||||
)
|
||||
});
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
Loading…
Reference in a new issue