Nest.js Controller in Easier Terms

Shameel Uddin - Dec 28 '23 - - Dev Community

Nest.js, a progressive Node.js framework, has gained popularity for its modular and scalable architecture. One of its key components is the Controller, which plays a pivotal role in handling incoming requests and defining the application's routing logic. In this blog post, we will delve into the Nest.js Controller and explore its routing mechanism with practical coding examples.

Please find video explanation below ↓

Understanding Nest.js Controllers

Controllers in Nest.js are responsible for handling incoming HTTP requests, processing them, and returning an appropriate response. They act as the bridge between the client (request) and the server (application logic). Controllers are decorated with the @Controller decorator, and they contain methods that handle specific routes.

Let's create a simple Nest.js controller to illustrate the basic structure:

// cats.controller.ts

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

@Controller('cats')
export class CatsController {
  @Get()
  findAll(): string {
    return 'This action returns all cats';
  }
}
Enter fullscreen mode Exit fullscreen mode

In this example, we've created a CatsController decorated with @Controller('cats'). The argument passed to @Controller specifies the base route for all the methods within this controller. The @Get() decorator is used to define an HTTP GET route, and the findAll method is the handler for this route.

Routing in Nest.js

Nest.js follows a decorator-based approach for defining routes within controllers. Decorators are special functions prefixed with @ that provide metadata to Nest.js, allowing it to understand the structure of the application.

Let's extend our CatsController to include more routes and demonstrate different HTTP methods:

// cats.controller.ts

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

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

  @Get(':id')
  findOne(@Param('id') id: string): string {
    return `This action returns cat #${id}`;
  }

  @Post()
  create(): string {
    return 'This action creates a new cat';
  }

  @Put(':id')
  update(@Param('id') id: string): string {
    return `This action updates cat #${id}`;
  }

  @Delete(':id')
  remove(@Param('id') id: string): string {
    return `This action removes cat #${id}`;
  }
}
Enter fullscreen mode Exit fullscreen mode

In this extended example, we've added methods for handling GET, POST, PUT, and DELETE requests. The @Get(':id') decorator defines a route with a dynamic parameter (id), and the @Param('id') decorator extracts that parameter from the request.

Organizing Controllers in Modules

Nest.js encourages the use of modules to organize the application. Controllers are often associated with modules, and the @Module decorator is used for this purpose. Here's an example of how you might organize your controllers into a module:

// cats.module.ts

import { Module } from '@nestjs/common';
import { CatsController } from './cats.controller';

@Module({
  controllers: [CatsController],
})
export class CatsModule {}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Nest.js controllers and routing mechanisms simplify the process of handling HTTP requests in your application. By using decorators, you can easily define routes and extract parameters from incoming requests. This modular and expressive approach contributes to the overall readability and maintainability of your code.

Remember, this is just a basic overview, and Nest.js offers many more features for handling authentication, validation, and other aspects of web development.

Follow me for more such content:
YouTube: https://www.youtube.com/@ShameelUddin123
LinkedIn: https://www.linkedin.com/in/shameeluddin/
Github: https://github.com/Shameel123

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player