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
EasyA client often wants one task, not the whole list. Add a route that returns one task by its id.
- In
src/tasks/tasks.controller.ts, add a second method toTasksController(call itfindOne) forGET /tasks/:id.:idstands for any value in that place of the path, so/tasks/2reaches it. - Read the id from the path with
@Param('id'). ImportParamfrom@nestjs/common. - The id arrives as text, like
"2", but the ids inthis.tasksare numbers, and"2" === 2is false. Turn the id into a number before you compare. - Return the task with that id.
- Leave
GET /tasksas 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
1Nest Basics
Classes and MethodsHello, NestRegistering a Controller4Guards, Filters, Interceptors
GuardsPractice on your own: Express playground