Skip to content

Commit f4e7688

Browse files
committed
feat: replaces require with dynamic import for loading commands
1 parent 9b4f7e9 commit f4e7688

2 files changed

Lines changed: 14 additions & 9 deletions

File tree

src/components/utils/cmd/loader.ts

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,16 @@ import { commands } from "../../../index";
55

66
const commandsPath = path.join(__dirname, "..", "..", "..", "commands");
77

8-
export default function loader(file: string, customPath?: string) {
8+
export default async function loader(file: string, customPath?: string) {
99
if (/\.js$|\.ts$/.test(file)) {
1010
const filePath = path.join(customPath || commandsPath, file);
1111

12-
if (require.cache[require.resolve(filePath)])
13-
delete require.cache[require.resolve(filePath)];
12+
const resolvedPath = path.resolve(filePath);
13+
if (require.cache[resolvedPath]) {
14+
delete require.cache[resolvedPath];
15+
}
1416

15-
const commandModule = require(filePath);
17+
const commandModule = await import(filePath);
1618

1719
if (
1820
typeof commandModule.default === "function" &&
@@ -35,6 +37,9 @@ export default function loader(file: string, customPath?: string) {
3537

3638
export async function mapCommands() {
3739
const files = await fs.readdir(commandsPath);
40+
await Promise.all(files.map((file) => loader(file)));
41+
}
3842

39-
Promise.all(files.map((file) => loader(file)));
40-
}
43+
export function mapCommandsBackground() {
44+
mapCommands().catch(err => log.error("MapCommandLoader", err));
45+
}

src/index.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ dotenv.config();
44
import { Message } from "whatsapp-web.js";
55
import path from "path";
66
import log from "./components/utils/log";
7-
import loader, { mapCommands } from "./components/utils/cmd/loader";
7+
import loader, { mapCommandsBackground } from "./components/utils/cmd/loader";
88
import watcher from "./components/utils/cmd/watcher";
99
import "./components/process";
1010
import server from "./components/server";
@@ -29,7 +29,7 @@ log.info("Bot", `prefix: ${commandPrefix}`);
2929

3030
if (!process.env.DATABASE_URL) {
3131
throw new Error(
32-
"DATABASE_URL is not set in the environment variables.\n This is required for the bot to function properly."
32+
"DATABASE_URL is not set in the environment variables.\n This is required for the bot to function properly.",
3333
);
3434
}
3535

@@ -46,7 +46,7 @@ const commands: Record<
4646
}
4747
> = {};
4848

49-
mapCommands();
49+
mapCommandsBackground();
5050

5151
// Watch for changes
5252
if (autoReload) watcher(commandsPath);

0 commit comments

Comments
 (0)