Skip to main content

102. Controllers

Controllers

@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

  @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([]);
}
}