102. Controllers
Controllers
- Controllers | NestJS - A progressive Node.js framework
- Nest.js controllers are responsible for handling HTTP requests and routing.
- For instance: The users.controller.ts file would define the routes and associated request handlers for the users feature.
@Controller('users')
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@Post()
create(@Body() createUserDto: CreateUserDto) {
return this.usersService.create(createUserDto);
}
@Get()
findAll() {
return this.usersService.findAll();
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.usersService.findOne(+id);
}
@Patch(':id')
update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) {
return this.usersService.update(+id, updateUserDto);
}
@Delete(':id')
remove(@Param('id') id: string) {
return this.usersService.remove(+id);
}
}
- Finally you need to add your controller to the respective module
@Module({
controllers: [CatsController],
})
export class AppModule {}
How to Change Response Status Code
- Controllers | NestJS - A progressive Node.js framework
- i.e by default 201 is returned from a post method
- ans: use @HttpCode(status_code), decorator
@Post()
@HttpCode(HttpStatus.GONE)
create(@Body() body) {
return body;
}
How to Gain Full Control of Req and Res
- Controllers | NestJS - A progressive Node.js framework
- use express, of fastify's, request and response arguments
- pros:
- can let us fully control response and request, such as set header
- cons
- not a standard way of doing things in next, might cause compatibility issue
- harder to test better to use nest standard response
import { Controller, Get, Post, Res, HttpStatus } from '@nestjs/common';
import { Response } from 'express';
@Controller('cats')
export class CatsController {
@Post()
create(@Res() res: Response) {
res.status(HttpStatus.CREATED).send();
}
@Get()
findAll(@Res() res: Response) {
res.status(HttpStatus.OK).json([]);
}
}