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 configgator register - adds a new user to the databasegator users - lists all the users in the databaseWe'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.
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.
Record utility type to create a map of command names to handler functions.