Controller NestJs : The NestJs Journey with Shiv (Part-2)

Controllers

In Nest.js, a controller is a class responsible for handling incoming HTTP requests and providing appropriate responses.

Image from nest js official documentation. 


we use @Controller decorator, which indicates this current class is the controller so when a request comes on a specific route so controller handles that request. Basically, the controller takes an argument where you specify the route.


Check the below code where @Controller is a decorator and "cats" in @Controller('cats')  which specify a route.


ex: http://localhost:3000/cats 

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

@Controller('cats') // Base route for the controller
export class CatsController {
  @Get() // Handles GET requests to /cats
  findAll(): string {
    return 'This is a GET request to /cats';
  }
}

Routing:

This base route path acts like a prefix for all the routes defined inside that controller. It helps us group related routes under a common path, making our code more organized and reducing redundancy.


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

@Controller('cats') // Setting the base route path to '/cats'
export class CatsController {
  @Get() // This handles GET requests to '/cats'
  findAll(): string {
    return 'we are all cats';
  }

  @Get('details') // This handles GET requests to '/cats/details'
  findDetails(): string {
    return 'All details of cats';
  }
}

In simple terms, routing is just a way to specify a route and group routes, just look at the above code. we have two @Get methods in the code. Let me explain

If we make a get request on "/cats" route it will return the ''we are all cats"  response if make a request on "/cats/details" it will return 'All details of cats' and @Get is also a decorator which is called Get decorator.

You see @Get decorator is used over the method so the corresponding method will execute. for '/cats' route findAll() method and similarly for '/cats/details' findDeatils() method will execute.

You see in @controller('cats'), "cats" is a base route and if you add another route in @Get decorator like @Get('details') it will group like "/cats/details" this is called route grouping.

More details are added on this page.



Comments

Popular Posts