Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Specify Which Module to add Controller to in NestJS CLI?

Ive been playing with NestJS for about a week. So far, Im really liking it. The Module system is great. And, I love how easy it is to do things like parse requests.

One question I do have is with regards to the NestJS CLI.

Suppose I have multiple modules. I can create a controller with the following command.

nest g controller Accounts

How do I specify which module this controller belongs to?

The CLI seems to default to the last module you created.

How do I change this behavior?

like image 903
Patrick Lumenus Avatar asked Dec 05 '22 08:12

Patrick Lumenus


2 Answers

The CLI, to my knowledge, will see if you have any modules that match the name of the controller you are creating. For example, if you run

nest g mo accounts
nest g mo contacts
nest g mo leads

And then you run the same for controllers, but in a different order, like

nest g co leads
nest g co accounts
nest g co contacts

You'll still get the AccountsController in the AccountsModule, the LeadsController in the LeadsModule, and the ContactsController in the ContactsModule

If you are looking to add a specific controller to a module that is named differently than the Controller (i.e. add the LeadsController to the AccountsModule) you can pass a path option as the final parameter to the CLI e.g.

nest g co leads accounts

The path you give is relative to src (or whatever your root directory is in the nest-cli.json). This will create the directory accounts/leads where the leads.controller.ts file will live, and will add the controller to the AccountsModule.

The reason that Nest adds the new class to the module of the same name by default is to allow for easy feature module development. The need to not specify the module makes the CLI usage much more friendly to developers (usually), and as a fallback, if a module cannot be found, the CLI adds it to the AppModule (or whatever you have the root module called).

like image 127
Jay McDoniel Avatar answered Dec 09 '22 15:12

Jay McDoniel


If a module already exists, you can simply add its name after the controller/service (or else ..)

nest generate controller <controller_name> <module_name> [--flat]

"--flat" option, if you don't want a new folder generated for your controller

like image 31
Nawfal Hamdi Avatar answered Dec 09 '22 14:12

Nawfal Hamdi