Gathering detailed insights and metrics for nest-commander
Gathering detailed insights and metrics for nest-commander
Gathering detailed insights and metrics for nest-commander
Gathering detailed insights and metrics for nest-commander
A module for using NestJS to build up CLI applications
npm install nest-commander
56.3
Supply Chain
94.9
Quality
78.7
Maintenance
100
Vulnerability
97.9
License
nest-commander-schematics@3.0.2
Published on 07 Oct 2024
nest-commander-schematics@3.0.1
Published on 07 Oct 2024
nest-commander@3.15.0
Published on 14 Aug 2024
nest-commander@3.14.0
Published on 01 Jul 2024
nest-commander@3.13.0
Published on 23 Apr 2024
nest-commander@3.12.5
Published on 04 Dec 2023
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
435 Stars
1,290 Commits
53 Forks
6 Watching
17 Branches
32 Contributors
Updated on 14 Nov 2024
Minified
Minified + Gzipped
TypeScript (73.58%)
Astro (13.35%)
CSS (9.4%)
JavaScript (3.42%)
Shell (0.26%)
Cumulative downloads
Total Downloads
Last day
7.1%
42,324
Compared to previous day
Last week
7.9%
214,412
Compared to previous week
Last month
14.2%
892,191
Compared to previous month
Last year
45.8%
8,269,285
Compared to previous year
3
Have you been building amazing applications with NestJS? Do you want that same structure for absolutely everything you're working with? Have you always wanted to build up some sweet CLI application but don't really know where to start? This is the solution. A package to bring building CLI applications to the Nest world with the same structure that you already know and love :heart: Built on top of the popular Commander package.
Before you get started, you'll need to install a few packages. First and foremost, this one:
nest-commander
(name pending). You'll also need to install @nestjs/common
and @nestjs/core
as
this package makes use of them under the hood, but doesn't want to tie you down to a specific
version, yay peerDependencies!
1npm i nest-commander @nestjs/common @nestjs/core 2# OR 3yarn add nest-commander @nestjs/common @nestjs/core 4# OR 5pnpm i nest-commander @nestjs/common @nestjs/core
nest-commander
makes it easy to write new command line applications with
decorators via the @Command()
decorator for classes and the @Option()
decorator for methods of that class. Every command file
should implement the CommandRunner
abstract class and should be decorated with a @Command()
decorator.
Every command is seen as an @Injectable()
by Nest, so your normal Dependency Injection still works
as you would expect it to (woohoo!). The only thing to take note of is the abstract class
CommandRunner
, which should be implemented by each command. The CommandRunner
abstract class
ensures that all commands have a run
method that return 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. You can view
how the Basic Command test manages that if interested.
The @Command()
decorator is to define what CLI command the class is going to manage and take care
of. The decorator takes in an object to define properties of the command. The options passed here
would be the same as the options passed to a new command
for Commander
property | type | required | description |
---|---|---|---|
name | string | true | the name of the command |
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 |
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 |
argsDescription | Record<string, string> | false | An object containing the description of each argument. This will be used by -h or --help |
Options | CommandOptions | false | Extra options to pass on down to commander |
For mor information on the @Command()
and @Option()
parameters, check out the
Commander docs.
Often times you're not just running a single command with a single input, but rather you're running
a command with multiple options and flags. Think of something like git commit
: you can pass a
--amend
flag, a -m
flag, or even -a
, all of these change how the command runs. These flags are
able to be set for each command using the @Option()
decorator on a method for how that flag should
be parsed. Do note that every command sent in via the command line is a raw string, so if you need
to transform that string to a number or a boolean, or any other type, this handler is where it can
be done. See the putting it all together for an example. The @Option()
decorator, like the @Command()
one, takes in an object of options defined in the table below
property | type | required | description |
---|---|---|---|
flags | string | true | a string that represents the option's incoming flag and if the option is required (using <>) or optional (using []) |
description | string | false | the description of the option, used if adding a --help flag |
defaultValue | string or boolean | false | the default value for the flag |
Under the hood, the method that the@Option()
is decorating is the custom parser passed to
commander for how the value should be parsed. This means if you want to parse a boolean value, the
best way to do so would be to use JSON.parse(val)
as Boolean('false')
actually returns true
instead of the expected false
.
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
1import { CommandFactory } from 'nest-commander'; 2import { AppModule } from './app.module'; 3 4async function bootstrap() { 5 await CommandFactory.run(AppModule); 6} 7 8bootstrap();
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.
1import { CommandFactory } from 'nest-commander'; 2import { AppModule } from './app.module'; 3import { LogService } './log.service'; 4 5async function bootstrap() { 6 await CommandFactory.run(AppModule, new LogService()); 7 8 // or, if you only want to print Nest's warnings and errors 9 await CommandFactory.run(AppModule, ['warn', 'error']); 10} 11 12bootstrap();
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.
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.
A nice example of this can be seen in the basic.command.factory.spec.ts file.
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.
1import { Command, CommandRunner, Option } from 'nest-commander';
2import { LogService } from './log.service';
3
4interface BasicCommandOptions {
5 string?: string;
6 boolean?: boolean;
7 number?: number;
8}
9
10@Command({ name: 'basic', description: 'A parameter parse' })
11export class BasicCommand extends CommandRunner {
12 constructor(private readonly logService: LogService) {
13 super();
14 }
15
16 async run(passedParam: string[], options?: BasicCommandOptions): Promise<void> {
17 if (options?.boolean !== undefined && options?.boolean !== null) {
18 this.runWithBoolean(passedParam, options.boolean);
19 } else if (options?.number) {
20 this.runWithNumber(passedParam, options.number);
21 } else if (options?.string) {
22 this.runWithString(passedParam, options.string);
23 } else {
24 this.runWithNone(passedParam);
25 }
26 }
27
28 @Option({
29 flags: '-n, --number [number]',
30 description: 'A basic number parser'
31 })
32 parseNumber(val: string): number {
33 return Number(val);
34 }
35
36 @Option({
37 flags: '-s, --string [string]',
38 description: 'A string return'
39 })
40 parseString(val: string): string {
41 return val;
42 }
43
44 @Option({
45 flags: '-b, --boolean [boolean]',
46 description: 'A boolean parser'
47 })
48 parseBoolean(val: string): boolean {
49 return JSON.parse(val);
50 }
51
52 runWithString(param: string[], option: string): void {
53 this.logService.log({ param, string: option });
54 }
55
56 runWithNumber(param: string[], option: number): void {
57 this.logService.log({ param, number: option });
58 }
59
60 runWithBoolean(param: string[], option: boolean): void {
61 this.logService.log({ param, boolean: option });
62 }
63
64 runWithNone(param: string[]): void {
65 this.logService.log({ param });
66 }
67}
Make sure the command class is added to a module
1@Module({ 2 providers: [LogService, BasicCommand] 3}) 4export class AppModule {}
And now to be able to run the CLI in your main.ts you can do the following
1async function bootstrap() { 2 await CommandFactory.run(AppModule); 3} 4 5bootstrap();
And just like that, you've got a command line application.
This project is licensed under the MIT License - see the LICENSE file for details.
No vulnerabilities found.
No security vulnerabilities found.
nest-commander-testing
A testing utility for nest-commander. It builds on top of ideas from @nestjs/testing and is not tied to any test framework directly.
commander
the complete solution for node.js command-line programs
nestjs-console
A NestJS module that provide a cli
@commander-js/extra-typings
Infer strong typings for commander options and action handlers