Menu
CoddyTech

Route Parameters

Part of the TypeScript and NestJS section of Coddy's Node.js journey. Lesson 4 of 24.

A client often needs one task, not the whole list. A path can hold a parameter: a part that changes from request to request.

@Get(':isbn')
findOne(@Param('isbn') isbn: string) {
    return this.books.find((book) => book.isbn === isbn);
}

:isbn matches any value in that place of the path, so GET /books/978 reaches this method. @Param('isbn') hands that value to the method. It is always text: /books/42 gives the string '42', never the number 42.

Leave out the name and @Param() gives the object of every parameter, { isbn: '978' }, instead of the value.

challenge icon

Challenge

Easy

A client often wants one task, not the whole list. Add a route that returns one task by its id.

  1. In src/tasks/tasks.controller.ts, add a second method to TasksController (call it findOne) for GET /tasks/:id. :id stands for any value in that place of the path, so /tasks/2 reaches it.
  2. Read the id from the path with @Param('id'). Import Param from @nestjs/common.
  3. The id arrives as text, like "2", but the ids in this.tasks are numbers, and "2" === 2 is false. Turn the id into a number before you compare.
  4. Return the task with that id.
  5. Leave GET /tasks as it is: it still returns the whole list.

Try it: send GET /tasks/2. You get 200 and:

{ "id": 2, "title": "Fix the login bug", "done": false }

Send GET /tasks/1 and GET /tasks/3 too. Then send GET /tasks/99. No task has that id, so your method returns nothing, and Nest responds with 200 and an empty body. That is expected for now. It tells the client nothing, and a later lesson fixes it.

Try it yourself

import { Controller, Get } 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;
    }
}

All lessons in TypeScript and NestJS

Practice on your own: Express playground