Lesson 2
Controllers in NestJS
Introduction

Let's talk about Controllers in NestJS. In our previous lesson, we set up a basic NestJS application and explored its project structure. We learned how to install necessary tools, create a new NestJS project, and examine key files such as app.controller.ts, app.service.ts, app.module.ts, and main.ts. Next, we will focus on creating and understanding controllers, which play a crucial role in handling server requests.

What is a Controller?

Controllers in NestJS are responsible for handling incoming requests, processing them, and returning responses to the caller. They act as the entry point for the application. By using decorators (such as @Controller() and @Get()), controllers map specific routes to methods within the controller, enabling clear and structured handling of various endpoints. This organized approach simplifies the development and maintenance of web applications by centralizing the logic for request handling.

Here is an exmaple of what a Controller for a feature might look like. Whenever you make a request to /books, you will receive one book back in JSON form:

TypeScript
1@Controller('books') 2export class BooksController { 3 4 @Get() 5 findAll(): Book[] { 6 return [ 7 { 8 title: "Pride and Prejudice", 9 author: "Jane Austen" 10 }, 11 ]; 12 } 13 14}
Understanding Decorators

You might have noticed the @Controller() and @Get() lines in the code. These are called decorators. In simple terms, decorators are special markers that can be attached to classes, methods, or other elements in your code to give them additional functionality.

Decorators help keep the code clean and readable by clearly indicating what each part of your code is supposed to do. They are a powerful feature in NestJS, making it easier to define routes, handle requests, and even apply custom logic in a consistent way.

The @Controller('books') decorator tells NestJS that this class is a controller and that it handles routes starting with /books. The @Get() decorator maps the /books route to the findAll() method, which in this case returns a single book.

Summary

In this lesson, we explored controllers in NestJS, understanding their crucial role in handling requests. We introduced how methods map to request handlers in the Controller. We discussed the use of decorators like @Controller() and @Get() to define routes and methods. Next, we'll put this concept into action.

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.