brainz-social-old/app.js

52 lines
No EOL
2.2 KiB
JavaScript

const express = require('express');
const fsPromises = require('fs').promises;
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(async (req, res, next) => {
const requestUrl = new URL(req.url, "https://example.com/");
var candidateUrl = "";
var secondCandidateUrl = "";
for ( let pathMatch in pathMatches ) {
if ( patchMatches[pathMatch](requestUrl.pathname) ) {
// If we get an exact match, we don't need to process further.
return next();
} else if ( requestUrl.pathname.endsWith('/') && patchMatches[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.
let secondRequestUrl = new URL(requestUrl);
secondRequestUrl.pathname = `${requestUrl.pathname}index`;
candidateUrl = secondRequestUrl.toString().substring(19);
} else if ( pathName[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.
let secondRequestUrl = new URL(requestUrl);
secondRequestUrl.pathname = `${requestUrl.pathname}/index`;
secondCandidateUrl = secondRequestUrl.toString().substring(19);
}
}
if ( candidateUrl !== "" ) {
req.url = candidateUrl;
return next();
}
if ( secondCandidateUrl !== "" ) {
req.url = secondCandidateUrl;
return next();
}
return next();
});
for ( let routeScript in routes ) {
let route = routes[routeScript].replace(/\.js$/, "");
pathMatches.push(createPathMatch(route));
let routeObj = require(`./routes/${route}`);
if ( routeObj.get ) {
app.get(`/${route}`, routeObj.get);
}
}
app.listen(process.env.PORT || 3000);
})();