-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.mjs
70 lines (62 loc) · 2.11 KB
/
index.mjs
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
65
66
67
68
69
70
import express from "express";
import fs from "fs-extra";
import path from "path";
import dotenv from "dotenv";
import { fileURLToPath } from "url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
dotenv.config();
const app = express();
const routesDir = path.join(__dirname, "../routes");
const loadMiddleware = async (dir) => {
const middlewares = [];
const files = await fs.readdir(dir);
for (const file of files) {
if (file.endsWith("middleware.js") || file.endsWith("middleware.ts")) {
const middlewareModule = await import(path.join(dir, file));
if (
typeof middlewareModule.default !== "function" ||
middlewareModule.default.constructor.name !== "AsyncFunction"
) {
throw new Error(`${file} must export a default async function`);
}
middlewares.push(middlewareModule.default);
}
}
return middlewares;
};
const loadRoutes = async (dir) => {
const folders = await fs.readdir(dir);
for (const folder of folders) {
const folderPath = path.join(dir, folder);
if ((await fs.stat(folderPath)).isDirectory()) {
const router = express.Router();
const middlewares = await loadMiddleware(folderPath);
const files = await fs.readdir(folderPath);
for (const file of files) {
const [method] = file.split(".");
if (["get", "post", "put", "patch", "delete"].includes(method)) {
const routeModule = await import(path.join(folderPath, file));
if (
typeof routeModule.default !== "function" ||
routeModule.default.constructor.name !== "AsyncFunction"
) {
throw new Error(`${file} must export a default async function`);
}
router[method]("/", ...middlewares, routeModule.default);
}
}
app.use(`/${folder}`, router);
}
}
};
loadRoutes(routesDir)
.then(() => {
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
})
.catch((err) => {
console.error("Error setting up routes:", err);
});