Menu
CoddyTech

Проверка входных данных

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

Клиент может отправить в теле запроса что угодно, а if (!name) останавливает только пустые значения. 123, true и ["x"] являются истинными значениями и проходят дальше, а строка из пробелов выглядит допустимой. Проверяй тип каждого поля с помощью typeof, а затем проверяй его ограничения:

const { seats } = req.body ?? {};
if (typeof seats !== 'number' || !Number.isInteger(seats) || seats < 1) {
    return res.status(400).json({ error: 'seats must be a whole number from 1' });
}

Сформулируй сообщение для того, кто читает ответ: назови поле и укажи, каким оно должно быть, чтобы человек понял, что исправить. PATCH проверяет только те поля, которые ему передали, поскольку остальные не меняются.

challenge icon

Задание

Легко
  • POST: title должно быть строкой длиной от 1 до 100 символов, не состоящей только из пробелов; иначе вернётся 400 с error, указывающим на title.
  • PATCH: то же правило применяется к title, если оно передано, а done, если оно передано, должно быть равно true или false.

Отправьте POST с { "title": 123 }, затем PATCH /api/tasks/2 с { "done": "yes" }.

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

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.put('/: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' });
    }
    const { title, done } = req.body ?? {};
    if (title === undefined || done === undefined) {
        return res.status(400).json({ error: 'PUT needs every field: title and done' });
    }
    const { id, createdAt } = tasks[index];
    tasks[index] = { id, title, done, 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 res.status(404).json({ error: 'Task not found' });
    }
    tasks.splice(index, 1);
    res.status(204).end();
});

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

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

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