Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Generating code: the nest CLI

NestJS files almost always start with the same lines: an import, a decorator, an empty class. The Nest CLI creates such skeletons with nest generate and immediately registers them in the right module, so you do not have to do it by hand.

One skeleton

Run the commands from the project root. The word generate can be shortened to g:

nest g module posts
nest g controller posts
nest g service posts

A src/posts/ folder appears with posts.module.ts, posts.controller.ts and posts.service.ts. The CLI adds PostsModule to the imports of the root module, and the controller and service to PostsModule. The terminal shows which files were created (CREATE) and changed (UPDATE).

A whole resource

A resource is everything one API entity needs: a module, controller, service, DTOs and an entity class. For the blog, create posts:

nest g resource posts

The CLI asks two questions. For the transport layer choose REST API, and answer Y to generating CRUD entry points. The result:

src/posts/
├── dto/
│   ├── create-post.dto.ts
│   └── update-post.dto.ts
├── entities/
│   └── post.entity.ts
├── posts.controller.spec.ts
├── posts.controller.ts
├── posts.module.ts
├── posts.service.spec.ts
└── posts.service.ts

CRUD stands for the four basic data actions: create, read, update and delete. The controller already has five routes: GET /posts, GET /posts/:id, POST /posts, PATCH /posts/:id and DELETE /posts/:id. Open http://localhost:3000/posts — you will see the string This action returns all posts. The generated service returns it; you will write the real code in the next lessons.

Useful flags

FlagWhat it does
--dry-run or -dShows what would be created without creating files
--no-specDo not create a .spec.ts test file
--flatDo not create a separate folder
nest g controller comments --dry-run

The command prints the list of files, but nothing changes on disk — handy for checking yourself.

Available skeletons

CommandWhat it creates
nest g moduleModule
nest g controllerController
nest g serviceService
nest g resourceModule, controller, service, DTOs and entity
nest g pipePipe
nest g guardGuard
nest g interceptorInterceptor
nest g middlewareMiddleware

nest g --help shows the full list.

Common mistake

If you create a controller file by hand and forget to list it in the module's controllers array, NestJS never learns about it: its routes answer 404 with no error at startup. Use nest g — it registers classes for you. If you do create a file by hand, add the class to the module right away.

Thanks for reading!

Donate to the site — we work hard for you.