API

nest-commander

Commander Decorators

@Command()

This class decorator is pretty much what everything else in this package relies on existing. This is the decorator that sets up the sub commands for the application that are to be consumed.

PropertyTypeRequiredDescription
namestringtrueThe name of the command.
argumentsstringfalseThe arguments that the command takes in. For required arguments, wrap the argument in <>, for optional use [].
descriptionstringfalseThe description of what the command does. This will be printed on the --help usage.
argsDescriptionRecord<string, string>falseThe description for each argument. It will be used on --help as well.
optionsCommandOptionsfalseExtra options to pass to the commander instance. Check commander’s types for more information.
subCommandsType<CommandRunner>falseSubcommands related to the parent command, e.g.:
docker compose up and docker compose stop.
aliasesArray<string>falseAliases for the SubCommand. You can pass this array to a Command but it will have no effect on the parsing of the command.

The above information holds for @SubCommand() as well, though default under options has no effect.

@RootCommand()

Just like @Command() except without the name property, and can only be used once per application.

PropertyTypeRequiredDescription
argumentsstringfalseThe arguments that the command takes in. For required arguments, wrap the argument in <>, for optional use [].
descriptionstringfalseThe description of what the command does. This will be printed on the --help usage.
argsDescriptionRecord<string, string>falseThe description for each argument. It will be used on --help as well.
optionsCommandOptionsfalseExtra options to pass to the commander instance. Check commander’s types for more information.
subCommandsType<CommandRunner>falseSubcommands related to the parent command, e.g.:
docker compose up and docker compose stop.
aliasesArray<string>falseAliases for the SubCommand. You can pass this array to a Command but it will have no effect on the parsing of the command.

@Option()

This method decorator allows for users to pass in extra options for commands defined with @Command(). These options allow for the program to act in slightly different, yet predictable ways.

PropertyTypeRequiredDescription
flagsstringtrueThe flags that should work for this option. Multiple flags can exist for a single option, so long as they are separated by a comma, space, or pipe character. Just like with arguments, <> for required, [] for optional.
descriptionstringfalseThe description of the flags and option. Used with the --help output.
defaultValuestring or booleanfalseThe default value, if any, for the option.
requiredbooleanfalseMake the option required like an argument and the command fail if the option is not provided.
namestringfalseThe name of the option for the CommandRunnerService (internal) to use when pairing against a @OptionChoicesFor() decorator. This has no effect on the help text rendered by commander.
choicesArray<string> OR truefalseThe choices for the option. If true, then the CommandRunnerService knows to go and find the @OptionChoicesFor() decorator that matches the name property. If an array, the options are used directly without searching to another method.

@OptionChoicesFor()

This method decorator allows you to get chocies for an @Option() in a dynamic manner rather than hard coding them into the @Option() decorator. The method this decorator decorates should return a string array of options.

PropertyTypeRequriedDescription
namestringtrueThe name to match back to the @Option() decorator. This is how the two decorators are tied together.

@Help()

This method decorator allows you to add custom help text for your command in a specified position with respect to the original help text

Help(position: 'before' | 'beforeAll' | 'after' | 'afterAll'): MethodDecorator

InquirerService

ask<T>

An asynchronous command to allow for getting user input based on existing options from commander and the name of a question set.

ask<T>(name: string, options: Partial<T> | undefined): Promise<T>
// The following is just an alias for the above
prompt<T>(name: string, options: Partial<T> | undefined): Promise<T>
ParameterTypeRequiredDescription
namestringtrueThe name of the question set to ask for. This is defined in @QuestionSet()
optionsT or undefinedtrueThe pre-existing options that come from commander, or defined by the developer. The type here will determine the return type, unless undefined, then it is any unless passed in the generic. Values that are passed in will not be asked for again.

Inquirer Decorators

@QuestionSet()

This class decorator allows for the setup of a set of questions to ask.

PropertyTypeRequiredDescription
namestringtrueThe name of the question set, to be later called by the InquirerService.

@Question()

This method decorator allows for creating questions to ask the user. For information on each specific kind of question, Inquirer’s docs should be consulted.

