1
0
mirror of https://github.com/matt-fidd/stratos.git synced 2026-01-01 20:39:28 +00:00

Added seperate routes folder and dynamic route loader

This commit is contained in:
2022-01-31 10:15:46 +00:00
parent a41d0d37d8
commit a28862c9f1
2 changed files with 39 additions and 5 deletions

30
app.js
View File

@@ -4,6 +4,7 @@
const bodyParser = require('body-parser'); const bodyParser = require('body-parser');
const express = require('express'); const express = require('express');
const { engine } = require('express-handlebars'); const { engine } = require('express-handlebars');
const fs = require('fs');
const path = require('path'); const path = require('path');
const session = require('express-session'); const session = require('express-session');
const serveFavicon = require('serve-favicon'); const serveFavicon = require('serve-favicon');
@@ -13,6 +14,28 @@ const serveStatic = require('serve-static');
const DatabaseConnectionPool = require('./lib/DatabaseConnectionPool'); const DatabaseConnectionPool = require('./lib/DatabaseConnectionPool');
const importJSON = require('./lib/importJSON'); const importJSON = require('./lib/importJSON');
/**
* loadRoutes() Loads all of the routes from /routers into a map
*
* @return {Map<String, Object>} Map of all of the routes
*/
function loadRoutes() {
// Load route files
const routes = new Map();
const routeFiles =
fs.readdirSync(path.join(__dirname, 'routes'))
.filter(file => file.endsWith('.js'));
for (const file of routeFiles) {
const route = require(path.join(__dirname, 'routes', file));
routes.set(route.root, route.router);
}
return routes;
}
async function main() { async function main() {
// Import config files // Import config files
const serverOptions = importJSON('server'); const serverOptions = importJSON('server');
@@ -57,11 +80,8 @@ async function main() {
} }
})); }));
app.get('/', (req, res) => { for (const [ root, router ] of loadRoutes().entries())
return res.render('index', { app.use(root, router);
title: 'Stratos - Home'
});
});
// If the request gets to the bottom of the route stack, it doesn't // If the request gets to the bottom of the route stack, it doesn't
// have a defined route and therefore a HTTP status code 404 is sent // have a defined route and therefore a HTTP status code 404 is sent

14
routes/main.js Normal file
View File

@@ -0,0 +1,14 @@
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
return res.render('index', {
title: 'Stratos - Home'
});
});
module.exports = {
root: '/',
router: router
};