Menu
CoddyTech

Schemi con zod

Fa parte della sezione API REST del percorso Node.js di Coddy. Lezione 7 di 18.

I controlli manuali aumentano con ogni campo e ogni route. Uno schema zod descrive la struttura una sola volta e safeParse verifica un valore rispetto a essa:

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 contiene il body validato, con name privato degli spazi iniziali e finali

.strict() rifiuta i campi che lo schema non elenca. Event.partial() rende facoltativo ogni campo, come richiesto da una PATCH, mentre Event.partial({ seats: true }) rende facoltativo solo seats. z.flattenError elenca i problemi per campo. Event.parse esegue lo stesso controllo, ma genera un'eccezione in caso di valore non valido; un'eccezione in una route si traduce in un errore 500.

challenge icon

Sfida

Facile
  • Sostituisci i controlli manuali con uno schema Task: title è una stringa senza spazi iniziali o finali, da 1 a 100 caratteri, done è un booleano, .strict().
  • POST (done facoltativo, predefinito false), PATCH (tutti i campi facoltativi) e PUT usano safeParse; un corpo non valido restituisce 400 con z.flattenError(result.error) come error.

Invia una richiesta POST con { "title": " Order new chairs ", "color": "red" }, poi senza color.

Provalo tu

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

const router = Router();

// Il motivo per cui un title non può essere memorizzato, oppure null se può esserlo.
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;

Tutte le lezioni di API REST