0

I'm using yargs with command modules, i.e. separate file for each command, with each command file defining exports.command, exports.desc, exports.handler for its own command.

For 60% of my commands, the way it works by default is fine. But the other 40% I want to first connect to a database with TypeORM, which is async, and then only after the connection has been made, execute exports.handler wrapped inside a .then() so that it doesn't execute before the DB has connected.

The issue is that in my global entry file, as soon as all the global yargs options are defined, and I execute .argv for yargs to parse the command (which determines if it's a db or non-db command), it also executes exports.handler immediately, so I have no opportunity first connect to the database, and use .then to wrap the exports.handler command code (for the 40% of commands that need it).

I want to avoid having to add async code just for the db connection to every one of those 40% of command files. And also avoid connecting to the db for all 100% of commands, as 60% of them don't need it.

I was about to make major changes and no longer use yargs' command modules... but there must be an easier way to do this?

Is there a way to tell yargs that I want to parse the command but not execute exports.handler yet?

If I can just figure that out, then I can simply segregate the commands that need to be wrapped inside .then() and those that don't.

LaVache
  • 2,372
  • 3
  • 24
  • 38
  • Can you share the code that handles the logic whether to connect to DB or not? – m1ch4ls Aug 24 '18 at 09:07
  • I haven't actually even written the conditional code yet, that will be easy. But I first need the value from `yargs.argv` to test on before I get to that. But as soon as I try to access `yargs.argv`, yargs executes my handler too. Might be that I just need to rename `handler` to something else and no longer follow yargs' conventions. But then I can't figure out how to get the module object to execute the exported code on. Might be just that yargs' command modules are too limited to do this. – LaVache Aug 24 '18 at 09:41
  • I use `yargs` but I am also not sure if what you asking is possible. as a hack you could peek into `process.argv` and check if it contains command that requires DB. – m1ch4ls Aug 24 '18 at 09:54

0 Answers0