Menu
CoddyTech

יצירת משימות

חלק מהיחידה TypeScript ו-NestJS במסלול ה-Node.js של Coddy. שיעור 4 מתוך 17.

לקוח שיוצר משימה שולח אותה כ-JSON בגוף הבקשה, וזקוק לקבל בחזרה את המשימה שנשמרה.

@Post()
create(@Body() review: { stars: number }) {
    this.reviews.push(review);
    return review;
}

@Post() ממפה את POST בנתיב של הבקר למתודה, ו-@Body() מעביר לה את ה-JSON שפוענח. Nest קורא גופי JSON בעצמו, ולכן אין צורך להוסיף express.json().

Nest משיב לבקשת POST עם 201 Created, קוד המצב שמציין שמשאב חדש קיים, ולכל שאר המתודות עם 200. @HttpCode(200) במתודה ישנה זאת; במקרה של יצירה, השאר אותו כפי שהוא.

challenge icon

אתגר

קל
  • POST /tasks עם { "title": "Buy milk" } מחזיר 201 עם המשימה החדשה: מספר id חדש, ה-title ו-done: false.
  • GET /tasks/:id מוצא אותה לאחר מכן.
  • שלחו את הבקשה הזאת, ואז שלחו POST /tasks עם {} וראו מה נשמר.

נסו בעצמכם

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));
    }
}

כל השיעורים ביחידה TypeScript ו-NestJS