Skip to content

Commit

Permalink
Errors now don't exit the code
Browse files Browse the repository at this point in the history
Removed internal node for a later integration, updated main nodes so
that errors now are logged into logs/cerebrum.log
  • Loading branch information
auth-xyz committed Oct 11, 2024
1 parent 86ba091 commit 5e321b0
Show file tree
Hide file tree
Showing 8 changed files with 94 additions and 119 deletions.
31 changes: 19 additions & 12 deletions libs/config_node.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import fs from 'fs/promises';
import path from 'path';

import { watch } from "chokidar";
import { EventEmitter } from 'events';

Expand All @@ -17,17 +16,25 @@ export async function watchNodes() {
watcher.on('addDir', async (dir) => {
const configPath = path.join(dir, 'node_config.json');

if (await exists(configPath)) {
try {
const config = await readNodeConfig(configPath);

if (validateConfig(config)) {
logger.info(`Processing node: ${config.name}`);
nodeEmitter.emit('nodeAdded', { config, dir });
try {
if (await exists(configPath)) {
try {
const config = await readNodeConfig(configPath);

if (validateConfig(config)) {
logger.info(`Processing node: ${config.name}`);
nodeEmitter.emit('nodeAdded', { config, dir });
} else {
logger.warn(`Invalid configuration in ${configPath}`);
}
} catch (err) {
logger.error(`Error reading or validating config from ${configPath}: ${err.message}`);
}
} catch (err) {
logger.error(`Error processing folder: ${err.message}`);
} else {
logger.warn(`Config file not found in ${dir}`);
}
} catch (err) {
logger.error(`Error checking existence of ${configPath}: ${err.message}`);
}
});

Expand All @@ -37,8 +44,8 @@ export async function watchNodes() {
});

watcher.on('error', (err) => {
logger.error(`Watcher error: ${err}`);
reject(`watcher error: ${err}`);
logger.error(`Watcher error: ${err.message}`);
reject(`watcher error: ${err.message}`);
});
});
};
Expand Down
105 changes: 66 additions & 39 deletions libs/loader_node.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Collection, Routes } from 'discord.js';
import { watch } from 'chokidar';
import { rest } from './utils.js';
import { logger } from './logger_node.js'; // Importing the logger
import { logger } from './logger_node.js';

