logo
Published on

nestjsで自作コマンドを使えるようにする

著者
  • profile
    名前
    平原典彦
nestjsで自作コマンドを作るにはnest-commanderを利用します。 https://docs.nestjs.com/recipes/nest-commander
まずは実行したいコマンドを作成します。
// src/commands/example.command.ts import { Command, CommandRunner, Option } from 'nest-commander'; type CommandOptions = { name?: string; }; @Command({ name: 'example', options: { isDefault: false }, }) export class ExampleCommand extends CommandRunner { constructor(private readonly prisma: PrismaService) { super(); } @Option({ flags: '-n --name [string]', }) parseName(value: string): string { return value; } async run(inputs: string[], options?: CommandOptions): void { console.log(options.name); } }
ただコンソール画面で入力した名前が返ってくるだけのコマンドです。
moduleを準備します。
// src/commands/commands.module.ts import { Module } from '@nestjs/common'; import { ExampleCommand } from './example.command'; @Module({ providers: [ExampleCommand], exports: [ExampleCommand], }) export class CommandsModule {}
module化しとくとコマンドが増えたときに便利です。
作成したmoduleAppModuleに登録します。
// src/app.module.ts import { Module } from '@nestjs/common'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { CommandsModule } from './commands/commands.module'; @Module({ imports: [ CommandsModule, ], controllers: [AppController], providers: [AppService], }) export class AppModule {}
コマンド実行用のファイルを作成します。
// src/cli.ts import { AppModule } from './app.module'; import { CommandFactory } from 'nest-commander'; async function bootstrap() { await CommandFactory.run(AppModule); } bootstrap();
main.tsCommandFactoryを書いていたのですが、正しく動作しなかったので、別ファイルとして準備します。
コマンド実行
$ node dist/src/cli example -n "日本太郎" 日本太郎
これで自作コマンド作成完了です。
簡単ですね。