Günün Tarifi
Coddy'nin Node.js Journey'sinin Express Temelleri bölümünün bir parçası. Ders 19 / 20.
Recipe Box güne ait bir tarif sunar: bütün gün herkes için aynı tarif, yarın ise farklı bir tarif. Tarih tarifi belirler ve ?date= ile istediğin günü deneyebilirsin.
new Date('2026-03-01') o günün UTC gece yarısıdır. Yılın gün sayısı 31 Aralık'tan başlayarak hesaplanır, bu nedenle 1 Ocak 1. gündür: (date - Date.UTC(year, 0, 0)) / 86400000, çünkü bir günde 86.400.000 milisaniye vardır. Tarih olmayan bir metin geçersiz bir tarih verir; bu tarihin getTime() değeri NaN olur.
Rotayı server.js dosyasında, 404 işleyicisinin üstüne ekle. API'de olduğu gibi data/recipes.json dosyasındaki tariflerden seçim yap; böylece birinin gönderdiği tarif günün tarifi olabilir: loadRecipes işlevini routes/recipes.js dosyasından dışa aktar ve bu işlevi await et.
Görev
KolayGET /api/today?date=2026-03-01,recipesdeğişkeniloadRecipes()işlevinden gelen vedayyılın günü olan JSON biçimindekirecipes[day % recipes.length]değerini döndürür.dateyoksa: bugün.- Çözümlenemeyen bir tarih:
{ "error": "Use a date like 2026-03-01" }ile400.
Önce ?date=2026-03-01 değerini iki kez, ardından ?date=soon değerini gönder.
Kendin dene
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('<', '<')
.replaceAll('>', '>')
.replaceAll('"', '"');
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') düz metin gönderir, böylece her başlık ayrı bir satırda görünür.
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');
});