Controllers in NestJS

Controllers play a crucial role in any web application, as they act as the intermediary between the client’s requests and the server’s responses. In NestJS, controllers serve as the primary mechanism for handling incoming requests and executing the appropriate logic to generate responses. In this guide, we’ll delve into the core concepts of controllers in NestJS, including basic routing, important decorators for request handling functions, redirection, and handling request payloads.

Basic Routing with Controllers

NestJS employs a modular approach to organize your application’s codebase. Controllers are essentially classes responsible for handling incoming requests from specific routes and generating responses. Let’s start by creating a basic controller in NestJS:

// cats.controller.ts

import { Controller, Get } from '@nestjs/common';

@Controller('cats')
export class CatsController {
  @Get()
  findAll(): string {
    return 'This endpoint returns all cats';
  }
}        

In the above example, we’ve created a simple controller named CatsController with a single route handler for the GET /cats endpoint. The @Controller() decorator specifies the base route path for all routes defined within the controller.

Important Decorators for Request Handling Functions

NestJS provides several decorators to define the behavior of request handling functions within controllers. Some important decorators include:

  • @Get(): Defines a route handler for HTTP GET requests.
  • @Post(): Defines a route handler for HTTP POST requests.
  • @Put(): Defines a route handler for HTTP PUT requests.
  • @Delete(): Defines a route handler for HTTP DELETE requests.
  • @Param(): Retrieves route parameters.
  • @Query(): Retrieves query parameters.
  • @Body(): Retrieves the request body.

Here’s an example demonstrating the usage of these decorators:

// cats.controller.ts
import { Controller, Get, Post, Param, Body } from '@nestjs/common';

@Controller('cats')
export class CatsController {
  @Get(':id')
  findOne(@Param('id') id: string): string {
    return `This endpoint returns cat with id ${id}`;
  }
  
  @Post()
  create(@Body() catData: any): string {
    return `This endpoint creates a new cat with data: ${JSON.stringify(catData)}`;
  }
}        

In the above example, we’ve defined two route handlers using the @Get() and @Post() decorators, along with @Param() and @Body() decorators to retrieve route parameters and request body, respectively.

Redirection

Redirecting requests to another route is a common requirement in web applications. NestJS provides a Redirect method from @nestjs/common package to perform redirection. Here's an example of how to use redirection in a controller:

// cats.controller.ts
import { Controller, Get, Redirect } from '@nestjs/common';

@Controller('cats')
export class CatsController {
  @Get('docs')
  @Redirect('https://nestjs.com', 302)
  redirectToDocs() {
    // This method will not be executed because of the redirection
  }
}        

In the above example, accessing the GET /cats/docs endpoint will automatically redirect the request to https://nestjs.com with a status code of 302.

Request Payloads

Handling request payloads is essential for processing data sent from clients to the server. NestJS simplifies this process using the @Body() decorator, as demonstrated earlier. You can also apply validation using various validation libraries like class-validator.

// create-cat.dto.ts

import { IsString, IsInt } from 'class-validator';

export class CreateCatDto {
  @IsString()
  readonly name: string;

  @IsInt()
  readonly age: number;

  @IsString()
  readonly breed: string;
}        
// cats.controller.ts
import { Controller, Post, Body } from '@nestjs/common';
import { CreateCatDto } from './create-cat.dto';

@Controller('cats')
export class CatsController {
  @Post()
  create(@Body() createCatDto: CreateCatDto): string {
    return `This endpoint creates a new cat with data: ${JSON.stringify(createCatDto)}`;
  }
}        

In this example, we define a data transfer object (DTO) CreateCatDto using class-validator for validating request payloads.

Conclusion

Controllers are a fundamental building block of NestJS applications, providing a structured way to handle incoming requests and generate responses. In this guide, we’ve explored basic routing, important decorators for request handling functions, redirection, and handling request payloads. Understanding these concepts will empower you to build robust and scalable applications with NestJS. Happy coding!

Manu K M

Freelance Full Stack Trainer | Developer |Machine learning enthusiastic|MERN Stack, MVC, NestJS,Pytjon,Django

9 个月

Very useful thank you Deepak Mandal

要查看或添加评论,请登录

Deepak Mandal的更多文章

  • AWS VPC (Virtual Private Cloud) and Its Key Components

    AWS VPC (Virtual Private Cloud) and Its Key Components

    1. What is an IP Address? An IP (Internet Protocol) address is a numerical label assigned to each device connected to a…

  • EC2 : Amazon Elastic Compute Cloud

    EC2 : Amazon Elastic Compute Cloud

    Amazon Elastic Compute Cloud (EC2) is a core service in AWS that provides scalable compute capacity in the cloud. EC2…

  • AWS IAM: How to manage Users

    AWS IAM: How to manage Users

    AWS Identity and Access Management (IAM) is a critical component of securing your AWS environment. In this guide, we…

  • Onboarding AWS

    Onboarding AWS

    Amazon Web Services (AWS) is a leading cloud platform that offers a broad range of services and tools for developers…

  • Understanding Amazon Web Services (AWS) Cloud Computing

    Understanding Amazon Web Services (AWS) Cloud Computing

    Introduction In today’s rapidly evolving digital landscape, businesses are increasingly turning to cloud computing to…

    5 条评论
  • Case Study: Typo.so

    Case Study: Typo.so

    Role: Senior Developer and DevOps Lead Overview Typo.so is a dynamic and feature-rich content creation platform…

  • The Role of Algorithms in Computing

    The Role of Algorithms in Computing

    Introduction Algorithms are the foundation of computing. They are step-by-step computational procedures that transform…

  • Implementing Microservice Communication (Part 2)

    Implementing Microservice Communication (Part 2)

    We have done our first part where we did get understanding of Communication style we can implement in between services.…

  • Implementing Microservice Communication (Part 1)

    Implementing Microservice Communication (Part 1)

    Finding the optimal technology for facilitating communication between microservices entails careful consideration of…

  • Communication styles in microservices

    Communication styles in microservices

    To even start thinking about any implementation, we always need something we called communication style. Defining…

社区洞察

其他会员也浏览了