feat: split random into 'Was koche ich?' + 'Was backe ich?'
- Two dice buttons on homepage - Cook: mittag, abend, fruehstueck categories - Bake: backen, torten, desserts categories - Backend: /api/recipes/random?categories=slug1,slug2 filter - Luna's feature request
This commit is contained in:
@@ -4,7 +4,9 @@ import * as svc from '../services/recipe.service.js';
|
||||
|
||||
export async function recipeRoutes(app: FastifyInstance) {
|
||||
app.get('/api/recipes/random', async (request, reply) => {
|
||||
const recipe = await svc.getRandomRecipe();
|
||||
const { categories } = request.query as { categories?: string };
|
||||
const categorySlugs = categories ? categories.split(',') : undefined;
|
||||
const recipe = await svc.getRandomRecipe(categorySlugs);
|
||||
if (!recipe) return reply.status(404).send({ error: 'No recipes found' });
|
||||
return recipe;
|
||||
});
|
||||
|
||||
@@ -261,8 +261,18 @@ export async function toggleFavorite(id: string, userId?: string) {
|
||||
}
|
||||
}
|
||||
|
||||
export async function getRandomRecipe() {
|
||||
const { rows } = await query('SELECT slug FROM recipes ORDER BY RANDOM() LIMIT 1');
|
||||
export async function getRandomRecipe(categorySlugs?: string[]) {
|
||||
let sql = 'SELECT r.slug FROM recipes r';
|
||||
const params: string[] = [];
|
||||
|
||||
if (categorySlugs && categorySlugs.length > 0) {
|
||||
sql += ' JOIN categories c ON r.category_id = c.id WHERE c.slug = ANY($1)';
|
||||
params.push(categorySlugs as any);
|
||||
}
|
||||
|
||||
sql += ' ORDER BY RANDOM() LIMIT 1';
|
||||
|
||||
const { rows } = await query(sql, params);
|
||||
if (rows.length === 0) return null;
|
||||
return getRecipeBySlug(rows[0].slug);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user