import fs from 'fs';
import path from 'path';
Expand All @@ -12,11 +12,18 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));
export async function loadFunctions(client, sortedData) {
const { node_commands, node_events, node_type, node_guildid } = sortedData;
const nodesDir = path.join(__dirname, '../nodes');
const nodeDirs = fs.readdirSync(nodesDir).filter(dir => {
const dirPath = path.join(nodesDir, dir);
return fs.statSync(dirPath).isDirectory() &&
fs.existsSync(path.join(dirPath, 'node_config.json'));
});

let nodeDirs;
try {
nodeDirs = fs.readdirSync(nodesDir).filter(dir => {
const dirPath = path.join(nodesDir, dir);
return fs.statSync(dirPath).isDirectory() &&
fs.existsSync(path.join(dirPath, 'node_config.json'));
});
} catch (error) {
logger.error(`Error reading node directories: ${error.message}`);
return;
}

if (node_commands.length > 0) {
for (const nodeDir of nodeDirs) {
Expand Down Expand Up @@ -70,44 +77,56 @@ async function reloadComponents(client, components, type, nodeType, nodeGuildId,
}

async function handleComponent(client, component, type, nodeType, nodeGuildId) {
if (type === 'command') {
client.commands.set(component.data.name, component);
await registerCommand(client, component.data, nodeType, nodeGuildId);
} else {
const eventName = component.data.name;
const execute = (...args) => component.execute(...args);
component.once ? client.once(eventName, execute) : client.on(eventName, execute);
try {
if (type === 'command') {
client.commands.set(component.data.name, component);
await registerCommand(client, component.data, nodeType, nodeGuildId);
} else {
const eventName = component.data.name;
const execute = (...args) => component.execute(...args);
component.once ? client.once(eventName, execute) : client.on(eventName, execute);
}
} catch (error) {
logger.error(`Error handling component: ${error.message}`);
}
}

async function registerCommand(client, commandData, nodeType, nodeGuildId) {
const registerGlobalCommand = async () => {
await rest.put(Routes.applicationCommands(process.env.CLIENT_ID));
logger.info(`Registered global command: ${commandData.name}`);
try {
await rest.put(Routes.applicationCommands(process.env.CLIENT_ID));
logger.info(`Registered global command: ${commandData.name}`);
} catch (error) {
logger.error(`Error registering global command: ${error.message}`);
}
};

switch (nodeType) {
case 'hybrid':
if (nodeGuildId) {
await rest.put(Routes.applicationGuildCommands(process.env.CLIENT_ID, nodeGuildId), { body: [commandData] });
logger.info(`Registered server-specific command: ${commandData.name}`);
}
await registerGlobalCommand();
break;

case 'server':
if (nodeGuildId) {
await rest.put(Routes.applicationGuildCommands(process.env.CLIENT_ID, nodeGuildId), { body: [commandData] });
logger.info(`Registered server-specific command: ${commandData.name}`);
}
break;

case 'internal':
await registerGlobalCommand();
break;

default:
logger.warn(`Unknown node type for command registration: ${nodeType}`);
try {
switch (nodeType) {
case 'hybrid':
if (nodeGuildId) {
await rest.put(Routes.applicationGuildCommands(process.env.CLIENT_ID, nodeGuildId), { body: [commandData] });
logger.info(`Registered server-specific command: ${commandData.name}`);
}
await registerGlobalCommand();
break;

case 'server':
if (nodeGuildId) {
await rest.put(Routes.applicationGuildCommands(process.env.CLIENT_ID, nodeGuildId), { body: [commandData] });
logger.info(`Registered server-specific command: ${commandData.name}`);
}
break;

case 'internal':
await registerGlobalCommand();
break;

default:
logger.warn(`Unknown node type for command registration: ${nodeType}`);
}
} catch (error) {
logger.error(`Error registering command: ${error.message}`);
}
}

Expand All @@ -118,15 +137,23 @@ export function watchForChanges(client, sortedData) {
logger.info(`Watching commands: ${commands}`);
watch(commands).on('change', async (filePath) => {
logger.info(`Command changed: ${filePath}`);
await reloadComponents(client, commands, 'command');
try {
await reloadComponents(client, commands, 'command');
} catch (error) {
logger.error(`Error reloading command after change: ${error.message}`);
}
});
}

if (events) {
logger.info(`Watching events: ${events}`);
watch(events).on('change', async (filePath) => {
logger.info(`Event changed: ${filePath}`);
await reloadComponents(client, events, 'event');
try {
await reloadComponents(client, events, 'event');
} catch (error) {
logger.error(`Error reloading event after change: ${error.message}`);
}
});
}

Expand Down
9 changes: 6 additions & 3 deletions libs/sorter_node.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,17 @@ export async function sortConfigNodeData(nodeDir) {
const configDir = subDirs.find(dir => dir.isDirectory());

if (!configDir) {
throw new Error('No subdirectory found inside nodes folder');
logger.error('No subdirectory found inside nodes folder');
return null;
}

const configPath = path.join(nodeDir, configDir.name, 'node_config.json');

try {
await fs.access(configPath);
} catch (err) {
throw new Error(`Config file not found in ${configDir.name}`);
logger.error(`Config file not found in ${configDir.name}`);
return null;
}

const configData = await readNodeConfig(configPath);
Expand All @@ -37,7 +39,8 @@ export async function sortConfigNodeData(nodeDir) {
node_commands: node_commands || []
};
} else {
throw new Error('Invalid config data');
logger.error('Invalid config data');
return null;
}
} catch (error) {
logger.error(`Error getting sorted data in controller node: ${error.message}`);
Expand Down
27 changes: 0 additions & 27 deletions nodes/internal/events/interactionCreate.js

This file was deleted.

10 changes: 0 additions & 10 deletions nodes/internal/events/messageCreate.js

This file was deleted.

9 changes: 0 additions & 9 deletions nodes/internal/events/ready.js

This file was deleted.

16 changes: 0 additions & 16 deletions nodes/internal/node_config.json

This file was deleted.

6 changes: 3 additions & 3 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,14 @@ const client = new Client({

if (typeof nodeData === "undefined" || !nodeData) {
console.error('Error loading node data or nodeData is undefined, exiting...');
return process.exit(1);
//return process.exit(1);
}

const sortedData = await sortConfigNodeData(nodeDir);

if (!sortedData) {
console.error('Error fetching sorted data, exiting...');
return process.exit(1);
console.error('Error fetching sorted data');
// return process.exit(1);
}

await client.login(process.env.DISCORD_TOKEN);
Expand Down

0 comments on commit 5e321b0

Please sign in to comment.