非同期ルート
CoddyのNode.jsジャーニー「Expressの基礎」セクションの一部。レッスン 18/20。
サーバーが再起動すると、配列の内容は消えます。ファイルならデータを保持できます。
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));
});ルートは、ここでは node:fs/promises の readFile の完了を待つために await を使う async 関数にできます。Express 5 はルートが返すプロミスを監視します。ファイルが見つからない場合や JSON が壊れている場合など、プロミスが拒否されると、throw のようにエラーがエラーハンドラーに渡されます。
await を使わないと、データではなくプロミスを受け取ることになり、res.json(promise) は {} を送信します。新しい data/recipes.json には4つのレシピが入っています。
チャレンジ
簡単routes/recipes.js内の各ルートは、リクエストごとにdata/recipes.jsonからレシピを読み込みます。POSTは、新しいリストをwriteFileで書き戻します。
レシピを投稿し、続けてGET /api/recipes、GET /api/recipes/5、GET /api/recipes/99を送信します。
自分で試してみよう
import express from 'express';
import { recipes } from '../data.js';
const router = express.Router();
// すべてのタグを重複なく、アルファベット順に。
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;
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。