Hello, Nest
Part of the TypeScript and NestJS section of Coddy's Node.js journey. Lesson 2 of 24.
In Express every route is a function you register by hand. NestJS gives each part of an API its own class, and decorators tell Nest what each class does.
@Controller('books')
export class BooksController {
@Get()
findAll() {
return [{ title: 'Dune' }];
}
}A controller answers the requests for one path. @Controller('books') and @Get() are decorators. A decorator starts with @ and sits on the line above a class or a method, telling Nest what it is for. Nest's decorators always end in (), even when nothing goes inside. Together they map findAll to GET /books, and Nest sends what the method returns as JSON with status 200. Nest never sends a request to a method that has no route decorator.
A module lists the classes that belong together. src/main.ts calls NestFactory.create(AppModule); AppModule imports TasksModule, which lists TasksController. On a laptop you would start it with npm run start; here Run does it.
In the starter, interface Task describes the fields of a task object, and Task[] means an array of them. private keeps a field inside its class. A type after a method’s parentheses describes its returned value. These annotations help TypeScript check your code; Nest’s decorators define the routes.
Challenge
EasyYour first Nest server already holds three tasks, but no route returns them yet. Add the route that lists them.
- Open
src/tasks/tasks.controller.ts. The classTasksControllerholds the list inthis.tasks.@Controller('tasks')above the class puts it in charge of paths under/tasks. - Where the comment is, add a method (call it
findAll) and mark it with@Get(). It returnsthis.tasks. Nest sends what the method returns as JSON, with status 200. Getcomes from@nestjs/common, likeController. Add it to the import on the first line.
Try it: press Run, then send GET /tasks. You get 200 and the three tasks:
[
{ "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 }
]Then send GET /task, without the s. No route matches that path, so Nest responds with 404:
{ "message": "Cannot GET /task", "error": "Not Found", "statusCode": 404 }Try it yourself
import { Controller } 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 },
];
// Add a method here that answers GET /tasks with the list.
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in TypeScript and NestJS
Practice on your own: Express playground