From a3687ac56b2bc30af05cee65365bebddc7d4d4b5 Mon Sep 17 00:00:00 2001 From: Mihkel Martin Kasterpalu Date: Mon, 10 Feb 2025 12:42:40 +0200 Subject: [PATCH] Fix case, where pakubiiti recieved only 2 albums from the server Use a while loop instead of the previous for loop Cap the amount of retries to not create infinite loops Show an error message on the client when this cap is reached without getting the required amount of albums --- .../api/pakubiiti/getAlbums/[count]/+server.ts | 16 +++++++++++++--- src/routes/vinge/pakubiiti/+page.server.ts | 5 +++++ src/routes/vinge/pakubiiti/+page.svelte | 18 ++++++++++++++---- 3 files changed, 32 insertions(+), 7 deletions(-) diff --git a/src/routes/api/pakubiiti/getAlbums/[count]/+server.ts b/src/routes/api/pakubiiti/getAlbums/[count]/+server.ts index 4194233..f09c3cf 100644 --- a/src/routes/api/pakubiiti/getAlbums/[count]/+server.ts +++ b/src/routes/api/pakubiiti/getAlbums/[count]/+server.ts @@ -1,15 +1,19 @@ import { albumState } from '$lib/server/AlbumState.svelte'; import { spotifyAPI } from '$lib/server/Spotify.svelte'; import type { AlbumSolveState } from '$lib/types'; -import { json } from '@sveltejs/kit'; +import { error, json } from '@sveltejs/kit'; + +const maxTries = 10; export async function GET({ params }) { - const count = params.count || 1; + const count = Number(params.count) || 1; const albums: AlbumSolveState[] = []; + let tries = 0; - for (let i = 0; i < count; i++) { + while (albums.length < count && tries++ < maxTries) { const album = await spotifyAPI.getRandomAlbum(); + if (album) { const image = album.images.at(0); if (!image?.url) { @@ -24,6 +28,12 @@ export async function GET({ params }) { } } + if (albums.length !== count) { + albumState.setAlbums([]); + + return error(500, "Couldn't get albums from Spotify."); + } + albumState.setAlbums(albums); return json({ albums: albums }); diff --git a/src/routes/vinge/pakubiiti/+page.server.ts b/src/routes/vinge/pakubiiti/+page.server.ts index 3015481..b227152 100644 --- a/src/routes/vinge/pakubiiti/+page.server.ts +++ b/src/routes/vinge/pakubiiti/+page.server.ts @@ -56,6 +56,11 @@ export const load: PageServerLoad = async ({ fetch, locals }) => { images: shuffleArray(albumImages), artists: shuffleArray(albumArtists) }; + }) + .catch((err) => { + console.log(err); + + return undefined; }); return { diff --git a/src/routes/vinge/pakubiiti/+page.svelte b/src/routes/vinge/pakubiiti/+page.svelte index 2606a9d..c4c255d 100644 --- a/src/routes/vinge/pakubiiti/+page.svelte +++ b/src/routes/vinge/pakubiiti/+page.svelte @@ -112,10 +112,20 @@ {@render footer(true)} {:then albums} -
- {@render playArea(albums as AlbumData)} -
- {@render footer(false)} + {#if albums} +
+ {@render playArea(albums as AlbumData)} +
+ {@render footer(false)} + {:else} +

+ Serveris tekkis mingi error. +
No clue miks see katki on, sorry. +

+

+ Proovi uuesti või kirjuta mulle. +

+ {/if} {/await} {:else}