Menu
CoddyTech

Замена с помощью PUT

Часть раздела REST API путешествия по Node.js на Coddy. Урок 5 из 18.

Форма редактирования отправляет обратно всю задачу, сразу со всеми полями. PUT означает «заменить ресурс на этот», поэтому тело запроса должно быть полным.

PATCH /api/invoices/7  { "paid": true }               → paid changes
PUT   /api/invoices/7  { "amount": 90, "paid": true } → a new invoice 7
PUT   /api/invoices/7  { "paid": true }               → 400: amount missing

Запрос PUT с пропущенным полем приводит к ответу 400: замена половиной счета привела бы к потере суммы. Поля, которыми управляет сервер, например id и время создания, берутся из старой версии, а не из тела запроса:

const { id, issuedAt } = invoices[index];
invoices[index] = { id, amount, paid, issuedAt };
challenge icon

Задание

Легко
  • PUT /api/tasks/:id заменяет title и done значениями из тела запроса и возвращает задачу с кодом 200.
  • id и createdAt остаются без изменений.
  • Отсутствует title или done: 400. Неизвестный идентификатор: 404.

Отправь PUT /api/tasks/2 с { "title": "Book the big room", "done": true }, а затем с { "done": true }.

Попробуйте сами

import { Router } from 'express';
import { nextId, tasks } from '../store.js';

const router = Router();

router.get('/', (req, res) => {
    res.json(tasks);
});

router.get('/:id', (req, res) => {
    const task = tasks.find((t) => t.id === Number(req.params.id));
    if (!task) {
        return res.status(404).json({ error: 'Task not found' });
    }
    res.json(task);
});

router.post('/', (req, res) => {
    const { title } = req.body ?? {};
    if (!title) {
        return res.status(400).json({ error: 'title is required' });
    }
    const task = { id: nextId(), title, done: false, createdAt: new Date().toISOString() };
    tasks.push(task);
    res.status(201).location(`/api/tasks/${task.id}`).json(task);
});

router.patch('/:id', (req, res) => {
    const task = tasks.find((t) => t.id === Number(req.params.id));
    if (!task) {
        return res.status(404).json({ error: 'Task not found' });
    }
    const { title, done } = req.body ?? {};
    if (title !== undefined) task.title = title;
    if (done !== undefined) task.done = done;
    res.json(task);
});

router.delete('/:id', (req, res) => {
    const index = tasks.findIndex((t) => t.id === Number(req.params.id));
    if (index === -1) {
        return res.status(404).json({ error: 'Task not found' });
    }
    tasks.splice(index, 1);
    res.status(204).end();
});

export default router;
quiz iconПроверьте себя

В этом уроке есть небольшой тест. Начните урок, чтобы ответить на вопросы и сохранить прогресс.

Все уроки раздела REST API