nest-commander
Version:
A module for making CLI applications with NestJS. Decorators for running commands and separating out config parsers included. This package works on top of commander.
40 lines • 17.6 kB
JSON
{
"name": "nest-commander",
"version": "3.13.0",
"description": "A module for making CLI applications with NestJS. Decorators for running commands and separating out config parsers included. This package works on top of commander.",
"repository": {
"type": "github",
"url": "https://github.com/jmcdo29/nest-commander.git",
"directory": "pacakges/nest-commander"
},
"keywords": [
"cli",
"nestjs",
"application",
"command",
"command-line",
"nest",
"decorator"
],
"author": "Jay McDoniel <jmcdo29@gmail.com>",
"license": "MIT",
"bugs": {
"url": "https://github.com/jmcdo29/nest-commander/issues"
},
"homepage": "https://nest-commander.jaymcdoniel.dev",
"dependencies": {
"@fig/complete-commander": "^3.0.0",
"@golevelup/nestjs-discovery": "4.0.0",
"commander": "11.1.0",
"cosmiconfig": "8.3.6",
"inquirer": "8.2.6"
},
"peerDependencies": {
"@nestjs/common": "^8.0.0 || ^9.0.0 || ^10.0.0",
"@nestjs/core": "^8.0.0 || ^9.0.0 || ^10.0.0",
"@types/inquirer": "^8.1.3"
},
"main": "./src/index.js",
"type": "commonjs",
"readme": "# NestJS Commander\n\nHave you been building amazing REST and RPC applications with [NestJS](https://docs.nestjs.com/)? Do\nyou want that same structure for absolutely everything you're working with? Have you always wanted\nto build up some sweet CLI application but don't really know where to start? This is the solution. A\npackage to bring building CLI applications to the Nest world with the same structure that you\nalready know and love :heart: Built on top of the popular\n[Commander](https://github.com/tj/commander.js) package.\n\n## Installation\n\nBefore you get started, you'll need to install a few packages. First and foremost, this one:\n`nest-commander` (name pending). You'll also need to install `@nestjs/common` and `@nestjs/core` as\nthis package makes use of them under the hood, but doesn't want to tie you down to a specific\nversion, yay peerDependencies!\n\n```sh\nnpm i nest-commander @nestjs/common @nestjs/core\n# OR\nyarn add nest-commander @nestjs/common @nestjs/core\n# OR\npnpm i nest-commander @nestjs/common @nestjs/core\n```\n\n## A Command File\n\n`nest-commander` makes it easy to write new command line applications with\n[decorators](https://www.typescriptlang.org/docs/handbook/decorators.html) via the `@Command()`\ndecorator for classes and the `@Option()` decorator for methods of that class. Every command file\n_should_ implement the `CommandRunner` interface and _should_ be decorated with a `@Command()`\ndecorator.\n\n### CommandRunner\n\nEvery command is seen as an `@Injectable()` by Nest, so your normal Dependency Injection still works\nas you would expect it to (woohoo!). The only thing to take note of is the interface\n`CommandRunner`, which should be implemented by each command. The `CommandRunner` interface ensures\nthat all commands have a `run` method that return a `Promise<void>` and takes in the parameters\n`string[], Record<string, any>`. The `run` command is where you can kick all of your logic off from,\nit will take in whatever parameters did not match option flags and pass them in as an array, just in\ncase you are really meaning to work with multiple parameters. As for the options, the\n`Record<string, any>`, the names of these properties match the `name` property given to the\n`@Option()` decorators, while their value matches the return of the option handler. If you'd like\nbetter type safety, you are welcome to create an interface for your options as well. You can view\nhow the [Basic Command test](test/basic.command.ts) manages that if interested.\n\n### @Command()\n\nThe `@Command()` decorator is to define what CLI command the class is going to manage and take care\nof. The decorator takes in an object to define properties of the command. The options passed here\nwould be the same as the options passed to a new `command` for Commander\n\n| property | type | required | description |\n| --------------- | ---------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------- |\n| name | string | true | the name of the command |\n| arguments | string | false | Named arguments for the command to work with. These can be required `<>` or optional `[]`, but do not map to an option like a flag does |\n| description | string | false | the description of the command. This will be used by the `--help` or `-h` flags to have a formalized way of what to print out |\n| argsDescription | Record<string, string> | false | An object containing the description of each argument. This will be used by `-h` or `--help` |\n| Options | CommandOptions | false | Extra options to pass on down to commander |\n\nFor mor information on the `@Command()` and `@Option()` parameters, check out the\n[Commander docs](https://github.com/tj/commander.js).\n\n### @Option()\n\nOften times you're not just running a single command with a single input, but rather you're running\na command with multiple options and flags. Think of something like `git commit`: you can pass a\n`--amend` flag, a `-m` flag, or even `-a`, all of these change how the command runs. These flags are\nable to be set for each command using the `@Option()` decorator on a method for how that flag should\nbe parsed. Do note that every command sent in via the command line is a raw string, so if you need\nto transform that string to a number or a boolean, or any other type, this handler is where it can\nbe done. See the [putting it all together](#putting-it-all-together) for an example. The `@Option()`\ndecorator, like the `@Command()` one, takes in an object of options defined in the table below\n\n| property | type | required | description |\n| ------------ | ----------------- | -------- | ------------------------------------------------------------------------------------------------------------------- |\n| flags | string | true | a string that represents the option's incoming flag and if the option is required (using <>) or optional (using []) |\n| description | string | false | the description of the option, used if adding a `--help` flag |\n| defaultValue | string or boolean | false | the default value for the flag |\n\nUnder the hood, the method that the`@Option()` is decorating is the custom parser passed to\ncommander for how the value should be parsed. This means if you want to parse a boolean value, the\nbest way to do so would be to use `JSON.parse(val)` as `Boolean('false')` actually returns `true`\ninstead of the expected `false`.\n\n### Inquirer Integration\n\nnest-commander also can integrate with [`inquirer`](https://www.npmjs.com/package/inquirer) to allow\nfor user input during your CLI run. I tried to keep this integration as smooth as possible, but\nthere are some caveats to watch for:\n\n1. Whatever inputs you want to handle via inquirer, must be omitted from commander if you don't want\n them passed in at all, or they must be optional if you want them to be passable from the command\n line. If you use a required option and it is not passed from the command line, commander will\n fail the CLI call.\n2. Inquirer plugins are not yet supported. I do have an idea for this, but they are out of scope for\n the initial integration.\n3. You, as the developer, have options on how to set up the inquirer integration. The details will\n come later, but know that you are given power here. Use it wisely.\n\n### QuestionSet\n\nA class decorated with `@QuestionSet()` is a class that represents a related set of questions.\nLooking at inquirer's own examples, this could be like the\n[pizza example](https://github.com/SBoudrias/Inquirer.js/blob/master/packages/inquirer/examples/pizza.js).\nThere's nothing too special about this decorator, all it does is allow the underlying engine to find\nthe appropriate question set when it is needed. The `@QuestionSet()` decorator takes an object of\noptions defined below\n\n| property | type | required | description |\n| -------- | ------ | -------- | --------------------------------------------------------------------------------- |\n| name | string | true | The name that will be used by the `InquirerService` when getting a prompt to run. |\n\n### Question\n\nHere's where the options start to open up. Each `@Question()` should decorate a class method. This\nmethod will essentially become the `filter` property for `inquirer`. If you don't need any filtering\ndone, simply return the value that comes into the method. All of the other properties come from, and\nadhere to the types of, [`Inquirer`](https://www.npmjs.com/package/inquirer) and their documentation\ncan better illustrate what values are needed when and where.\n\n#### Question Functional Properties\n\nWith Inquirer, several of the properties can have functions instead of simple types. For these\nproperties, you can do one of two things: 1) pass the function to the decorator or 2) use the\n`@*For()`^ decorator. Each `@*For()` decorator takes in an object similar to the `@Question()`\ndecorator as described below\n\n| property | type | required | description |\n| -------- | ------ | -------- | -------------------------------------------------------------------------------------- |\n| name | string | true | The name that will be used to determine which `@Question()` this decorator belongs to. |\n\n##### Passing to the `@Question()` decorator\n\nBelow is an example of using the `validate` method in the `@Question()` decorator\n\n```ts\n@Question({\n type: 'input',\n name: 'phone',\n message: \"What's your phone number?\",\n validate: function(value: string) {\n const pass = value.match(\n /^([01]{1})?[-.\\s]?\\(?(\\d{3})\\)?[-.\\s]?(\\d{3})[-.\\s]?(\\d{4})\\s?((?:#|ext\\.?\\s?|x\\.?\\s?){1}(?:\\d+)?)?$/i,\n );\n if (pass) {\n return true;\n }\n return 'Please enter a valid phone number';\n }\n})\nparsePhone(val: string) {\n return val;\n}\n```\n\n##### Using the `@*For()` decorator\n\nBelow is an example of a `@Question()` and `@ValidateFor()` decorator in use\n\n```ts\n@Question({\n type: 'input',\n name: 'phone',\n message: \"What's your phone number?\",\n})\nparsePhone(val: string) {\n return val;\n}\n\n@ValidateFor({ name: 'phone' })\nvalidatePhone(value: string) {\n const pass = value.match(\n /^([01]{1})?[-.\\s]?\\(?(\\d{3})\\)?[-.\\s]?(\\d{3})[-.\\s]?(\\d{4})\\s?((?:#|ext\\.?\\s?|x\\.?\\s?){1}(?:\\d+)?)?$/i,\n );\n if (pass) {\n return true;\n }\n\n return 'Please enter a valid phone number';\n}\n```\n\nAs you can see, the `name` of both `@Question()` and `@ValidateFor()` align, allowing the underlying\nengine to properly map the `validatePhone` method to the `phone`'s property set.\n\n^ Please note that `@*For()` is shorthand for `@ValidateFor()`, `@ChoicesFor()`, `@MessageFor()`,\n`@DefaultFor()`, and `@WhenFor()`.\n\n### InquirerService\n\nThe `InquirerService` is an injectable provider that allows you to call inquirer for a specific set\nof questions (named with `@QuestionSet()`). When calling the question set, you can pass in the\nalready obtained options as well, and inquirer will skip over the options that are already answered,\nunless the `askAnswered` property is set to `true` as mentioned in their docs. You can use either\n`InquirerService#ask` or `InquirerService#prompt`, as they are aliases for each other. The return\nfrom the `InquirerService#prompt` method is the non-partial variant of the options passed in; in\nother words, the return is the answers that the user provided, mapping appropriately in the cases\nwhere necessary, such as lists. For an example usage, please check the\n[pizza integration test](../../integration/pizza/src/pizza.command.ts).\n\n## Running the Command\n\nSimilar to how in a NestJS application we can use the `NestFactory` to create a server for us, and\nrun it using `listen`, the `nest-commander` package exposes a simple to use API to run your server.\nImport the `CommandFactory` and use the `static` method `run` and pass in the root module of your\napplication. This would probably look like below\n\n```ts\nimport { CommandFactory } from 'nest-commander';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n await CommandFactory.run(AppModule);\n}\n\nbootstrap();\n```\n\nAnd that's it. Under the hood, `CommandFactory` will worry about calling `NestFactory` for you and\ncalling `app.close()` when necessary, so you shouldn't need to worry about memory leaks there. If\nyou need to add in some error handling, there's always `try/catch` wrapping the `run` command, or\nyou can chain on some `.catch()` method to the `bootstrap()` call.\n\n## Error Handling\n\nBy default, `nest-commander` does not add in any error handling, other that the default that\n`commander` itself does. If you would like to use commander's `exitOverride` you can pass an\n`errorHandler` property to the `options` object of the `CommandFactory.run` method. This error\nhandler should take in an error object, and return void.\n\n```ts\nimport { CommandFactory } from 'nest-commander';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n await CommandFactory.run(AppModule, {\n errorHandler: (err) => {\n console.error(err);\n process.exit(1); // this could also be a 0 depending on how you want to handle the exit code\n }\n });\n}\n\nbootstrap();\n```\n\n## Testing\n\nThere is a testing helper package called\n[`nest-commander-testing`](./../nest-commander-testing/README.md) that works very similarly to\n`@nestjs/testing`. Check out it's documentation and examples for help.\n\n## Putting it All Together\n\nThe following class would equate to having a CLI command that can take in the subcommand `basic` or\nbe called directly, with `-n`, `-s`, and `-b` (along with their long flags) all being supported and\nwith custom parsers for each option. The `--help` flag is also supported, as is customary with\ncommander.\n\n```ts\nimport { Command, CommandRunner, Option } from 'nest-commander';\nimport { LogService } from './log.service';\n\ninterface BasicCommandOptions {\n string?: string;\n boolean?: boolean;\n number?: number;\n}\n\n@Command({ name: 'basic', description: 'A parameter parse' })\nexport class BasicCommand implements CommandRunner {\n constructor(private readonly logService: LogService) {}\n\n async run(passedParam: string[], options?: BasicCommandOptions): Promise<void> {\n if (options?.boolean !== undefined && options?.boolean !== null) {\n this.runWithBoolean(passedParam, options.boolean);\n } else if (options?.number) {\n this.runWithNumber(passedParam, options.number);\n } else if (options?.string) {\n this.runWithString(passedParam, options.string);\n } else {\n this.runWithNone(passedParam);\n }\n }\n\n @Option({\n flags: '-n, --number [number]',\n description: 'A basic number parser'\n })\n parseNumber(val: string): number {\n return Number(val);\n }\n\n @Option({\n flags: '-s, --string [string]',\n description: 'A string return'\n })\n parseString(val: string): string {\n return val;\n }\n\n @Option({\n flags: '-b, --boolean [boolean]',\n description: 'A boolean parser'\n })\n parseBoolean(val: string): boolean {\n return JSON.parse(val);\n }\n\n runWithString(param: string[], option: string): void {\n this.logService.log({ param, string: option });\n }\n\n runWithNumber(param: string[], option: number): void {\n this.logService.log({ param, number: option });\n }\n\n runWithBoolean(param: string[], option: boolean): void {\n this.logService.log({ param, boolean: option });\n }\n\n runWithNone(param: string[]): void {\n this.logService.log({ param });\n }\n}\n```\n\nMake sure the command class is added to a module\n\n```ts\n@Module({\n providers: [LogService, BasicCommand]\n})\nexport class AppModule {}\n```\n\nAnd now to be able to run the CLI in your main.ts you can do the following\n\n```ts\nasync function bootstrap() {\n await CommandFactory.run(AppModule);\n}\n\nbootstrap();\n```\n\nAnd just like that, you've got a command line application. All that's left is to run your build\ncommand (usually `nest build`) and run start like normal (`node dist/main`). If you're looking to\npackage the command line app for other devs consumption (making somethng like the `@nestjs/cli` or\n`jest`), then you can add the `bin` property to the `package.json` and map the command\nappropriately.\n"
}