66 lines
2.7 KiB
JavaScript
66 lines
2.7 KiB
JavaScript
'use strict';
|
|
|
|
const express = require('express');
|
|
const glob = require('glob');
|
|
const log4js = require('log4js');
|
|
const { match: createPathMatch } = require('path-to-regexp');
|
|
const log = require('./lib/log');
|
|
|
|
(async () => {
|
|
const app = express();
|
|
const routes = await glob('**/*.js', {
|
|
cwd: './routes',
|
|
dot: true,
|
|
});
|
|
app.use(log4js.connectLogger(log.accessLog, {
|
|
level: 'auto',
|
|
format: ':remote-addr - - ":method :url HTTP/:http-version" :status :content-length ":referrer" ":user-agent"'
|
|
}));
|
|
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;
|
|
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);
|
|
})();
|