입력값 검증하기
Coddy Node.js 여정의 REST API 섹션에 포함된 레슨. 18개 중 6번째.
클라이언트는 본문에 무엇이든 보낼 수 있으며, if (!name)은 빈 값만 걸러냅니다. 123, true, ["x"]는 참으로 평가되어 통과하고, 공백으로만 이루어진 문자열도 문제가 없어 보입니다. 각 필드의 유형을 typeof로 확인한 다음, 허용 범위를 검사하세요.
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' });
}응답을 읽는 사람을 위한 메시지를 작성하세요. 필드 이름을 밝히고 어떤 값이어야 하는지 말해 주면, 무엇을 수정해야 하는지 알 수 있습니다. PATCH는 전송된 필드만 확인합니다. 나머지 필드는 변경되지 않기 때문입니다.
챌린지
쉬움- POST:
title은 공백만으로 이루어져 있지 않은 1~100자 길이의 문자열이어야 하며, 그렇지 않으면title을 명시하는error와 함께 400을 반환해야 합니다. - PATCH: 전송된 경우
title에도 동일한 규칙이 적용되며, 전송된done은true또는false여야 합니다.
{ "title": 123 }을 포함한 POST를 보낸 다음, { "done": "yes" }를 포함한 PATCH /api/tasks/2를 보내세요.
직접 해보기
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;
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.