Menu
CoddyTech

נתיבים אסינכרוניים

חלק מהיחידה יסודות Express במסלול ה-Node.js של Coddy. שיעור 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));
});

נתיב יכול להיות פונקציה מסוג async שממתינה באמצעות await, במקרה הזה ל־readFile מתוך node:fs/promises. Express 5 עוקב אחר ההבטחה שהנתיב מחזיר: אם היא נדחית, כי הקובץ חסר או שה־JSON שלו פגום, השגיאה עוברת למטפל השגיאות שלך, כמו בזריקת שגיאה.

בלי await נשארת לך הבטחה במקום הנתונים, ו־res.json(promise) שולח {}. הקובץ החדש data/recipes.json מכיל את ארבעת המתכונים.

challenge icon

אתגר

קל
  • כל נתיב בקובץ 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;
quiz iconבחנו את עצמכם

השיעור הזה כולל חידון קצר. התחילו את השיעור כדי לענות עליו ולעקוב אחרי ההתקדמות.

כל השיעורים ביחידה יסודות Express