Hello, Nest
Part of the TypeScript and NestJS section of Coddy's Node.js journey. Lesson 1 of 17.
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: labels Nest reads when the app starts. Together they map findAll to GET /books, and Nest sends what the method returns as JSON with status 200. A method without a decorator is never called.
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.
Challenge
Easy- Add a method to
TasksControllerthat answersGET /taskswith thetasksarray. - Press Run and send
GET /tasks, thenGET /taskto see what a path without a route answers.
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.