Schemas with zod
Part of the REST APIs section of Coddy's Node.js journey. Lesson 7 of 18.
Hand checks grow with every field and every route. A zod schema describes the shape once, and safeParse tests a value against it:
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 holds the checked body, with name trimmed.strict() refuses fields the schema does not list. Event.partial() makes every field optional, which is what a PATCH needs, and Event.partial({ seats: true }) only seats. z.flattenError lists the problems by field. Event.parse does the same check but throws on a bad value, and a throw in a route becomes a 500.
Challenge
Easy- Replace the hand checks with a
Taskschema:titlea trimmed string of 1 to 100 characters,donea boolean,.strict(). - POST (
doneoptional, defaultfalse), PATCH (all optional) and PUT usesafeParse; a bad body answers 400 withz.flattenError(result.error)aserror.
Send POST with { "title": " Order new chairs ", "color": "red" }, then without color.
Try it yourself
import { Router } from 'express';
import { nextId, tasks } from '../store.js';
const router = Router();
// Why a title cannot be stored, or null when it can.
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;