Creating Tasks
Part of the TypeScript and NestJS section of Coddy's Node.js journey. Lesson 6 of 24.
A client that creates a task sends it as JSON in the request body, and needs the saved task back.
@Post()
create(@Body() review: { stars: number }) {
this.reviews.push(review);
return review;
}@Post() maps POST on the controller's path to the method, and @Body() hands it the parsed JSON. Nest reads JSON bodies on its own, so there is no express.json() to add.
Nest answers a POST with 201 Created, the status that says a new resource exists, and every other method with 200. @HttpCode(200) on the method would change it; for a create, leave it.
Challenge
EasyClients need to add tasks, not only read them. Add a route that creates a task from the JSON the client sends.
- In
src/tasks/tasks.controller.ts, add a method toTasksController(call itcreate) forPOST /tasks. Mark it with@Post(), and read the JSON body with@Body()on its parameter. Both come from@nestjs/common. - Build the new task from the body's
title. Give it anidthat no other task has: one more than the largest id inthis.tasks. A new task is never done, sodoneisfalse. - Add the task to
this.tasks, so thatGET /tasksandGET /tasks/:idfind it later. Return the new task. - Do not set a status yourself. Nest responds to a POST with 201 Created on its own.
Try it: choose POST, path /tasks, and the body { "title": "Buy milk" }. You get 201 and:
{ "id": 4, "title": "Buy milk", "done": false }Send GET /tasks/4: the same task. Then POST an empty body, {}. Nothing checks the body yet, so you still get 201, with a task that has no title: { "id": 5, "done": false }. The Validation chapter fixes that.
Try it yourself
import { Controller, Get, Param, Query } 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(@Query('done') done?: string): Task[] {
if (done === undefined) {
return this.tasks;
}
return this.tasks.filter((task) => task.done === (done === 'true'));
}
@Get(':id')
findOne(@Param('id') id: string): Task | undefined {
return this.tasks.find((task) => task.id === Number(id));
}
}
All lessons in TypeScript and NestJS
1Nest Basics
Classes and MethodsHello, NestRegistering a Controller4Guards, Filters, Interceptors
GuardsPractice on your own: Express playground