command-parser/src/classes/CommandOption.ts
2022-07-29 14:16:43 +03:00

95 lines
2.5 KiB
TypeScript

import ICommandOption, { Choice, CommandOptionDefinition, DependsOnMode, OptionType, ParseResult } from "../interfaces/CommandOption";
import IResolver from "../interfaces/Resolver";
class CommandOption implements ICommandOption {
[key: string]: unknown;
name: string;
aliases: string[];
// eslint-disable-next-line no-use-before-define
options: CommandOption[];
type: OptionType;
minimum?: number;
maximum?: number;
flag: boolean;
valueOptional: boolean;
defaultValue: boolean | number | string | null;
valueAsAlias: boolean;
choices: Choice[];
dependsOn: string[];
dependsOnMode: DependsOnMode;
required: boolean;
rawValue?: string[];
value?: unknown;
aliased = false;
private resolver?: IResolver<unknown, unknown, unknown, unknown>|undefined = undefined;
constructor(def: CommandOptionDefinition|ICommandOption) {
this.name = def.name;
this.aliases = def.aliases || [];
this.options = def.options || [];
this.choices = def.choices || [];
this.type = def.type || OptionType.STRING;
this.flag = def.flag || false;
this.valueOptional = def.valueOptional || false;
this.defaultValue = def.defaultValue ?? null;
this.valueAsAlias = def.valueAsAlias || false;
this.dependsOn = def.dependsOn || [];
this.dependsOnMode = def.dependsOnMode || 'AND';
this.required = def.required || false;
}
clone(rawValue?: string[], resolver?: IResolver<unknown, unknown, unknown, unknown>): CommandOption {
const opt = new CommandOption(this);
opt.rawValue = rawValue;
opt.resolver = resolver || undefined;
return opt;
}
async parse(): Promise<ParseResult> {
if(!this[OptionType[this.type]]) throw new Error(`Missing parsing function for ${this.type}`);
const result = await this[OptionType[this.type]];
return result as ParseResult;
}
get plural(): boolean {
return this.type.toString().endsWith('S');
}
protected async MEMBER() {
if (!this.resolver) throw new Error('Missing resolver');
if(!this.rawValue) throw new Error('Missing raw value');
const member = await this.resolver?.resolveMember(this.rawValue[0]);
if (!member) return { error: true };
return { value: member, removed: this.rawValue };
}
}
export { CommandOption };
export default CommandOption;