Skip to content

Commit

Permalink
server/client: refactor command input
Browse files Browse the repository at this point in the history
Keep happy path on the left and try to return as early
as we can to help the reader understand the logic better

The function is too large to be able to quickly scan an if / else
chain and see the function return at the end
  • Loading branch information
brunnre8 committed Mar 17, 2023
1 parent 4023323 commit 4e954b9
Showing 1 changed file with 39 additions and 31 deletions.
70 changes: 39 additions & 31 deletions server/client.ts
Expand Up @@ -465,46 +465,54 @@ class Client {
const cmd = args?.shift()?.toLowerCase() || "";

const irc = target.network.irc;
let connected = irc && irc.connection && irc.connection.connected;
const connected = irc?.connected;

if (inputs.userInputs.has(cmd)) {
const plugin = inputs.userInputs.get(cmd);

if (!plugin) {
// should be a no-op
throw new Error(`Plugin ${cmd} not found`);
}

if (typeof plugin.input === "function" && (connected || plugin.allowDisconnected)) {
connected = true;
plugin.input.apply(client, [target.network, target.chan, cmd, args]);
}
} else if (inputs.pluginCommands.has(cmd)) {
const plugin = inputs.pluginCommands.get(cmd);

if (typeof plugin.input === "function" && (connected || plugin.allowDisconnected)) {
connected = true;
plugin.input(
new PublicClient(client, plugin.packageInfo),
{network: target.network, chan: target.chan},
cmd,
args
);
}
} else if (connected) {
// TODO: fix
irc!.raw(text);
}

if (!connected) {
const emitFailureDisconnected = () => {
target.chan.pushMessage(
this,
new Msg({
type: MessageType.ERROR,
text: "You are not connected to the IRC network, unable to send your command.",
})
);
};

const plugin = inputs.userInputs.get(cmd);

if (plugin) {
if (!connected && !plugin.allowDisconnected) {
emitFailureDisconnected();
return;
}

plugin.input.apply(client, [target.network, target.chan, cmd, args]);
return;
}

const extPlugin = inputs.pluginCommands.get(cmd);

if (extPlugin) {
if (!connected && !extPlugin.allowDisconnected) {
emitFailureDisconnected();
return;
}

extPlugin.input(
new PublicClient(client, extPlugin.packageInfo),
{network: target.network, chan: target.chan},
cmd,
args
);
return;
}

if (!connected) {
emitFailureDisconnected();
return;
}

// TODO: fix
irc!.raw(text);
}

compileCustomHighlights() {
Expand Down

0 comments on commit 4e954b9

Please sign in to comment.