'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); } } app.listen(process.env.PORT || 3000); })();