brainz-social-old/app.js

82 lines
3.1 KiB
JavaScript

"use strict";
const express = require("express");
const {glob} = require("glob");
const {match: createPathMatch} = require("path-to-regexp");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const qs = require("qs");
const databaseHandler = require("./lib/database-handler");
(async () => {
const app = express();
app.set("query parser", "extended");
app.use(bodyParser.json({
type: "application/*+json",
verify (req, _res, buf) {
req.rawBody = buf;
},
}));
app.use(bodyParser.json({
verify (req, _res, buf) {
req.rawBody = buf;
},
}));
app.use(bodyParser.urlencoded({
extended: false,
verify (req, _res, buf) {
req.rawBody = buf;
},
}));
app.use(cookieParser());
const routes = await glob("**/*.js", {
cwd: "./routes",
dot: true,
});
const pathMatches = [];
app.use((req, _res, next) => {
console.log(`${req.path}${Object.keys(req.query).length ? "?" : ""}${qs.stringify(req.query)}`);
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();
} 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$/, "");
pathMatches.push(createPathMatch(`/${route}`));
const routeObj = require(`./routes/${route}`);
if (routeObj.route) {
routeObj.route(app.route(`/${route}`));
}
}
const server = app.listen(process.env.PORT || 3000, () => {
process.on("SIGINT", () => {
databaseHandler.db.close();
server.close();
});
});
})();