Pop-Code / nestjs-console

A nestjs module that provide a cli to your application.
https://www.npmjs.com/package/nestjs-console
MIT License
561 stars 26 forks source link

Can't read CLI options to configure the database #371

Closed pminiszewski closed 3 years ago

pminiszewski commented 3 years ago

In my CLI program, I have a --db option that allows configuring database connection for all Commands. The code below is what I got so far. However this causes the program to freeze because module waits until useFactory() resolves the Promise but it will never resolve because commandline options haven't been parsed yet.

Is there any way to make sure that CLI commands get parsed and are available before anything else?

`import { Auth0Module } from '@app/common/auth0/auth0.module'; import { CommonModule } from '@app/common/common.module'; import { UsersModule } from '@app/common/users/users.module'; import { HttpException, Module } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { MongooseModule, MongooseModuleOptions } from '@nestjs/mongoose'; import { ConsoleModule, ConsoleService } from 'nestjs-console';

@Module({ imports: [ ConsoleModule, MongooseModule.forRootAsync({ imports: [ConfigModule, ConsoleModule], useFactory: async function (configService: ConfigService, cli: ConsoleService): Promise { const c = cli.getCli().requiredOption("--db ", "DB string")

    let v = {
      uri: configService.get('MONGODB_URL', 'mongodb://localhost/mydb'),
      retryAttempts: 1,
    }

    return new Promise((resolve) => {
      console.log("promise start")
      c.on('option:db', (op: string) => {
        console.log("op:" + op)
        v.uri = op //override database uri with cli global option
        resolve(v)
      })
    })

  },
  inject: [ConfigService, ConsoleService],
}),
CommonModule,

], providers: [

] }) export class AppModule { }`

Rmannn commented 3 years ago

The cli parses args after dependency injection is done because the app may register cli providers and we need to build the app to get providers ready. The bootstrap is building the app and deps before any job. So your db is connecting before args been parsed. You can't use it this way.

Rmannn commented 3 years ago

I will test if we can parse args before to bootstrap, because your example is a nice way to use the cli. But I can't tell you when.

pminiszewski commented 3 years ago

Thanks for the reply! So far I found a walkaround by calling commander.program.parse(process.argv) inside useFactory function. It isn't ideal but should work for now.