Route Parameters
Part of the TypeScript and NestJS section of Coddy's Node.js journey. Lesson 2 of 17.
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
Easy- Add
GET /tasks/:id: it answers the task with that id. - Send
GET /tasks/2, thenGET /tasks/99and look at what an id with no task answers.
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;
}
}