Generating Controllers, Services, and Module From the CLI
Explore how to efficiently generate modules, controllers, and services in a NestJS application using the CLI. Understand commands to create these core building blocks, automate CRUD operations, and utilize CLI options to preview or customize file generation. Gain practical skills to speed up backend development workflow.
Now that we have a fundamental understanding of the NestJS CLI, we’ll explore how to use it to generate key building blocks of a NestJS application, including modules, controllers, and services. We’ll see how these commands create files quickly, helping us avoid the often tedious process of manual file creation.
Generating a module
Suppose we build a user management system that handles user registrations, logins, and other user-related operations. We’ll need to create a dedicated module to encapsulate all these functionalities, a controller to handle HTTP requests, and a service for business logic. Let’s start with a module.
For example, to generate the users module from NestJS CLI, run the following command:
nest g mo users
This command will generate a new users.module.ts file within the src/users folder.
src/
├── app.controller.ts
├── app.module.ts
├── app.service.ts
└── users/
└── users.module.ts
Generating controllers
To generate the users controllers, run the following command:
nest g controller users
...