自行准备并运行命令
应用可以在打开数据库连接或创建 API 客户端之前验证参数并选择命令。本例由应用运行处理函数、格式化结果并处理错误。如需由 TerminalApp 管理输出和诊断,请参阅终端应用示例。
定义命令
在应用代码旁定义命令和注册表。prepare 处理函数验证或规范化输入。本例去除名称首尾的空白,再通过 payload 将名称交给 handle。问候语由应用通过 context 提供。
TypeScript
import { createCommand, type PreparedCommand } from 'icore';
type GreetingContext = {
greeting: string;
};
const command = createCommand();
const greetCommand = command.define({
path: ['greet'],
options: {
name: {
type: 'string',
required: true
}
} as const,
prepare({ options }) {
return {
normalizedName: options.name.trim()
};
},
handle({ payload, context }: {
payload: { normalizedName: string };
context: GreetingContext;
}) {
return `${context.greeting}, ${payload.normalizedName}!\n`;
}
});
const commands = command.registry([
greetCommand
] as const);
运行已准备的命令
调用 commands.prepare(...) 验证参数,再将已准备的命令和应用数据传给 commands.run(...)。在准备成功后创建资源,以便输入无效时省去这一步。
TypeScript
async function runTwoPhase(args: readonly string[]): Promise<string> {
const prepared: PreparedCommand<typeof greetCommand> = await commands.prepare(args, {
strict: true
});
return commands.run(prepared, {
greeting: 'Hello'
});
}
一次调用完成执行
数据已经就绪时,commands.runFromArgs(...) 一次完成解析、准备和命令执行。
TypeScript
async function runFromArgs(args: readonly string[]): Promise<string> {
return commands.runFromArgs(args, {
greeting: 'Hello'
}, {
strict: true
});
}
向两种调用方式传入相同的参数,就像从终端输入一样。
TypeScript
const args = [
'greet',
'--name',
'Alice'
];
process.stdout.write(await runTwoPhase(args));
process.stdout.write(await runFromArgs(args));
每次调用写入一行。
代码
Hello, Alice!
Hello, Alice!