Creating Tasks
Part of the TypeScript and NestJS section of Coddy's Node.js journey. Lesson 4 of 17.
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
EasyPOST /taskswith{ "title": "Buy milk" }answers 201 with the new task: a new numberid, thetitleanddone: false.GET /tasks/:idfinds it afterwards.- Send that request, then send
POST /taskswith{}and see what gets saved.
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));
}
}