Menu
CoddyTech

המתכון היומי

חלק מהיחידה יסודות Express במסלול ה-Node.js של Coddy. שיעור 22 מתוך 23.

תיבת המתכונים יכולה להשתמש במיומנויות מוכרות של ניתוב וקריאת קבצים כדי להגיש מתכון אחד לכל יום. פונקציית העזר dayOfYear שסופקה ממירה תאריך למספר: 1 בינואר הוא 1 ו־1 במרץ 2026 הוא 60. תאריך חסר פירושו היום; טקסט שלא ניתן לקרוא מחזיר null.

const day = dayOfYear(req.query.date);
// ?date=2026-03-01 מחזיר 60
// ?date=soon מחזיר null

השתמשו באופרטור השארית כדי לבחור מיקום: day % recipes.length. עם ארבעה מתכונים, יום 60 בוחר במיקום אפס. טענו את המתכונים בתוך הבקשה כדי שגם מתכונים שפורסמו לאחרונה ייכללו. פענוח התאריך כבר סופק; התמקדו בהרכבת הנתיב.

challenge icon

אתגר

קל

הוסף נקודת קצה למתכון היום ב-Recipe Box. הקובץ שסופק day-of-year.js מייצא את dayOfYear(text), שמחזירה את מספר היום או null עבור תאריך לא תקין.

  1. ייצא את loadRecipes מתוך routes/recipes.js. ייבא אותו אל server.js: הנתב נשאר הייבוא כברירת מחדל, ואחריו, לאחר פסיק, { loadRecipes }.
  2. ייבא את dayOfYear. ב-server.js, מעל מטפל ה-404, הוסף נתיב async עבור GET /api/today. העבר לפונקציית העזר את req.query.date.
  3. עבור null, החזר 400 עם {"error":"Use a date like 2026-03-01"}.
  4. אחרת, המתן ל-loadRecipes() והחזר את recipes[day % recipes.length] כ-JSON. השאר את הנתיבים הקיימים ואת מטפל השגיאות.

נסה GET /api/today?date=2026-03-01: הוא מחזיר את המתכון הראשון, כי מספר היום הוא 60 ויש ארבעה מתכונים. נסה ?date=soon: הוא מחזיר את שגיאת 400 שלמעלה.

נסו בעצמכם

import { escapeHtml } from './html.js';
import express from 'express';
import { randomUUID } from 'node:crypto';
import { recipes } from './data.js';
import recipesRouter from './routes/recipes.js';
import reviewsRouter from './routes/reviews.js';

const app = express();

app.use((req, res, next) => {
    console.log(`${req.method} ${req.url}`);
    next();
});

app.use((req, res, next) => {
    res.set('X-Request-Id', randomUUID());
    next();
});

app.use(express.json());

app.use(express.static('public'));

app.get('/', (req, res) => {
    const items = recipes.map((r) => `<li><a href="/recipes/${r.id}">${escapeHtml(r.title)}</a></li>`);
    res.send(`<link rel="stylesheet" href="/style.css"><h1>Recipe Box</h1><ul>${items.join('')}</ul>`);
});

// type('text') שולחת טקסט פשוט, כך שכל כותרת מופיעה בשורה נפרדת.
app.get('/recipes', (req, res) => {
    const { tag } = req.query;
    const list = tag ? recipes.filter((recipe) => recipe.tags.includes(tag)) : recipes;
    res.type('text').send(list.map((recipe) => recipe.title).join('\n'));
});

app.get('/recipes/:id', (req, res) => {
    const recipe = recipes.find((r) => r.id === Number(req.params.id));
    if (!recipe) {
        res.status(404).send('No such recipe');
        return;
    }
    res.send(recipe.title);
});

app.use('/api/recipes', recipesRouter);
app.use('/api/recipes/:id/reviews', reviewsRouter);

app.get('/about', (req, res) => {
    res.send('Recipe Box collects family recipes.');
});

app.get('/menu', (req, res) => {
    res.redirect(301, '/recipes');
});

app.get('/menu/:id', (req, res) => {
    res.redirect(301, `/recipes/${req.params.id}`);
});

app.use((req, res) => {
    if (req.path.startsWith('/api/')) {
        res.status(404).json({ error: 'Not found' });
        return;
    }
    res.status(404).send('<h1>Page not found</h1><p><a href="/">Back to Recipe Box</a></p>');
});

app.use((err, req, res, next) => {
    console.error(err);
    res.status(500).json({ error: 'Something went wrong' });
});

app.listen(3000, () => {
    console.log('Recipe Box is running on port 3000');
});

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

תרגלו בעצמכם: Express אונליין