Initial commit
This commit is contained in:
39
src/server/commands/commands.ts
Normal file
39
src/server/commands/commands.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { ServerContentBase } from "../ContentBase.ts";
|
||||
import type Command from "./command.ts";
|
||||
|
||||
export class CommandsBase extends ServerContentBase {
|
||||
|
||||
#cmds: Set<Command> = new Set();
|
||||
|
||||
addRootCommand(cmd: Command) {
|
||||
this.#cmds.add(cmd);
|
||||
}
|
||||
|
||||
removeRootCommandByKey(key: string) {
|
||||
for (const cmd of this.#cmds) if (cmd.getKey().includes(key))
|
||||
this.#cmds.delete(cmd);
|
||||
}
|
||||
|
||||
removeRootCommand(cmd: Command) {
|
||||
this.#cmds.delete(cmd);
|
||||
}
|
||||
|
||||
async dispatch(...args: string[]): Promise<unknown> {
|
||||
const root = args[0];
|
||||
if (typeof root !== 'string') return new Error("Root command must be of primitive type 'string'");
|
||||
else {
|
||||
const cmd = this.#cmds.values().toArray().find(cmd => cmd.getKey().includes(root));
|
||||
if (cmd) {
|
||||
const val = await cmd.dispatch(...args.slice(1));
|
||||
if (val == null) return "null";
|
||||
else if (typeof val == 'string') return `"${val}"`;
|
||||
else if (typeof val == 'undefined') return "undefined";
|
||||
else if (val instanceof Error) return val;
|
||||
else if (typeof val == 'object') return JSON.stringify(val);
|
||||
else return String(val);
|
||||
}
|
||||
else return new Error(`'${root.trim()}': Command not found (args: "${args.join(' ')}")`);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user