Horje
Controllers in NestJS

NestJS is a Node.js framework for building efficient, reliable, and scalable server-side applications. One of its core concepts is the use of controllers. Controllers in NestJS are responsible for handling incoming requests, processing them, and returning responses to the client. In this article, we will learn more about Controllers in NestJS.

What is a Controller?

In the context of NestJS, a controller is a class decorated with the @Controller() decorator. It is designed to handle specific routes within an application. Controllers are responsible for accepting incoming requests, invoking the appropriate service methods, and sending the response back to the client. They act as an intermediate between the client and the service layer.

Creating a Controller

To create a controller in NestJS, you need to define a class and decorate it with the @Controller() decorator. Here’s a basic example:

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

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

In this example, the CatsController is created to handle requests to the /cats route. The @Get() decorator maps HTTP GET requests to the findAll method.

Route Handlers

Route handlers in NestJS are methods within a controller that are decorated with route-specific decorators like @Get(), @Post(), @Put(), @Delete(), and @Patch(). These decorators define the HTTP method and the route to which the handler will respond.

Here’s an example demonstrating various route handlers:

import { Controller, Get, Post, Put, Delete, Param, Body } 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(@Body() createCatDto: any): string {
        return 'This action adds a new cat';
    }

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

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

In this example, the CatsController has handlers for different HTTP methods and routes. The @Param() and @Body() decorators are used to extract route parameters and request bodies, respectively.

Dependency Injection

NestJS utilizes dependency injection to manage dependencies within an application. Controllers can inject services and other providers using the constructor. This allows for cleaner and more maintainable code.

import { Controller, Get } from '@nestjs/common';
import { CatsService } from './cats.service';

@Controller('cats')
export class CatsController {
    constructor(private readonly catsService: CatsService) { }

    @Get()
    findAll(): string {
        return this.catsService.findAll();
    }
}

In this example, the CatsController injects the CatsService through its constructor. This allows the controller to delegate the business logic to the service.

Handling Requests

NestJS controllers can handle various types of requests, including:

  • Query Parameters: Using the @Query() decorator.
  • Route Parameters: Using the @Param() decorator.
  • Request Body: Using the @Body() decorator.
  • Headers: Using the @Headers() decorator.

Middleware and Guards

Controllers can also utilize middleware and guards to handle authentication, logging, and other cross-cutting concerns. Middleware is applied to routes to perform actions before the route handler is invoked. Guards determine whether a request should be handled by a route based on custom logic.

import { Controller, Get, UseGuards } from '@nestjs/common';
import { AuthGuard } from './auth.guard';

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

In this example, the AuthGuard is applied to the CatsController, ensuring that all requests to this controller are authenticated.

Steps to Implement Controllers in NextJS

Step 1: Setup a Nest.js Project

First, ensure you have Node.js and npm installed. Then, install the Nest CLI if you haven’t already:

npm install -g @nestjs/cli

Step 2: Create a new NestJS project:

nest new nest-gfg

Step 3: Navigate to the project directory:

cd nest-gfg

Step 4: Creating a Simple Controller

Generate a new controller using the Nest CLI:

nest generate controller hello

This will create a new controller file under the src/hello directory.

Folder Structure

dfg

Folder Structure

Dependencies

"dependencies": {
    "@nestjs/common": "^10.0.0",
    "@nestjs/core": "^10.0.0",
    "@nestjs/mongoose": "^10.0.10",
    "@nestjs/platform-express": "^10.0.0",
    "dotenv": "^16.4.5",
    "mongoose": "^8.5.1",
    "reflect-metadata": "^0.2.0",
    "rxjs": "^7.8.1"
  }

Example: Implementing the Controller

JavaScript
//src/main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
    const app = await NestFactory.create(AppModule);
    await app.listen(3000);
}
bootstrap();
JavaScript
//src/app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { HelloController } from './hello/hello.controller';

@Module({
    imports: [],
    controllers: [AppController, HelloController],
    providers: [AppService],
})
export class AppModule { }
JavaScript
//src/hello/hello.controler.ts

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

@Controller('hello')
export class HelloController {
    @Get()
    getHello(): string {
        return 'Hello World!';
    }
}

To start the application run the following command.

npm run start

Output

ewrt

Controllers in NestJS




Reffered: https://www.geeksforgeeks.org


Web Technologies

Related
E-commerce Websites : User Account Section: E-commerce Websites : User Account Section:
E-commerce Websites : Filter and Sort Options E-commerce Websites : Filter and Sort Options
E-commerce Websites : Search Bar E-commerce Websites : Search Bar
E-commerce Websites : User Login and Sign up E-commerce Websites : User Login and Sign up
Folder Structure of a NestJS Project Folder Structure of a NestJS Project

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
17