29. A Tríade do NestJS: Modules, Controllers e Providers (Services)
Módulo 4: NestJS Framework & Arquitetura Empresarial
45 min de leitura técnica
Nível Intermediário
45 min de leitura técnica
Nível Intermediário
📑 Índice do Conteúdo
1. Controllers Declarativos com Decorators HTTP
No NestJS, rotas HTTP são definidas de forma declarativa e limpa através de decorators TypeScript (@Get(), @Post(), @Put(), @Delete(), @Param(), @Body() e @Query()):
typescript
src/users/users.controller.ts — Controller NestJS
src/users/users.controller.ts — Controller NestJS
import { Controller, Get, Post, Body, Param, HttpCode, HttpStatus } from '@nestjs/common';
import { UsersService } from './users.service';
@Controller('users')
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@Get()
async findAll() {
return this.usersService.findAll();
}
@Get(':id')
async findOne(@Param('id') id: string) {
return this.usersService.findById(id);
}
@Post()
@HttpCode(HttpStatus.CREATED)
async create(@Body() createUserDto: any) {
return this.usersService.create(createUserDto);
}
}
2. A Camada de Serviços com @Injectable()
typescript
src/users/users.service.ts — Serviço Injetável
src/users/users.service.ts — Serviço Injetável
import { Injectable, NotFoundException } from '@nestjs/common';
@Injectable()
export class UsersService {
private users = [
{ id: '1', name: 'Ana Silva', email: '[email protected]' }
];
findAll() {
return this.users;
}
findById(id: string) {
const user = this.users.find(u => u.id === id);
if (!user) {
throw new NotFoundException('Usuário não encontrado');
}
return user;
}
create(dto: any) {
const newUser = { id: String(Date.now()), ...dto };
this.users.push(newUser);
return newUser;
}
}
Pratique Agora no Playground IDE
Experimente estruturas de classes e construtores tipados no Playground Web IDE.
🛠️ Laboratório Prático & Prática Imediata
Aplique o que você aprendeu nesta lição
Utilize nossas ferramentas online gratuitas para experimentar os conceitos ou teste o código ao vivo no Playground IDE.
💻
Desenvolvedor & Código
Editor de Códigos Web Online
Ambiente com destaque de sintaxe para você testar tags, tabelas e scripts na hora.
Abrir Ferramenta Online
⚡
Live Code Studio
Playground Web Online
Escreva seu código HTML, CSS ou JavaScript e veja o resultado renderizado ao vivo no navegador com zero configuração.
⚡ Codificar no Playground IDE