Menu
CoddyTech

Parámetros de consulta

Parte de la sección TypeScript y NestJS del Journey de Node.js de Coddy. Lección 3 de 17.

Un cliente que solo quiere las tareas abiertas no debería tener que descargar todas las tareas y filtrarlas por su cuenta. La cadena de consulta, la parte que va después de ?, incluye opciones como esa.

@Get()
findAll(@Query('author') author?: string) {
    if (!author) {
        return this.books;
    }
    return this.books.filter((book) => book.author === author);
}

@Query('author') lee ?author=Le%20Guin o devuelve undefined cuando la solicitud no incluye ninguno.

Los tipos de TypeScript se eliminan cuando se ejecuta el código: Node ejecuta el JavaScript que queda después de quitar los tipos, y nada los comprueba. Escribe inStock?: boolean y Nest aun así te entrega la cadena 'false', que es verdadera en un contexto booleano. Los tipos documentan tu código y ayudan al editor; compara los valores de consulta como texto.

challenge icon

Desafío

Fácil
  • GET /tasks?done=true devuelve solo las tareas completadas; GET /tasks?done=false, solo las que están abiertas.
  • Sin done, GET /tasks devuelve todas las tareas.
  • Envía GET /tasks?done=false y después GET /tasks?done=true.

Pruébalo tú mismo

import { Controller, Get, Param } from '@nestjs/common';

interface Task {
    id: number;
    title: string;
    done: boolean;
}

@Controller('tasks')
export class TasksController {
    private tasks: Task[] = [
        { id: 1, title: 'Write the README', done: true },
        { id: 2, title: 'Fix the login bug', done: false },
        { id: 3, title: 'Plan the sprint', done: false },
    ];

    @Get()
    findAll(): Task[] {
        return this.tasks;
    }

    @Get(':id')
    findOne(@Param('id') id: string): Task | undefined {
        return this.tasks.find((task) => task.id === Number(id));
    }
}
quiz iconPonte a prueba

Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.

Todas las lecciones de TypeScript y NestJS