PropertyTypeRequiredDescription
type"input", "number", "confirm", "list", "rawlist", "expand", "checkbox", "password", or "editor"falseThe kind of question for inquirer to ask. Each question has slightly different options, so pay attention to the type. Defaults to "input".
namestringtrueThe name of the question’s input. This is used when being passed back from the InquirerService and can be used with the @*For() decorators described below.
messagestringtrue*The question to ask.
defaultstring, number, boolean, arrayfalseThe default value for the question’s input.
choicesarraytrueThe choices to be defined for a list, rawlist, checkbox, and expand question. The array can be of strings, or numbers, or objects containing a name, value, and short property.
validateFunctionfalseA validation function that ensures the input is correct. On failed validation the question is re-asked.
transformFunctionfalseA transform method that takes the user’s input and transforms it before printing it back to the terminal. This does not have an impact on the incoming value itself.
whenFunction or booleanfalseA function or boolean to determine if a question should be asked or not.
pageSizenumberfalseThe number of lines to render for list, rawlist, checkbox, and expand question.
prefixstringfalseChanges the prefix message.
suffixstringfalseChanges the suffix message.
askAnsweredbooleanfalseForce the prompt even if the question has been answered. Defaults to false.
loopbooleanfalseEnable loop listing. Defaults to true.

When you use the @*For() decorator factories, the equivalent option on @Question() (eg: message) will not be used.

* The property itself is not required, but there must be a value for this, whether through dynamic decorator or the @Question() decorator.

@ValidateFor()

This method decorator allows a user to define a dynamic value for inquirer’s validate option for the named question. The method this decorator decorates takes in the user input and answer hashes and returns a boolean.

PropertyTypeRequiredDescription
namestringtrueThe name of the question this decorator effects.

@TransformFor()

This method decorator allows a user to define a dynamic value for inquirer’s transform option for the named question. The method this decorator decorates takes in the user input, answer hashes, and option flags and returns the input after transformation. This transformation does not impact what is returned by Inquirer, only what is shown back to the user.

PropertyTypeRequiredDescription
namestringtrueThe name of the question this decorator effects.

@WhenFor()

This method decorator allows a user to define a dynamic value for inquirer’s when option for the named question. The method this decorator decorates takes in the answer hashes and returns a boolean for if the question should be shown or not.

PropertyTypeRequiredDescription
namestringtrueThe name of the question this decorator effects.

@MessageFor()

This method decorator allows a user to define a dynamic value for inquirer’s message option for the named question. The method this decorator decorates takes in the current set of answers and returns a string.

PropertyTypeRequiredDescription
namestringtrueThe name of the question this decorator effects.

@ChoicesFor()

This method decorator allows a user to define a dynamic value for inquirer’s choices option for the named question. The method this decorator decorates takes in the current answer hashes and returns an array of choices. These choices can be an array of string, number, or objects containing a name, value, and short. The choices array can also contain a separator which can be read about in Inquirer’s docs.

PropertyTypeRequiredDescription
namestringtrueThe name of the question this decorator effects.

@DefaultFor()

This method decorator allows a user to define a dynamic value for inquirer’s default option for the named question. The method this decorator decorates takes in the current hash of answers and returns a number, string, or boolean.

PropertyTypeRequiredDescription
namestringtrueThe name of the question this decorator effects.

Most of the decorators for the @QuestionSet() decorated class are just dynamic setters for inquirer’s options. Their docs will go more in depth about what each one does.

CliUtilityService

The CliUtilityService is available from nest-commander@2.4.0 and on

parseBoolean

A helper method to turn a string into a boolean based on true or false values.

PropertyTypeRequiredDescription
valstringtrueThe string value to be turned into a boolean

parseInt

A Simple wrapper around Number.parseInt()

PropertyTypeRequiredDescription
valstringtrueThe string value to be turned into an integer
radixnumberfalseThe radix to use for praseInt. Defaults to 10

parseFloat

A simple wrapper around Number.parseFloat()

PropertyTypeRequiredDescription
valstringtrueThe string value to be turned into a float

CommandFactory

run

A static method that kicks off the command and manages the Nest application lifecycle.

