Günün Tarifi
Coddy'nin Node.js Journey'sinin Express Temelleri bölümünün bir parçası. Ders 22 / 23.
Recipe Box, her gün için bir tarif sunmak üzere bildik rota ve dosya okuma becerilerini kullanabilir. Sağlanan dayOfYear yardımcı işlevi bir tarihi sayıya dönüştürür: 1 Ocak 1, 1 Mart 2026 ise 60'tır. Tarih belirtilmezse bugün kullanılır; okunamayan metin null döndürür.
const day = dayOfYear(req.query.date);
// ?date=2026-03-01, 60 döndürür
// ?date=soon, null döndürürBir konum seçmek için kalan operatörünü kullan: day % recipes.length. Dört tarif olduğunda 60. gün sıfırıncı konumu seçer. Yakın zamanda eklenen tariflerin de seçime katılması için tarifleri isteğin içinde yükle. Tarih ayrıştırma zaten sağlanmıştır; rotayı oluşturma kısmına odaklan.
Görev
KolayRecipe Box’a Günün Tarifi uç noktası ekle. Sağlanan day-of-year.js, gün numarasını ya da geçersiz bir tarih için null değerini döndüren dayOfYear(text) işlevini dışa aktarır.
loadRecipesişleviniroutes/recipes.jsdosyasından dışa aktar.server.jsdosyasına içe aktar: yönlendirici varsayılan içe aktarma olarak kalır ve{ loadRecipes }virgülden sonra gelir.dayOfYearişlevini içe aktar.server.jsdosyasında, 404 işleyicisinin üstüneGET /api/todayiçin birasyncrotası ekle. Yardımcı işlevereq.query.datedeğerini ilet.nulliçin{"error":"Use a date like 2026-03-01"}ile 400 döndür.- Aksi durumda
loadRecipes()işlevini bekle verecipes[day % recipes.length]değerini JSON olarak döndür. Mevcut rotaları ve hata işleyicisini koru.
GET /api/today?date=2026-03-01 adresini dene: gün numarası 60 ve dört tarif bulunduğundan ilk tarifi döndürür. ?date=soon adresini dene: yukarıdaki 400 hatasını döndürür.
Kendin dene
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') düz metin gönderir, bu yüzden 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');
});
Express Temelleri bölümündeki tüm dersler
Kendi başına pratik yap: Express playground