-
-
Notifications
You must be signed in to change notification settings - Fork 26
Using the ConsoleService
Rmannn edited this page May 20, 2021
·
3 revisions
As a simple example, we will define a cli with 2 commands, new and list.
The new command will have 2 sub commands, directory and file
Cli -> new -> [
directory -> execution,
file -> execution
]
-> list -> execution
Registering methods using the ConsoleService is more flexible than decorators.
When you use the ConsoleService, you simply bind your methods to the cli manually.
This is useful if you need to create the cli or a part of the cli at runtime.
This way you can also create multiple commands and sub commands from the same context.
Note: you can use both the ConsoleService and the decorators.
// service.ts - a nestjs provider
import { Injectable } from '@nestjs/common';
import { ConsoleService } from 'nestjs-console';
@Injectable()
export class MyService {
constructor(private readonly consoleService: ConsoleService) {
// get the root cli
const cli = this.consoleService.getCli();
// create a single command (See [npm commander arguments/options for more details])
this.consoleService.createCommand(
{
command: 'list <directory>',
description: 'description'
},
this.listContent,
cli // attach the command to the cli
);
// create a parent command container
const groupCommand = this.consoleService.createGroupCommand(
{
command: 'new',
description: 'A command to create an item'
},
cli // attach the command to the root cli
);
// create command
this.consoleService.createCommand(
{
command: 'file <name>',
description: 'Create a file'
},
this.createFile,
groupCommand // attach the command to the group
);
// create an other sub command
this.consoleService.createCommand(
{
command: 'directory <name>',
description: 'Create a directory'
},
this.createDirectory,
groupCommand // attach the command to the group
);
}
listContent = async (directory: string): void | Promise<void> => {
console.log(`Listing files in directory ${directory}`);
// your code...
};
createFile = async (name: string): void | Promise<void> => {
console.log(`Creating a file named ${name}`);
// your code...
};
createDirectory = async (name: string): void | Promise<void> => {
console.log(`Creating a directory named ${name}`);
// your code...
};
}