Asenkron Rotalar
Coddy'nin Node.js Journey'sinin Express Temelleri bölümünün bir parçası. Ders 18 / 20.
Sunucu yeniden başlatıldığında dizi kaybolur. Dosya verileri saklar.
import { readFile } from 'node:fs/promises';
app.get('/api/forecast', async (req, res) => {
const text = await readFile('data/forecast.json', 'utf8');
res.json(JSON.parse(text));
});Bir rota, burada node:fs/promises içindeki readFile için await ile bekleyen bir async işlev olabilir. Express 5, rotanın döndürdüğü promise'i izler: dosya bulunamadığı veya JSON'u bozuk olduğu için promise reddedilirse hata, bir throw gibi hata işleyicinize gider.
await olmadan veriler yerine bir promise elde edersiniz ve res.json(promise), {} gönderir. Yeni data/recipes.json dosyasında dört tarif bulunur.
Görev
Kolayroutes/recipes.jsiçindeki her rota, her istekte tarifleridata/recipes.jsondosyasından okur.POST, yeni listeyiwriteFileile geri kaydeder.
Bir tarif gönderin, ardından GET /api/recipes, GET /api/recipes/5 ve GET /api/recipes/99 isteklerini gönderin.
Kendin dene
import express from 'express';
import { recipes } from '../data.js';
const router = express.Router();
// Her etiket bir kez, alfabetik sırayla.
router.get('/tags', (req, res) => {
const tags = new Set(recipes.flatMap((recipe) => recipe.tags));
res.json([...tags].sort());
});
router.get('/', (req, res) => {
res.json(recipes);
});
router.get('/:id', (req, res) => {
const recipe = recipes.find((r) => r.id === Number(req.params.id));
if (!recipe) {
res.status(404).json({ error: 'No such recipe' });
return;
}
res.json(recipe);
});
router.post('/', (req, res) => {
const { title, tags } = req.body;
if (!title) {
res.status(400).json({ error: 'A recipe needs a title' });
return;
}
const recipe = { id: recipes.length + 1, title, tags: tags ?? [] };
recipes.push(recipe);
res.status(201).json(recipe);
});
router.get('/:id/scale', (req, res) => {
const recipe = recipes.find((r) => r.id === Number(req.params.id));
if (!recipe) {
res.status(404).json({ error: 'No such recipe' });
return;
}
const by = Number(req.query.by);
if (!Number.isFinite(by) || by <= 0) {
res.status(400).json({ error: 'Scale by a positive number' });
return;
}
if (!recipe.servings) {
throw new Error(`Recipe ${recipe.id} has no servings`);
}
res.json({ title: recipe.title, servings: recipe.servings * by });
});
export default router;
Bu ders kısa bir quiz içerir. Soruları yanıtlamak ve ilerlemeni kaydetmek için derse başla.