Menu
CoddyTech

Walidacja danych wejściowych

Część sekcji API REST ścieżki Node.js w Coddy. Lekcja 6 z 18.

Klient może wysłać cokolwiek w treści żądania, a if (!name) odrzuca tylko puste wartości. 123, true i ["x"] są wartościami prawdziwymi i przechodzą dalej, a ciąg spacji wygląda poprawnie. Sprawdź typ każdego pola za pomocą typeof, a następnie jego ograniczenia:

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

Napisz komunikat z myślą o osobie, która czyta odpowiedź: wskaż pole i powiedz, jakie musi być, aby wiedziała, co poprawić. Żądanie PATCH sprawdza tylko pola, które zostały w nim przesłane, ponieważ pozostałe się nie zmieniają.

challenge icon

Wyzwanie

Łatwy
  • POST: title musi być ciągiem znaków o długości od 1 do 100 znaków, zawierającym coś więcej niż same spacje, w przeciwnym razie zwracany jest kod 400 z error wskazującym title.
  • PATCH: to samo dotyczy title, gdy zostanie przesłane, a done, gdy zostanie przesłane, musi mieć wartość true lub false.

Wyślij POST z { "title": 123 }, a następnie PATCH /api/tasks/2 z { "done": "yes" }.

Spróbuj swoich sił

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 iconSprawdź się

Ta lekcja zawiera krótki quiz. Zacznij lekcję, żeby na niego odpowiedzieć i śledzić swoje postępy.

Wszystkie lekcje w sekcji API REST