Skip to content

Commit 61e9065

Browse files
Merge pull request #2079 from jmcdo29/feat/commander-recipe
feat: make a recipe for nest-commander
2 parents 1ce9375 + 8034051 commit 61e9065

File tree

5 files changed

+179
-4
lines changed

5 files changed

+179
-4
lines changed

content/recipes/nest-commander.md

Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
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.

src/app/homepage/menu/menu.component.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,7 @@ export class MenuComponent implements OnInit {
237237
{ title: 'Compodoc', path: '/recipes/documentation' },
238238
{ title: 'Prisma', path: '/recipes/prisma' },
239239
{ title: 'Serve static', path: '/recipes/serve-static' },
240+
{ title: 'Nest Commander', path: '/recipes/nest-commander' },
240241
],
241242
},
242243
{

src/app/homepage/pages/microservices/custom-transport/custom-transport.component.html

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -197,8 +197,8 @@ <h4 appAnchor id="message-serialization"><span>Message serialization</span></h4>
197197
<p>If you need to add some custom logic around the serialization of responses on the client side, you can use a custom class that extends the <code>ClientProxy</code> class or one of its child classes. For modifying successful requests you can override the <code>serializeResponse</code> method, and for modifying any errors that go through this client you can override the <code>serializeError</code> method. To make use of this custom class, you can pass the class itself to the <code>ClientsModule.register()</code> method using the <code>customClass</code> property. Below is an example of a custom <code>ClientProxy</code> that serializes each error into an <code>RpcException</code>.</p>
198198

199199
<span class="filename">
200-
{{ 'error-handling.proxy' | extension: app6cfb1a7ffd89db0636851e47b45f946d1913a4ef.isJsActive }}
201-
<app-tabs #app6cfb1a7ffd89db0636851e47b45f946d1913a4ef></app-tabs>
200+
{{ 'error-handling.proxy' | extension: appef748bdb0474f8314c0d2d844a046dd0b313d5bd.isJsActive }}
201+
<app-tabs #appef748bdb0474f8314c0d2d844a046dd0b313d5bd></app-tabs>
202202
</span><pre><code class="language-typescript">
203203
import &#123; ClientTcp, RpcException &#125; from &#39;@nestjs/microservices&#39;;
204204

@@ -210,8 +210,8 @@ <h4 appAnchor id="message-serialization"><span>Message serialization</span></h4>
210210
</code></pre><p>and then use it in the <code>ClientsModule</code> like so:</p>
211211

212212
<span class="filename">
213-
{{ 'app.module' | extension: appa6c68c9ced980f6c3b4d7063dcf2e7e304b20254.isJsActive }}
214-
<app-tabs #appa6c68c9ced980f6c3b4d7063dcf2e7e304b20254></app-tabs>
213+
{{ 'app.module' | extension: appe71a4ea7740a397e20f1e653d6c83fd05f372e95.isJsActive }}
214+
<app-tabs #appe71a4ea7740a397e20f1e653d6c83fd05f372e95></app-tabs>
215215
</span><pre><code class="language-typescript">
216216
@Module(&#123;
217217
imports: [
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
2+
import { ChangeDetectionStrategy, Component } from '@angular/core';
3+
import { BasePageComponent } from '../../page/page.component';
4+
5+
@Component({
6+
selector: 'app-nest-commander',
7+
templateUrl: './nest-commander.component.html',
8+
changeDetection: ChangeDetectionStrategy.OnPush,
9+
})
10+
export class NestCommanderComponent extends BasePageComponent {}

src/app/homepage/pages/recipes/recipes.module.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { SqlSequelizeComponent } from './sql-sequelize/sql-sequelize.component';
1414
import { SqlTypeormComponent } from './sql-typeorm/sql-typeorm.component';
1515
import { TerminusComponent } from './terminus/terminus.component';
1616
import { RouterModuleComponent } from './router-module/router-module.component';
17+
import { NestCommanderComponent } from './nest-commander/nest-commander.component';
1718

1819
const routes: Routes = [
1920
{
@@ -88,6 +89,11 @@ const routes: Routes = [
8889
component: RouterModuleComponent,
8990
data: { title: 'Router module' },
9091
},
92+
{
93+
path: 'nest-commander',
94+
component: NestCommanderComponent,
95+
data: { title: 'Nest Commander' },
96+
},
9197
];
9298

9399
@NgModule({
@@ -105,6 +111,7 @@ const routes: Routes = [
105111
CrudGeneratorComponent,
106112
RouterModuleComponent,
107113
ServeStaticComponent,
114+
NestCommanderComponent,
108115
],
109116
})
110117
export class RecipesModule {}

0 commit comments

Comments
 (0)