summary refs log tree commit diff
path: root/scripts/util/getRouteDescriptions.js
blob: a79dac962cb27898b9f2587d73ef67b38ebdc853 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
const express = require("express");
const path = require("path");
const { traverseDirectory } = require("lambert-server");
const RouteUtility = require("../../dist/api/util/handlers/route.js");

const methods = ["get", "post", "put", "delete", "patch"];
const routes = new Map();
let currentFile = "";
let currentPath = "";

/*
	For some reason, if a route exports multiple functions, it won't be registered here!
	If someone could fix that I'd really appreciate it, but for now just, don't do that :p
*/

const proxy = (file, method, prefix, path, ...args) => {
	const opts = args.find((x) => x?.prototype?.OPTS_MARKER == true);
	if (!opts)
		return console.error(
			`${file} has route without route() description middleware`,
		);

	console.log(prefix + path + " - " + method);
	opts.file = file.replace("/dist/", "/src/").replace(".js", ".ts");
	routes.set(prefix + path + "|" + method, opts());
};

express.Router = () => {
	return Object.fromEntries(
		methods.map((method) => [
			method,
			proxy.bind(null, currentFile, method, currentPath),
		]),
	);
};

RouteUtility.route = (opts) => {
	const func = function () {
		return opts;
	};
	func.prototype.OPTS_MARKER = true;
	return func;
};

module.exports = function getRouteDescriptions() {
	const root = path.join(__dirname, "..", "..", "dist", "api", "routes", "/");
	traverseDirectory({ dirname: root, recursive: true }, (file) => {
		currentFile = file;

		currentPath = file.replace(root.slice(0, -1), "");
		currentPath = currentPath.split(".").slice(0, -1).join("."); // trancate .js/.ts file extension of path
		currentPath = currentPath.replaceAll("#", ":").replaceAll("\\", "/"); // replace # with : for path parameters and windows paths with slashes
		if (currentPath.endsWith("/index"))
			currentPath = currentPath.slice(0, "/index".length * -1); // delete index from path

		try {
			require(file);
		} catch (e) {
			console.error(e);
		}
	});

	return routes;
};