Girdiyi Doğrulama
Coddy'nin Node.js Journey'sinin REST API'leri bölümünün bir parçası. Ders 6 / 18.
Bir istemci, gövdede herhangi bir şey gönderebilir ve if (!name) yalnızca boş değerleri engeller. 123, true ve ["x"] doğruluk değeri taşıdığından kontrolleri geçer; boşluklardan oluşan bir dize de uygun görünür. Her alanın türünü typeof ile, ardından sınırlarını denetleyin:
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' });
}Yanıtı okuyacak kişi için mesajı yazın: alanı belirtin ve hangi koşulu sağlaması gerektiğini söyleyin; böylece neyi düzeltmesi gerektiğini bilir. PATCH yalnızca gönderilen alanları denetler, çünkü diğer alanlar değiştirilmiyordur.
Görev
Kolay- POST:
title1 ila 100 karakter uzunluğunda, yalnızca boşluklardan oluşmayan bir dize olmalıdır; aksi hâldetitleadını belirten birerrorile 400 döner. - PATCH: Gönderildiğinde
titleiçin aynı kural geçerlidir ve gönderildiğindedone,trueveyafalseolmalıdır.
{ "title": 123 } ile POST gönderin, ardından { "done": "yes" } ile PATCH /api/tasks/2 gönderin.
Kendin dene
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;
Bu ders kısa bir quiz içerir. Soruları yanıtlamak ve ilerlemeni kaydetmek için derse başla.