|
| 1 | +### Nest Commander |
| 2 | + |
| 3 | +Expanding on the [standalone application](/standalone-applications) docs there's also the [nest-commander](https://jmcdo29.github.io/nest-commander) package for writing command line applications in a structure similar to your typical Nest application. |
| 4 | + |
| 5 | +> info **info** `nest-commander` is a third party package and is not managed by the entirety of the NestJS core team. Please, report any issues found with the library in the [appropriate repository](https://github.com/jmcdo29/nest-commander/issues/new/choose) |
| 6 | +
|
| 7 | +#### Installation |
| 8 | + |
| 9 | +Just like any other package, you've got to install it before you can use it. |
| 10 | + |
| 11 | +```bash |
| 12 | +$ npm i nest-commander |
| 13 | +``` |
| 14 | + |
| 15 | +#### A Command file |
| 16 | + |
| 17 | +`nest-commander` makes it easy to write new command-line applications with [decorators](https://www.typescriptlang.org/docs/handbook/decorators.html) via the `@Command()` decorator for classes and the `@Option()` decorator for methods of that class. Every command file should implement the `CommandRunner` interface and should be decorated with a `@Command()` decorator. |
| 18 | + |
| 19 | +Every command is seen as an `@Injectable()` by Nest, so your normal Dependency Injection still works as you would expect it to. The only thing to take note of is the interface `CommandRunner`, which should be implemented by each command. The `CommandRunner` interface ensures that all commands have a `run` method that returns a `Promise<void>` and takes in the parameters `string[], Record<string, any>`. The `run` command is where you can kick all of your logic off from, it will take in whatever parameters did not match option flags and pass them in as an array, just in case you are really meaning to work with multiple parameters. As for the options, the `Record<string, any>`, the names of these properties match the `name` property given to the `@Option()` decorators, while their value matches the return of the option handler. If you'd like better type safety, you are welcome to create an interface for your options as well. |
| 20 | + |
| 21 | +#### Running the Command |
| 22 | + |
| 23 | +Similar to how in a NestJS application we can use the `NestFactory` to create a server for us, and run it using `listen`, the `nest-commander` package exposes a simple to use API to run your server. Import the `CommandFactory` and use the `static` method `run` and pass in the root module of your application. This would probably look like below |
| 24 | + |
| 25 | +```ts |
| 26 | +import { CommandFactory } from 'nest-commander'; |
| 27 | +import { AppModule } from './app.module'; |
| 28 | + |
| 29 | +async function bootstrap() { |
| 30 | + await CommandFactory.run(AppModule); |
| 31 | +} |
| 32 | + |
| 33 | +bootstrap(); |
| 34 | +``` |
| 35 | + |
| 36 | +By default, Nest's logger is disabled when using the `CommandFactory`. It's possible to provide it though, as the second argument to the `run` function. You can either provide a custom NestJS logger, or an array of log levels you want to keep - it might be useful to at least provide `['error']` here, if you only want to print out Nest's error logs. |
| 37 | + |
| 38 | +```ts |
| 39 | +import { CommandFactory } from 'nest-commander'; |
| 40 | +import { AppModule } from './app.module'; |
| 41 | +import { LogService } './log.service'; |
| 42 | + |
| 43 | +async function bootstrap() { |
| 44 | + await CommandFactory.run(AppModule, new LogService()); |
| 45 | + |
| 46 | + // or, if you only want to print Nest's warnings and errors |
| 47 | + await CommandFactory.run(AppModule, ['warn', 'error']); |
| 48 | +} |
| 49 | + |
| 50 | +bootstrap(); |
| 51 | +``` |
| 52 | +
|
| 53 | +And that's it. Under the hood, `CommandFactory` will worry about calling `NestFactory` for you and calling `app.close()` when necessary, so you shouldn't need to worry about memory leaks there. If you need to add in some error handling, there's always `try/catch` wrapping the `run` command, or you can chain on some `.catch()` method to the `bootstrap()` call. |
| 54 | +
|
| 55 | +#### Testing |
| 56 | +
|
| 57 | +So what's the use of writing a super awesome command line script if you can't test it super easily, right? Fortunately, `nest-commander` has some utilities you can make use of that fits in perfectly with the NestJS ecosystem, it'll feel right at home to any Nestlings out there. Instead of using the `CommandFactory` for building the command in test mode, you can use `CommandTestFactory` and pass in your metadata, very similarly to how `Test.createTestingModule` from `@nestjs/testing` works. In fact, it uses this package under the hood. You're also still able to chain on the `overrideProvider` methods before calling `compile()` so you can swap out DI pieces right in the test. |
| 58 | +
|
| 59 | +#### Putting it all together |
| 60 | +
|
| 61 | +The following class would equate to having a CLI command that can take in the subcommand `basic` or be called directly, with `-n`, `-s`, and `-b` (along with their long flags) all being supported and with custom parsers for each option. The `--help` flag is also supported, as is customary with commander. |
| 62 | +
|
| 63 | +```ts |
| 64 | +import { Command, CommandRunner, Option } from 'nest-commander'; |
| 65 | +import { LogService } from './log.service'; |
| 66 | + |
| 67 | +interface BasicCommandOptions { |
| 68 | + string?: string; |
| 69 | + boolean?: boolean; |
| 70 | + number?: number; |
| 71 | +} |
| 72 | + |
| 73 | +@Command({ name: 'basic', description: 'A parameter parse' }) |
| 74 | +export class BasicCommand implements CommandRunner { |
| 75 | + constructor(private readonly logService: LogService) {} |
| 76 | + |
| 77 | + async run( |
| 78 | + passedParam: string[], |
| 79 | + options?: BasicCommandOptions, |
| 80 | + ): Promise<void> { |
| 81 | + if (options?.boolean !== undefined && options?.boolean !== null) { |
| 82 | + this.runWithBoolean(passedParam, options.boolean); |
| 83 | + } else if (options?.number) { |
| 84 | + this.runWithNumber(passedParam, options.number); |
| 85 | + } else if (options?.string) { |
| 86 | + this.runWithString(passedParam, options.string); |
| 87 | + } else { |
| 88 | + this.runWithNone(passedParam); |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + @Option({ |
| 93 | + flags: '-n, --number [number]', |
| 94 | + description: 'A basic number parser', |
| 95 | + }) |
| 96 | + parseNumber(val: string): number { |
| 97 | + return Number(val); |
| 98 | + } |
| 99 | + |
| 100 | + @Option({ |
| 101 | + flags: '-s, --string [string]', |
| 102 | + description: 'A string return', |
| 103 | + }) |
| 104 | + parseString(val: string): string { |
| 105 | + return val; |
| 106 | + } |
| 107 | + |
| 108 | + @Option({ |
| 109 | + flags: '-b, --boolean [boolean]', |
| 110 | + description: 'A boolean parser', |
| 111 | + }) |
| 112 | + parseBoolean(val: string): boolean { |
| 113 | + return JSON.parse(val); |
| 114 | + } |
| 115 | + |
| 116 | + runWithString(param: string[], option: string): void { |
| 117 | + this.logService.log({ param, string: option }); |
| 118 | + } |
| 119 | + |
| 120 | + runWithNumber(param: string[], option: number): void { |
| 121 | + this.logService.log({ param, number: option }); |
| 122 | + } |
| 123 | + |
| 124 | + runWithBoolean(param: string[], option: boolean): void { |
| 125 | + this.logService.log({ param, boolean: option }); |
| 126 | + } |
| 127 | + |
| 128 | + runWithNone(param: string[]): void { |
| 129 | + this.logService.log({ param }); |
| 130 | + } |
| 131 | +} |
| 132 | +``` |
| 133 | + |
| 134 | +Make sure the command class is added to a module |
| 135 | + |
| 136 | +```ts |
| 137 | +@Module({ |
| 138 | + providers: [LogService, BasicCommand], |
| 139 | +}) |
| 140 | +export class AppModule {} |
| 141 | +``` |
| 142 | + |
| 143 | +And now to be able to run the CLI in your main.ts you can do the following |
| 144 | + |
| 145 | +```ts |
| 146 | +async function bootstrap() { |
| 147 | + await CommandFactory.run(AppModule); |
| 148 | +} |
| 149 | + |
| 150 | +bootstrap(); |
| 151 | +``` |
| 152 | + |
| 153 | +And just like that, you've got a command line application. |
| 154 | + |
| 155 | +#### More Information |
| 156 | + |
| 157 | +Visit the [nest-commander docs site](https://jmcdo29.github.io/nest-commander) for more information, examples, and API documentation. |
0 commit comments