Menu
CoddyTech

Validare l'input

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

Un client può inviare qualsiasi cosa nel corpo della richiesta e if (!name) blocca solo i valori vuoti. 123, true e ["x"] sono truthy e passano, mentre una stringa di spazi sembra valida. Controlla il tipo di ogni campo con typeof, poi i suoi limiti:

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

Scrivi il messaggio per chi legge la risposta: indica il campo e spiega come deve essere, così saprà cosa correggere. Una PATCH controlla solo i campi che le sono stati inviati, poiché gli altri non stanno cambiando.

challenge icon

Sfida

Facile
  • POST: title deve essere una stringa da 1 a 100 caratteri, non composta solo da spazi, altrimenti viene restituito un errore 400 con un error che indica title.
  • PATCH: lo stesso vale per title quando viene inviato e done, quando viene inviato, deve essere true oppure false.

Invia una richiesta POST con { "title": 123 }, poi PATCH /api/tasks/2 con { "done": "yes" }.

Provalo tu

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 iconMettiti alla prova

Questa lezione include un breve quiz. Inizia la lezione per rispondere e tenere traccia dei tuoi progressi.

Tutte le lezioni di API REST