Skip to content

Commit a375b51

Browse files
committed
refactor: improve server startup logic and enhance error handling; update command loader to prevent cache issues
1 parent 443e0ce commit a375b51

2 files changed

Lines changed: 35 additions & 10 deletions

File tree

src/components/server.ts

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,33 @@
11
import http from "http";
22
import log from "./utils/log";
33

4-
const port = process.env.PORT || 3000;
4+
const DEFAULT_PORT = process.env.PORT ? Number(process.env.PORT) : 3000;
5+
const MAX_PORT_TRIES = 10;
56

6-
const server = http.createServer((req, res) => {
7-
res.writeHead(200, { "Content-Type": "text/plain" });
8-
res.end("Bot is running\n");
9-
});
7+
function startServer(port: number, tries = 0) {
8+
const server = http.createServer((req, res) => {
9+
res.writeHead(200, { "Content-Type": "text/plain" });
10+
res.end("Bot is running\n");
11+
});
1012

11-
server.listen(port, () => {
12-
log.info("Server", `HTTP server started on port ${port}`);
13-
});
13+
server.listen(port, () => {
14+
log.info("Server", `HTTP server started on port ${port}`);
15+
});
16+
17+
server.on("error", (err: any) => {
18+
if (err.code === "EADDRINUSE" && tries < MAX_PORT_TRIES) {
19+
log.warn("Server", `Port ${port} in use, trying port ${port + 1}`);
20+
startServer(port + 1, tries + 1);
21+
} else {
22+
log.error("Server", `Failed to start server: ${err.message}`);
23+
process.exit(1);
24+
}
25+
});
26+
27+
return server;
28+
}
29+
30+
const port = Number(process.env.PORT) || DEFAULT_PORT;
31+
const server = startServer(port);
1432

1533
export default server;

src/components/utils/loader.ts

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,17 @@ const commandsPath = path.join(__dirname, "..", "..", "commands");
88
export default function (file: string, customPath?: string) {
99
if (/\.js$|\.ts$/.test(file)) {
1010
const filePath = path.join(customPath || commandsPath, file);
11-
delete require.cache[require.resolve(filePath)];
11+
12+
if (require.cache[require.resolve(filePath)])
13+
delete require.cache[require.resolve(filePath)];
14+
1215
const commandModule = require(filePath);
1316

14-
if (typeof commandModule.default === "function") {
17+
if (
18+
typeof commandModule.default === "function" &&
19+
commandModule.info &&
20+
commandModule.info.command
21+
) {
1522
commands[commandModule.info.command] = {
1623
command: commandModule.info.command,
1724
description: commandModule.info.description || "No description",

0 commit comments

Comments
 (0)