brainz-social-old/app.js
Andrew Pietila 58adbdc459 Allow routes to use app.route()
Concerns were raised that the previous method potentially made middleware more complicated. In order to allay this, hoist the full route into the route file. Still a single route per file, but facilitates simpler middleware.
2023-03-24 01:33:25 -05:00

61 lines
2.4 KiB
JavaScript

'use strict';
const express = require('express');
const glob = require('glob');
const { match: createPathMatch } = require('path-to-regexp');
(async () => {
const app = express();
const routes = await glob('**/*.js', {
cwd: './routes',
dot: true,
});
const pathMatches = [];
app.use((req, _res, next) => {
const requestUrl = new URL(req.url, 'https://example.com/');
let candidateUrl = '';
let secondCandidateUrl = '';
for ( const pathMatch in pathMatches ) {
if ( pathMatches[pathMatch](requestUrl.pathname) ) {
// If we get an exact match, we don't need to process further.
return next();
} else if ( requestUrl.pathname.endsWith('/') && pathMatches[pathMatch](`${requestUrl.pathname}index`) ) {
// If we end with a /, and the index path matches, lets do the index path, but prioritize the non-index path.
const secondRequestUrl = new URL(requestUrl);
secondRequestUrl.pathname = `${requestUrl.pathname}index`;
candidateUrl = secondRequestUrl.toString().substring(19);
} else if ( pathMatches[pathMatch](`${requestUrl.pathname}/index`) ) {
// If we don't end with a /, and the /index path matches, lets do the /index path, but prioritize paths checked previously.
const secondRequestUrl = new URL(requestUrl);
secondRequestUrl.pathname = `${requestUrl.pathname}/index`;
secondCandidateUrl = secondRequestUrl.toString().substring(19);
}
}
if ( candidateUrl !== '' ) {
req.url = candidateUrl;
console.log(candidateUrl);
return next();
}
if ( secondCandidateUrl !== '' ) {
req.url = secondCandidateUrl;
return next();
}
return next();
} );
for ( const routeScript in routes ) {
const route = routes[routeScript].replace(/\.js$/, '');
console.log(route);
pathMatches.push( createPathMatch(`/${route}`));
const routeObj = require(`./routes/${route}`);
if ( routeObj.get ) {
app.get(`/${route}`, routeObj.get);
}
if ( routeObj.post ) {
app.post(`/${route}`, routeObj.post);
}
if ( routeObj.route ) {
routeObj.route(app.route(`/${route}`));
}
}
app.listen(process.env.PORT || 3000);
})();