dynamically import routes

This commit is contained in:
Arthur Lu 2023-08-07 18:48:47 +00:00
parent 0232b2208e
commit 212d9721f8
3 changed files with 30 additions and 34 deletions

View File

@ -33,29 +33,7 @@ global.server = app.listen(global.db.listenPort, () => {
console.log(`proxmoxaas-api v${global.api.version} listening on port ${global.db.listenPort}`);
});
import("./routes/auth.js").then((module) => {
app.use("/api/auth", module.router);
});
import("./routes/cluster.js").then((module) => {
app.use("/api/cluster", module.router);
});
import("./routes/global.js").then((module) => {
app.use("/api/global", module.router);
});
import("./routes/proxmox.js").then((module) => {
app.use("/api/proxmox", module.router);
});
import("./routes/sync.js").then((module) => {
app.use("/api/sync", module.router);
});
import("./routes/user.js").then((module) => {
app.use("/api/user", module.router);
});
global.utils.recursiveImport(app, "/api", "routes");
/**
* GET - get API version

View File

@ -16,17 +16,7 @@ const vmidRegexP = "\\d+";
const basePath = `/:node(${nodeRegexP})/:type(${typeRegexP})/:vmid(${vmidRegexP})`;
import("./cluster/disk.js").then((module) => {
router.use(`${basePath}/disk`, module.router);
});
import("./cluster/net.js").then((module) => {
router.use(`${basePath}/net`, module.router);
});
import("./cluster/pci.js").then((module) => {
router.use(`${basePath}/pci`, module.router);
});
global.utils.recursiveImport(router, basePath, "cluster", import.meta.url);
/**
* GET - get available pcie devices given node and user

View File

@ -1,4 +1,7 @@
import { createHash } from "crypto";
import path from 'path';
import url from 'url';
import * as fs from "fs";
import { getUsedResources, requestPVE } from "./pve.js";
@ -116,3 +119,28 @@ export function getObjectHash (object, alg = "sha256", format = "hex") {
export function getTimeLeft (timeout) {
return Math.ceil((timeout._idleStart + timeout._idleTimeout - (global.process.uptime() * 1000)));
}
/**
* Recursively import routes from target folder.
* @param {Object} router or app object.
* @param {string} baseroute API route for each imported module.
* @param {string} target folder to import modules.
* @param {string} from source folder of calling module, optional for imports from the same base directory.
*/
export function recursiveImport (router, baseroute, target, from = import.meta.url) {
const thisPath = path.dirname(url.fileURLToPath(import.meta.url));
const fromPath = path.relative(".", path.dirname(url.fileURLToPath(from)));
const targetPath = path.relative(".", `${fromPath}/${target}`);
const importPath = path.relative(thisPath, targetPath);
const files = fs.readdirSync(targetPath);
files.forEach((file) => {
if (file.endsWith(".js")) {
const path = `./${importPath}/${file}`;
const route = `${baseroute}/${file.replace(".js", "")}`
import(path).then((module) => {
router.use(route, module.router);
});
console.log(`routes: loaded ${path} as ${route}`);
}
});
}