CommandFactory.run(rootModule: Type<any>, optionsOrLogger?: CommandFactoryRunOptions | NestLogger): Promise<void>
ParameterTypeRequiredDescription
rootModuleType<any>trueThe module, or module metadata, required to run the command. This is the same module metadata passed to NestFactory.create.
optionsOrLoggerCommandFactoryRunOptions or NestLoggerfalseOptions or a Nest logger instance for the CommandFactory to pass on to NestLogger. See below for more information.

runWithoutClosing

The same static method as above, but without handling the closing of the Nest application when the command finishes. This is to allow the setup of things like file watchers or pollers.

CommandFactoryRunOptions

Options that can be passed to the run or runWithoutClosing method to modify the behavior.

PropertyTypeRequiredDescription
loggerNestLoggerfalseA logger instance to use with the CommandFactory. Defaults to false to turn off the initialization logs.
errorHandlerFunctionfalseA custom error handler that takes in an Error and returns void synchronously.
usePluginsbooleanfalseThe choice of if the built CLI should look for a config file and plugins or not.
cliNamestringfalseThe name of the CLI and the prefix for the config file to be looked for. Defaults to "nest-commander".
enablePositionalOptionsbooleanfalseMake commander view <comamnd> -p <sub-command> and <command <sub-command> -p as two different commands. Commander’s reference
serviceErrorHandlerFunctionfalseA custom error handler that takes in an Error and return void. This is to handle errors at the Nest service level rather than the command level like errorHandler
versionstringfalseThe global version of the CLI. If this option is set, the -V or —version option will be enabled.

CommandRunner

The CommandRunner is abstract class to define your command. You define the command in the class inherits it.

registerWithSubCommands

A static method that returns a list of the root command class, which calls this api, and all sub command classes set via the metadata of the @Command() and @SubCommand() decorators in the scope of module tree that the root command class traverses.

@Module({
  providers: [...RunCommand.registerWithSubCommands()]
})
export class AppModule {}
ParameterTypeRequiredDescription
metastringfalse@Command or @SubCommand decorator identifier is explicitly specified for extracting metadata,
It is used internal this library and you shouldn’t need to specify it normally.

@RequestModule()

A wrapper decorator for Nest’s @Module() that exposes a way to set a request object mock for the REQUEST injection token.

@RequestModule({
  providers: [SomeCommand],
  requestObject: { headers: { Authorization: 'Bearer token' } }
})
export class SomeCommandModule {}
ParameterTypeRequiredDescription
importsArrayfalseImports for the current module. This is Nest’s standard property
controllersType[]falseControllers for the module
providersProvider[]falseProviders for the module. This includes commands
exportsArrayfalseValues the module exports
requestObjectObjectfalseThe mock request object that should be used in place of REQUEST

nest-commander-testing

CommandTestFactory

createTestingCommand

Similar to @nestjs/testing’s createTestingModule, this static method sets up a TestingModuleBuilder that can be used with Nest’s overrideProvider and compile methods for creating a TestingModule.

CommandFactory.createTestingCommand(moduleMetadata: CommandModuleMetadata): TestingModuleBuilder
ParameterTypeRequiredDescription
moduleMetadataCommandModuleMetadatatrueNest’s module metadata which requires imports to be populated. This will get passed down to createTestingModule to create the proper testing metadata.

run

Similar to CommandFactory.run but to be used within a test instance.

CommandTestFactory.run(app: TestingModule, args?: string[]): Promise<void>
ParameterTypeRequiredDescription
appTestingModuletrueThe testing application that is to be used for the CommandFactory. This should be set up in your beforeAll() or right before calling the run method.
argsArray<string>falseThe name of the command to run, if not the default, and the options that would normally be passed, each as a separate array entry.

setAnswers

A command to mock the gathering of information from a user, to help with automated testing.

CommandFactory.setAnswers(value: any | any[]): void
ParameterTypeRequiredDescription
valueArray<any> or anytrueThe answers that are to be returned from the user’s input gathers in InquirerService#ask. These should be the post-parsed values.

useDefaultInquirer

A method to sub back in the regular Inquirer instance instead of the mock used for testing. If this is used, the setAnswers will have no effect, and stdin data must be passed manually

CommandFactory.useDefaultInquirer(): typeof CommandTestFactory