Prepare and run commands yourself
An application can validate arguments and select a command before opening a database connection or creating an API client. In this example the application runs the handler, formats its result, and handles errors. To let TerminalApp handle output and diagnostics, see the terminal application example.
Define the command
Define the command and registry next to the application code. The prepare handler validates or normalizes input. Here it trims the name and passes it to handle in payload. The application supplies the greeting in context.
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);
Run the prepared command
Call commands.prepare(...) to validate the arguments, then pass the prepared command and application data to commands.run(...). Create resources after preparation succeeds to save that work when input is invalid.
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'
});
}
Run in one call
When the data is already available, commands.runFromArgs(...) parses, prepares, and runs the command in one call.
async function runFromArgs(args: readonly string[]): Promise<string> {
return commands.runFromArgs(args, {
greeting: 'Hello'
}, {
strict: true
});
}
Pass the same arguments to both forms, as if you had typed them in the terminal.
const args = [
'greet',
'--name',
'Alice'
];
process.stdout.write(await runTwoPhase(args));
process.stdout.write(await runFromArgs(args));
Each call writes one line.
Hello, Alice!
Hello, Alice!