file-routing-expressjs
Version:
A dependency-free, flexible, system-based file routing for Express.
108 lines • 3.23 kB
JavaScript
import { color } from "./logging";
function methodColor(method) {
switch (method.toLowerCase()) {
case "get":
return "green";
case "post":
return "blue";
case "put":
return "yellow";
case "delete":
return "red";
case "patch":
return "magenta";
default:
return "cyan";
}
}
function pad(str, len) {
return str + " ".repeat(Math.max(0, len - str.length));
}
function flattenRoutes(nodes) {
const result = [];
function walk(node) {
var _a;
if (node.method !== "-") {
result.push(node);
}
if ((_a = node.children) == null ? void 0 : _a.length) {
node.children.forEach(walk);
}
}
nodes.forEach(walk);
return result;
}
function printTree(nodes, indent = "") {
var _a, _b, _c, _d;
for (const node of nodes) {
const isGroup = node.method === "-";
const method = (_a = node.method) == null ? void 0 : _a.toUpperCase();
const methodColored = method ? color(`[${method}]`, methodColor(method)) : "";
const label = isGroup ? color(node.endpoint, "bold") : `${methodColored} ${node.endpoint}`;
console.log(`${indent}${label}`);
if (!isGroup) {
if ((_b = node.middlewares) == null ? void 0 : _b.length) {
console.log(
`${indent} ${color("\u251C\u2500", "gray")} ${color("middlewares:", "cyan")} ${node.middlewares.join(", ")}`
);
}
if ((_c = node.plugins) == null ? void 0 : _c.length) {
console.log(
`${indent} ${color("\u251C\u2500", "gray")} ${color("plugins:", "magenta")} ${node.plugins.join(", ")}`
);
}
if (node.errorHandler && node.errorHandler !== "-") {
console.log(
`${indent} ${color("\u2514\u2500", "gray")} ${color("error:", "red")} ${node.errorHandler}`
);
}
}
if ((_d = node.children) == null ? void 0 : _d.length) {
printTree(node.children, indent + " ");
}
}
}
function printTable(endpoints) {
const headers = ["Method", "URI", "Name", "Middleware", "Plugins", "Error"];
const widths = headers.map((h) => h.length);
const rows = flattenRoutes(endpoints);
for (const row of rows) {
const values = [
row.method,
row.endpoint,
row.name,
row.middlewares.join(", ") || "-",
row.plugins.join(", ") || "-",
row.errorHandler
];
values.forEach((v, i) => {
widths[i] = Math.max(widths[i], String(v).length);
});
}
const line = (char) => "+" + widths.map((w) => char.repeat(w + 2)).join("+") + "+";
const printRow = (cols, colorize = false) => {
const row = cols.map((c, i) => pad(c, widths[i])).join(" | ");
const content = `| ${row} |`;
return colorize ? color(content, "green") : content;
};
console.log(color(line("-"), "green"));
console.log(printRow(headers, true));
console.log(color(line("-"), "green"));
for (const row of rows) {
console.log(printRow([
row.method,
row.endpoint,
row.name,
row.middlewares.join(", ") || "-",
row.plugins.join(", ") || "-",
row.errorHandler
], true));
}
console.log(color(line("-"), "green"));
}
export {
flattenRoutes,
printTable,
printTree
};
//# sourceMappingURL=cli.mjs.map