2021-09-21 22:52:30 +02:00
|
|
|
const { traverseDirectory } = require("lambert-server");
|
|
|
|
const path = require("path");
|
|
|
|
const express = require("express");
|
|
|
|
const RouteUtility = require("../dist/util/route");
|
2021-09-18 01:50:29 +02:00
|
|
|
const Router = express.Router;
|
|
|
|
|
2021-09-21 22:52:30 +02:00
|
|
|
/**
|
|
|
|
* Some documentation.
|
|
|
|
*
|
|
|
|
* @type {Map<string, RouteUtility.RouteOptions>}
|
|
|
|
*/
|
|
|
|
const routes = new Map();
|
2021-09-18 01:50:29 +02:00
|
|
|
let currentPath = "";
|
|
|
|
let currentFile = "";
|
|
|
|
const methods = ["get", "post", "put", "delete", "patch"];
|
|
|
|
|
|
|
|
function registerPath(file, method, prefix, path, ...args) {
|
|
|
|
const urlPath = prefix + path;
|
|
|
|
const sourceFile = file.replace("/dist/", "/src/").replace(".js", ".ts");
|
2021-09-21 22:52:30 +02:00
|
|
|
const opts = args.find((x) => typeof x === "object");
|
2021-09-18 01:50:29 +02:00
|
|
|
if (opts) {
|
2021-09-18 11:56:06 +02:00
|
|
|
routes.set(urlPath + "|" + method, opts); // @ts-ignore
|
|
|
|
opts.file = sourceFile;
|
2021-09-18 01:50:29 +02:00
|
|
|
// console.log(method, urlPath, opts);
|
|
|
|
} else {
|
2021-09-21 22:52:30 +02:00
|
|
|
console.log(`${sourceFile}\nrouter.${method}("${path}") is missing the "route()" description middleware\n`);
|
2021-09-18 01:50:29 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function routeOptions(opts) {
|
|
|
|
return opts;
|
|
|
|
}
|
|
|
|
|
|
|
|
// @ts-ignore
|
|
|
|
RouteUtility.route = routeOptions;
|
|
|
|
|
|
|
|
express.Router = (opts) => {
|
|
|
|
const path = currentPath;
|
|
|
|
const file = currentFile;
|
|
|
|
const router = Router(opts);
|
|
|
|
|
|
|
|
for (const method of methods) {
|
|
|
|
router[method] = registerPath.bind(null, file, method, path);
|
|
|
|
}
|
|
|
|
|
|
|
|
return router;
|
|
|
|
};
|
|
|
|
|
2021-09-21 22:52:30 +02:00
|
|
|
module.exports = function getRouteDescriptions() {
|
2021-09-18 01:50:29 +02:00
|
|
|
const root = path.join(__dirname, "..", "dist", "routes", "/");
|
|
|
|
traverseDirectory({ dirname: root, recursive: true }, (file) => {
|
|
|
|
currentFile = file;
|
|
|
|
let path = file.replace(root.slice(0, -1), "");
|
|
|
|
path = path.split(".").slice(0, -1).join("."); // trancate .js/.ts file extension of path
|
|
|
|
path = path.replaceAll("#", ":").replaceAll("\\", "/"); // replace # with : for path parameters and windows paths with slashes
|
|
|
|
if (path.endsWith("/index")) path = path.slice(0, "/index".length * -1); // delete index from path
|
|
|
|
currentPath = path;
|
|
|
|
|
2021-09-21 22:52:30 +02:00
|
|
|
try {
|
|
|
|
require(file);
|
|
|
|
} catch (error) {
|
|
|
|
console.error("error loading file " + file, error);
|
|
|
|
}
|
2021-09-18 01:50:29 +02:00
|
|
|
});
|
|
|
|
return routes;
|
2021-09-21 22:52:30 +02:00
|
|
|
};
|