zod로 스키마 정의하기
Coddy Node.js 여정의 REST API 섹션에 포함된 레슨. 18개 중 7번째.
수동 검사는 필드와 경로가 늘어날 때마다 복잡해집니다. zod 스키마는 형태를 한 번 설명하고, safeParse는 값이 그 형태에 맞는지 검사합니다:
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에는 검증된 body가 들어 있으며, name의 앞뒤 공백은 제거되어 있습니다.strict()는 스키마에 없는 필드를 거부합니다. Event.partial()은 모든 필드를 선택 사항으로 만드는데, 이것이 PATCH에 필요한 동작입니다. Event.partial({ seats: true })는 seats만 선택 사항으로 만듭니다. z.flattenError는 필드별 문제를 나열합니다. Event.parse도 같은 검사를 수행하지만 잘못된 값이면 예외를 발생시키며, 경로에서 예외가 발생하면 500 오류가 됩니다.
챌린지
쉬움- 직접 작성한 검사를
Task스키마로 대체합니다.title은 공백을 제거한 1~100자 문자열이고,done은 불리언이며,.strict()를 사용합니다. - POST(
done은 선택 사항이며 기본값은false), PATCH(모두 선택 사항), PUT은safeParse를 사용합니다. 잘못된 본문에는z.flattenError(result.error)를error로 담아 400을 응답합니다.
{ "title": " Order new chairs ", "color": "red" }로 POST 요청을 보낸 다음, color 없이 보냅니다.
직접 해보기
import { Router } from 'express';
import { nextId, tasks } from '../store.js';
const router = Router();
// title을 저장할 수 없는 이유를 반환하고, 저장할 수 있으면 null을 반환합니다.
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;