Menu
CoddyTech

המתכון היומי

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

תיבת המתכונים מקבלת מתכון יומי: אותו מתכון לכולם לאורך כל היום, ומתכון אחר מחר. התאריך בוחר אותו, ו-?date= מאפשר לך לנסות כל יום.

new Date('2026-03-01') הוא חצות לפי UTC באותו יום. ספירת הימים בשנה מתחילה ב-31 בדצמבר, לכן 1 בינואר הוא יום 1: (date - Date.UTC(year, 0, 0)) / 86400000, מכיוון שביממה יש 86,400,000 מילישניות. טקסט שאינו תאריך יוצר תאריך לא תקין, שה-getTime() שלו הוא NaN.

הוסף את הנתיב ב-server.js, מעל המטפל ב-404. בחר מתוך המתכונים שב-data/recipes.json, כפי שה-API עושה, כדי שמתכון שמישהו מפרסם יוכל להיות המתכון היומי: ייצא את loadRecipes מתוך routes/recipes.js והמתן לו.

challenge icon

אתגר

קל
  • GET /api/today?date=2026-03-01 מחזיר את recipes[day % recipes.length] כ-JSON, כאשר recipes מגיע מ-loadRecipes() ו-day הוא היום בשנה.
  • בלי date: היום.
  • תאריך שלא ניתן לפענח: 400 עם { "error": "Use a date like 2026-03-01" }.

שלחו פעמיים ?date=2026-03-01, ואז ?date=soon.

נסו בעצמכם

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'));

const escapeHtml = (text) =>
    text
        .replaceAll('&', '&')
        .replaceAll('<', '&lt;')
        .replaceAll('>', '&gt;')
        .replaceAll('"', '&quot;');

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