Menu
CoddyTech

Schematy w zod

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

Ręczne sprawdzanie rozrasta się wraz z każdym polem i każdą trasą. Schemat zod opisuje strukturę raz, a safeParse sprawdza wartość pod tym kątem:

import { z } from 'zod';

const Event = z.object({
    name: z.string().trim().min(1).max(80),
    seats: z.number().int().min(1),
}).strict();

const result = Event.safeParse(req.body);
if (!result.success) {
    return res.status(400).json({ error: z.flattenError(result.error) });
}
// result.data zawiera zweryfikowaną treść żądania, z usuniętymi białymi znakami z początku i końca pola name

.strict() odrzuca pola, których nie ma na liście schematu. Event.partial() sprawia, że wszystkie pola są opcjonalne, czego wymaga PATCH, a Event.partial({ seats: true }) sprawia, że opcjonalne jest tylko seats. z.flattenError wylicza problemy dla poszczególnych pól. Event.parse wykonuje to samo sprawdzenie, ale zgłasza wyjątek dla nieprawidłowej wartości, a wyjątek w trasie skutkuje błędem 500.

challenge icon

Wyzwanie

Łatwy
  • Zastąp ręczne sprawdzanie schematem Task: title to przycięty ciąg znaków o długości od 1 do 100 znaków, done to wartość logiczna, .strict().
  • POST (done jest opcjonalne, domyślnie false), PATCH (wszystkie pola są opcjonalne) i PUT używają safeParse; w przypadku nieprawidłowego body zwracają status 400, a z.flattenError(result.error) — jako error.

Wyślij POST z { "title": " Order new chairs ", "color": "red" }, a następnie bez color.

Spróbuj swoich sił

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

const router = Router();

// Powód, dla którego nie można zapisać tytułu, lub null, gdy można go zapisać.
const titleError = (title) => {
    if (typeof title !== 'string' || title.trim() === '' || title.length > 100) {
        return 'title must be a string of 1 to 100 characters';
    }
    return null;
};

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 ?? {};
    const problem = titleError(title);
    if (problem) {
        return res.status(400).json({ error: problem });
    }
    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 && titleError(title)) {
        return res.status(400).json({ error: titleError(title) });
    }
    if (done !== undefined && typeof done !== 'boolean') {
        return res.status(400).json({ error: 'done must be true or false' });
    }
    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;

Wszystkie lekcje w sekcji API REST