Menu
CoddyTech

Конфликты

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

Вторая задача под названием «Отправить счёт» сбивает с толку, но её тело запроса корректно. Это 409 Conflict: запрос конфликтует с тем, что уже сохранено. Код 400 означает, что само тело запроса некорректно.

const taken = users.some((u) => u.name.toLowerCase() === name.toLowerCase());
if (taken) {
    return sendError(res, 409, 'conflict', 'That username is taken');
}

Сравнивайте в нижнем регистре, поскольку люди воспринимают «Ada» и «ada» как одно и то же имя. Если запрос переименовывает что-либо, пропустите сам элемент при поиске. Иначе пользователь, который сохраняет форму, не изменив имя, получит конфликт с самим собой.

challenge icon

Задание

Легко

Две задачи с названием "Send the invoice" делают список запутанным. Отклоняй название, которое уже есть у другой задачи.

  1. В routes/tasks.js сравнивай названия без учёта регистра: "Book the meeting room" и "book the MEETING room" считаются одинаковыми названиями.
  2. В POST после успешной проверки схемы: если у какой-либо задачи уже есть такое название, используй sendError, чтобы ответить со статусом 409, и ничего не добавляй:
    { "error": { "code": "conflict", "message": "A task with this title already exists" } }
  3. Сделай то же самое в PATCH (только если в теле запроса передан title) и в PUT. В этих двух маршрутах при поиске исключай изменяемую задачу, чтобы задача могла сохранить своё название или изменить только его регистр. Отклонённый запрос PATCH или PUT ничего не меняет.

Попробуй: отправь POST { "title": "book the meeting room" } на /api/tasks: получишь 409 с кодом conflict, потому что задача 2 называется "Book the meeting room". Отправь PATCH /api/tasks/3 с { "title": "Write the Project Brief" }: получишь 409, а GET /api/tasks/3 по-прежнему покажет "Send the invoice". Отправь PUT /api/tasks/2 с { "title": "Book the meeting room", "done": true }: получишь 200, потому что это название самой задачи 2. Отправь POST { "title": "Order new chairs" }: получишь 201.

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

import { Router } from 'express';
import { z } from 'zod';
import { sendError, sendInvalid } from '../errors.js';
import { nextId, tasks } from '../store.js';

const router = Router();

// Задача целиком, в том виде, в каком её отправляет PUT. .strict() отклоняет поля, которые не указаны в схеме.
const Task = z
    .object({
        title: z.string().trim().min(1).max(100),
        done: z.boolean(),
    })
    .strict();
const NewTask = Task.partial({ done: true });
const TaskChanges = Task.partial();

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 sendError(res, 404, 'not_found', 'Task not found');
    }
    res.json(task);
});

router.post('/', (req, res) => {
    const result = NewTask.safeParse(req.body);
    if (!result.success) {
        return sendInvalid(res, result.error);
    }
    const { title, done = false } = result.data;
    const task = { id: nextId(), title, done, 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 sendError(res, 404, 'not_found', 'Task not found');
    }
    const result = TaskChanges.safeParse(req.body);
    if (!result.success) {
        return sendInvalid(res, result.error);
    }
    Object.assign(task, result.data);
    res.json(task);
});

router.put('/:id', (req, res) => {
    const index = tasks.findIndex((t) => t.id === Number(req.params.id));
    if (index === -1) {
        return sendError(res, 404, 'not_found', 'Task not found');
    }
    const result = Task.safeParse(req.body);
    if (!result.success) {
        return sendInvalid(res, result.error);
    }
    const { id, createdAt } = tasks[index];
    tasks[index] = { id, ...result.data, createdAt };
    res.json(tasks[index]);
});

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

export default router;

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

Потренируйтесь самостоятельно: Песочница Express