handle random recipe page

This commit is contained in:
Ruidy 2024-12-13 21:37:51 +01:00
parent 3c4d4db1be
commit 821a48dfe4
No known key found for this signature in database
GPG key ID: E00F51288CB857CC
5 changed files with 23 additions and 31 deletions

View file

@ -0,0 +1,4 @@
export default function useRecipeRandom() {
const { $client } = useNuxtApp();
return $client.recipeRandom.useQuery();
}

View file

@ -15,10 +15,13 @@ useHead({
const { params } = useRoute();
const routeParam = params.id;
const id =
typeof routeParam === "string" ? Number(routeParam) : Number(routeParam[0]);
const id = typeof routeParam === "string" ? routeParam : routeParam[0];
const { data: recipe, status, error } = await useRecipeById(id);
const {
data: recipe,
status,
error,
} = id === "random" ? await useRecipeRandom() : await useRecipeById(Number(id));
if (error.value) {
let statusCode = 400;

View file

@ -1,15 +0,0 @@
<script setup lang="ts">
const {
data: recipe,
pending,
error,
} = await useFetch("/api/recipes", { lazy: true });
</script>
<template>
<div v-if="pending">Loading</div>
<div v-else-if="error">Failed: {{ error }}</div>
<section v-else>
<Recipe :recipe="recipe" />
</section>
</template>

View file

@ -1,13 +0,0 @@
import { parseRecipeData } from "~/utils/recipes";
import type { Meal } from "~/types/recipe";
export default defineEventHandler(async (_event) => {
const { apiUrl } = useRuntimeConfig();
const data = await $fetch<{ meals: Meal[] }>(
new URL("random.php", apiUrl).toString(),
);
const recipes = parseRecipeData(data);
return recipes[0];
});

View file

@ -29,4 +29,17 @@ export const recipeRouter = router({
const recipes = parseRecipeData(data);
return recipes[0];
}),
recipeRandom: publicProcedure.query(async () => {
const data = await $fetch<{ meals: Meal[] }>(
new URL("random.php", apiUrl).toString(),
);
if (!data?.meals) {
throw createError({
statusCode: 500,
});
}
const recipes = parseRecipeData(data);
return recipes[0];
}),
});