Menu
CoddyTech

Parse Pipes

Part of the TypeScript and NestJS section of Coddy's Node.js journey. Lesson 13 of 17.

GET /tasks/abc answers 404 "Task NaN not found", but abc is not an id at all: that is a bad request, 400. Pipes can convert as well as check.

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

Passed as the second argument of a parameter decorator, ParseIntPipe turns the text into a number before the method runs. GET /reports?year=2026 passes the number 2026, so year: number is finally true; ?year=soon answers 400 "Validation failed (numeric string is expected)" and the method never runs. ParseBoolPipe and ParseUUIDPipe work the same way.

challenge icon

Challenge

Easy
  • GET /tasks/abc and DELETE /tasks/abc answer 400.
  • Numeric ids work as before; an unknown one still answers 404.
  • Send GET /tasks/abc, then GET /tasks/1, then GET /tasks/9999.

Try it yourself

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

All lessons in TypeScript and NestJS