Menu
CoddyTech

Query Parameters

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

A client that wants only the open tasks should not have to download every task and filter them itself. The query string, the part after ?, carries options like that.

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

@Query('author') reads ?author=Le%20Guin, or gives undefined when the request has none.

TypeScript types are removed when the code runs: Node runs the JavaScript left after the types are stripped, and nothing checks them. Write inStock?: boolean and Nest still hands you the string 'false', which is truthy. The types document your code and help the editor; compare query values as text.

challenge icon

Challenge

Easy
  • GET /tasks?done=true answers only the finished tasks; GET /tasks?done=false only the open ones.
  • Without done, GET /tasks answers every task.
  • Send GET /tasks?done=false, then GET /tasks?done=true.

Try it yourself

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 iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in TypeScript and NestJS