We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Commands

Gator is a CLI application, and like many CLI applications, it has a set of valid commands. For example:

  • gator login - sets the current user in the config
  • gator register - adds a new user to the database
  • gator users - lists all the users in the database
  • etc.

We'll be hand-rolling our CLI rather than using a framework like commander.js. This will give us a better understanding of how CLI applications work.

Assignment

Let's start with a simple login command. For now, all it will do is set the current user in the config file. Usage:

npm run start login <username>

We want to add many commands to our CLI, so let's build a flexible system that will allow us to register new commands easily.

type CommandHandler = (cmdName: string, ...args: string[]) => void;

Variadic parameters (...args) are treated as optional in TypeScript, meaning we can omit them later for commands that don't need them.
A function satisfies a type as long as it includes all required parameters and matches the return type.

  • function registerCommand(registry: CommandsRegistry, cmdName: string, handler: CommandHandler) - This function registers a new handler function for a command name.
  • function runCommand(registry: CommandsRegistry, cmdName: string, ...args: string[]) - This function runs a given command with the provided state if it exists.

After slicing the arguments, if there isn't at least one argument, print an error message to the terminal and exit with code 1.

Run and submit the CLI tests from the root of your project.

Tip

  • You can use the Record utility type to create a map of command names to handler functions.