Pipes de Parse
Parte da seção TypeScript e NestJS do Journey de Node.js da Coddy. Lição 13 de 17.
GET /tasks/abc responde com 404 "Task NaN not found", mas abc não é um ID: isso é uma solicitação inválida, 400. Os pipes podem converter além de verificar.
@Get()
findAll(@Query('year', ParseIntPipe) year: number) {
return this.reportsService.forYear(year);
}Passado como segundo argumento de um decorador de parâmetro, ParseIntPipe transforma o texto em um número antes de o método ser executado. GET /reports?year=2026 passa o número 2026, então year: number finalmente é verdadeiro; ?year=soon responde com 400 "Validation failed (numeric string is expected)" e o método nunca é executado. ParseBoolPipe e ParseUUIDPipe funcionam da mesma maneira.
Desafio
FácilGET /tasks/abceDELETE /tasks/abcretornam 400.- IDs numéricos funcionam como antes; um ID desconhecido ainda retorna 404.
- Envie
GET /tasks/abc, depoisGET /tasks/1e, em seguida,GET /tasks/9999.
Experimente você mesmo
import { Body, Controller, Delete, Get, HttpCode, Inject, Param, Post, Query } from '@nestjs/common';
import { CreateTaskDto } from './dto/create-task.dto';
import { Task, TasksService } from './tasks.service';
@Controller('tasks')
export class TasksController {
constructor(
private readonly tasksService: TasksService,
@Inject('PAGE_SIZE') private readonly pageSize: number,
) {}
@Get()
findAll(@Query('done') done?: string, @Query('page') page = '1') {
const tasks = this.tasksService.findAll(done);
const current = Number(page);
const start = (current - 1) * this.pageSize;
return {
items: tasks.slice(start, start + this.pageSize),
page: current,
total: tasks.length,
pages: Math.ceil(tasks.length / this.pageSize),
};
}
@Get(':id')
findOne(@Param('id') id: string): Task {
return this.tasksService.findOne(Number(id));
}
@Post()
create(@Body() dto: CreateTaskDto): Task {
return this.tasksService.create(dto);
}
@Delete(':id')
@HttpCode(204)
remove(@Param('id') id: string): void {
this.tasksService.remove(Number(id));
}
}