Menu
CoddyTech

Рецепт дня

Часть раздела Основы Express путешествия по Node.js на Coddy. Урок 19 из 20.

Recipe Box получает рецепт дня: один и тот же рецепт для всех в течение всего дня, а завтра — другой. Его выбирает дата, а ?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