Controllers: Handling Incoming Requests
Creating controllers, defining routes, and handling HTTP methods (GET, POST, PUT, DELETE).
NestJS Controllers and Request Handling
Controllers: Handling Incoming Requests
In NestJS, Controllers play a pivotal role in handling incoming requests. They are responsible for receiving specific requests from the client and determining the appropriate response. Think of them as the entry points for your application's API. They connect HTTP routes (like /users
or /products
) to your application's logic.
NestJS Controllers are typically classes decorated with the @Controller()
decorator. This decorator signifies to NestJS that this class will handle routing and request processing. The decorator can accept an optional path prefix which helps organize your application's routes.
Creating Controllers
Here's a simple example of creating a controller in NestJS:
// src/users/users.controller.ts
import { Controller, Get, Post, Body, Param, Put, Delete } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { UsersService } from './users.service'; // Assuming you have a UserService
@Controller('users')
export class UsersController {
constructor(private readonly usersService: UsersService) {} // Injecting UsersService
@Post()
create(@Body() createUserDto: CreateUserDto) {
return this.usersService.create(createUserDto);
}
@Get()
findAll() {
return this.usersService.findAll();
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.usersService.findOne(+id); // Convert string to number (if ID is numeric)
}
@Put(':id')
update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) {
return this.usersService.update(+id, updateUserDto);
}
@Delete(':id')
remove(@Param('id') id: string) {
return this.usersService.remove(+id);
}
}
Explanation:
@Controller('users')
: This decorator tells NestJS that this controller will handle routes starting with/users
. For example, all routes defined within this controller will be prefixed with/users
.@Post()
,@Get()
,@Put()
,@Delete()
: These are route handlers that define the HTTP methods and the specific paths they respond to.@Body()
: This decorator extracts data from the request body and maps it to a DTO (Data Transfer Object) likeCreateUserDto
. DTOs are best practices for validating your payload@Param('id')
: This decorator extracts parameters from the URL (e.g.,/users/123
). The'id'
corresponds to the parameter name in the route path.- Dependency Injection: The
UsersService
is injected into the controller's constructor. This allows the controller to delegate the actual business logic to the service.
Defining Routes and Handling HTTP Methods
NestJS provides decorators to map specific HTTP methods to handler functions within your controller. Here's a breakdown of the common HTTP methods:
@Get(path)
: Handles GET requests. Used to retrieve data.- Example:
@Get() findAll()
handles/users
. - Example:
@Get(':id') findOne(@Param('id') id: string)
handles/users/:id
(e.g.,/users/123
).
- Example:
@Post(path)
: Handles POST requests. Used to create new resources.- Example:
@Post() create(@Body() createUserDto: CreateUserDto)
handles/users
(typically to create a new user).
- Example:
@Put(path)
: Handles PUT requests. Used to update existing resources. Typically requires sending the entire updated resource.- Example:
@Put(':id') update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto)
handles/users/:id
(to update the user with the specified ID).
- Example:
@Delete(path)
: Handles DELETE requests. Used to delete resources.- Example:
@Delete(':id') remove(@Param('id') id: string)
handles/users/:id
(to delete the user with the specified ID).
- Example:
@Patch(path)
: Handles PATCH requests. Used to partially update existing resources. (not shown above, but important)
The path
argument in these decorators is optional. If omitted, the route will match the controller's base path. You can also specify dynamic route parameters using colons (:
), as shown in the examples above.
Request Handling Flow
- A client sends an HTTP request to your NestJS application.
- NestJS's routing module matches the request's method (GET, POST, etc.) and URL to the appropriate controller and handler function.
- NestJS extracts any data from the request (e.g., request body, URL parameters) and passes it to the handler function as arguments.
- The handler function processes the request, often calling services to perform business logic.
- The handler function returns a response (e.g., a JSON object, an HTTP status code, a redirect).
- NestJS sends the response back to the client.
This is the fundamental process of how NestJS controllers handle incoming requests and provide a structured way to build APIs.