Menu
CoddyTech

Pipe di parsing

Fa parte della sezione TypeScript e NestJS del percorso Node.js di Coddy. Lezione 13 di 17.

GET /tasks/abc risponde con 404 "Task NaN not found", ma abc non è affatto un id: è una richiesta non valida, 400. Le pipe possono convertire oltre che verificare.

@Get()
findAll(@Query('year', ParseIntPipe) year: number) {
    return this.reportsService.forYear(year);
}

Passato come secondo argomento di un decoratore di parametri, ParseIntPipe trasforma il testo in un numero prima che venga eseguito il metodo. GET /reports?year=2026 passa il numero 2026, quindi year: number è finalmente vero; ?year=soon risponde con 400 "Validation failed (numeric string is expected)" e il metodo non viene mai eseguito. ParseBoolPipe e ParseUUIDPipe funzionano allo stesso modo.

challenge icon

Sfida

Facile
  • GET /tasks/abc e DELETE /tasks/abc restituiscono 400.
  • Gli id numerici funzionano come prima; uno sconosciuto restituisce comunque 404.
  • Invia GET /tasks/abc, poi GET /tasks/1, poi GET /tasks/9999.

Provalo tu

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));
    }
}

Tutte le lezioni di TypeScript e NestJS