NESTJs Controller

Pradeep R.R.
YavarTechWorks
Published in
2 min readOct 30, 2022

--

In this blog we will discuss about the controller part in nestjs

Controllers are responsible for handling request sent to the server ad returning response to the client.

A controllers is to receive specific request for the application.the routing is a mechanism to controls which controller receives request.

Each controller has more than one route and different routes have different actions.

To generate the controller we use ,

nest g controller name

Routing

we use the `@controller()` decorator it is basic controller to define an endpoints.

import { Controller, Get } from '@nestjs/common';
@Controller('sample')
export class SampleController {
@Get()
findAll():string{
return 'Hello World';
}
}

The Get() Http request method decorator.the route path for a handler is detemined by concatenating the prefix declared for the controller.

The request object represents the HTTP request and has propertis for the request query string,parameters,Http headers,and body.

@Request,@Req()             req
@Response(),@res() res
@Next() next
@Session() req.session
@Param(key?: string) req.params/req.params[key]
@Body(key?: string) req.body/req.body[key]
@Query(key?: string) req.query/req.query[key]
@Headers(name?: string) req.headers/req.headers[name]
@Ip() req.ip
@HostParam() req.hosts

Route parameters:

Routes with static path won’t work when you need to accept the dynamic data as part of the request.eg(GET/sample/1-toget sample with id 1).

`@Param()` is used to decorate a method parameter.we an access the id parameter by referencig params.id.

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

Request Payloads:

The post route handler didn’t accept any client params.let fix by this adding `@Body()` decorator used.

DTO schema- (data transfer object)

DTO schema is used to determine by using typescript interfaces and classes.

``createsampledto`` class

export class CreateCatDto {
name: string;
age: number;
breed: string;
}

It has three basic properties we can use the newly created DTO inside,

@Post()
async create(@Body() createCatDto: CreateCatDto) {
return 'Hello world';
}

Library specific approach

The second way of manipulating response is to use a specific response object.The ``@Res() decorator`

import { Controller, Get, Post, Res, HttpStatus } from '@nestjs/common';
import { Response } from 'express';

@Controller('sample')
export class SampleController {
@Post()
create(@Res() res: Response) {
res.status(HttpStatus.CREATED).send();
}

@Get()
findAll(@Res() res: Response) {
res.status(HttpStatus.OK).json([]);
}
}

--

--