feat: refactoring api logic

This commit is contained in:
Mat12143 2025-08-02 03:54:26 +02:00
parent 1383c0fbed
commit 44e0d9f44c
7 changed files with 150 additions and 74 deletions

View file

@ -1,8 +1,10 @@
<script lang="ts">
let { code, message } = $props()
import type { FetchError } from "$lib/types"
let { returnError }: { returnError: FetchError } = $props()
</script>
<div class="flex h-screen w-full flex-col items-center justify-center">
<h1 class="p-2 text-xl">Error {code}</h1>
<p>{message}</p>
<h1 class="p-2 text-xl">Error {returnError.code}</h1>
<p>{returnError.message}</p>
</div>

View file

@ -1,12 +1,12 @@
<script lang="ts">
import { type Song, createEmptySong } from "$lib/types"
let { songs, playing } = $props()
let { queueSongs, playingIndex } = $props()
let displaySongs = $derived<Song[]>([
playing > 0 && playing < songs.length ? songs[playing - 1] : createEmptySong(),
songs[playing],
playing == songs.length - 1 ? createEmptySong() : songs[playing + 1],
playingIndex > 0 ? queueSongs[playingIndex - 1] : createEmptySong(),
queueSongs[playingIndex],
playingIndex == queueSongs.length - 1 ? createEmptySong() : queueSongs[playingIndex + 1],
])
</script>

View file

@ -35,3 +35,8 @@ export const parseSuggestion = async function (sugg: any): Promise<Suggestion> {
let resp = await SuggestionSchema.parseAsync(sugg)
return resp
}
export type FetchError = {
code: number
message: string
}

69
frontend/src/lib/utils.ts Normal file
View file

@ -0,0 +1,69 @@
import { parseSong, parseSuggestion, type FetchError, type Song, type Suggestion } from "./types"
export const joinRoom = async function (roomId: string): Promise<[FetchError | null, string]> {
let resp = await fetch("/api/join?room=" + roomId)
if (resp.status != 200) {
return [{ code: 400, message: "Cannot join the room" }, ""]
}
return [null, "test"]
}
export const getSuggestions = async function (roomId: string): Promise<[FetchError | null, Suggestion[]]> {
let resp = await fetch("/api/room/suggestions?room=" + roomId)
if (resp.status != 200) {
return [{ code: 400, message: "Failed to retrieve suggestions" }, []]
}
let json = await resp.json()
let suggestions: Suggestion[] = []
json["songs"].forEach(async (i: any) => {
suggestions.push(await parseSuggestion(i))
})
suggestions = suggestions.sort((a, b) => {
return a.upvote - b.upvote
})
return [null, suggestions]
}
export const getQueueSongs = async function (roomId: string): Promise<[FetchError | null, Song[], number]> {
let resp = await fetch("/api/queue?room=" + roomId)
if (resp.status != 200) {
return [{ code: 400, message: "Failed to load queue songs" }, [], 0]
}
let json = await resp.json()
let songs: Song[] = []
json["queue"].forEach(async (i: any) => {
songs.push(await parseSong(i))
})
let playingId = json["index"]
return [null, songs, playingId]
}
export const triggerPlayNext = async function (roomId: string): Promise<[FetchError | null, Song[], number]> {
let resp = await fetch("/api/queue/next?room=" + roomId, { method: "POST" })
if (resp.status != 200) {
return [{ code: 400, message: "Failed to trigger next song playback" }, [], 0]
}
let json = await resp.json()
let songs: Song[] = []
if (json["ended"]) {
json["queue"].forEach(async (i: any) => {
songs.push(await parseSong(i))
})
}
return [null, songs, json["index"]]
}

View file

@ -1,37 +1,43 @@
<script lang="ts">
import QueueSlider from "$lib/components/QueueSlider.svelte"
import { type Song } from "$lib/types"
import { onMount } from "svelte"
import type { FetchError } from "$lib/types"
import { getQueueSongs, triggerPlayNext } from "$lib/utils.js"
let songs = $state([
{
name: "Cisco PT - Cantarex",
image: "https://s2.qwant.com/thumbr/474x474/5/9/bcbd0c0aeb1838f6916bf452c557251d7be985a13449e49fccb567a3374d4e/OIP.pmqEiKWv47zViDGgPgbbQAHaHa.jpg?u=https%3A%2F%2Ftse.mm.bing.net%2Fth%2Fid%2FOIP.pmqEiKWv47zViDGgPgbbQAHaHa%3Fr%3D0%26pid%3DApi&q=0&b=1&p=0&a=0",
points: 0,
},
{
name: "Io e i miei banchi - Paul Ham",
image: "https://i.prcdn.co/img?regionKey=RbtvKb5E1Cv4j1VWm2uGrw%3D%3D",
points: 0,
},
{
name: "Ragatthi - Bersatetthi",
image: "https://s2.qwant.com/thumbr/474x474/5/9/bcbd0c0aeb1838f6916bf452c557251d7be985a13449e49fccb567a3374d4e/OIP.pmqEiKWv47zViDGgPgbbQAHaHa.jpg?u=https%3A%2F%2Ftse.mm.bing.net%2Fth%2Fid%2FOIP.pmqEiKWv47zViDGgPgbbQAHaHa%3Fr%3D0%26pid%3DApi&q=0&b=1&p=0&a=0",
points: 0,
},
{
name: "Quarta",
image: "https://s2.qwant.com/thumbr/474x474/5/9/bcbd0c0aeb1838f6916bf452c557251d7be985a13449e49fccb567a3374d4e/OIP.pmqEiKWv47zViDGgPgbbQAHaHa.jpg?u=https%3A%2F%2Ftse.mm.bing.net%2Fth%2Fid%2FOIP.pmqEiKWv47zViDGgPgbbQAHaHa%3Fr%3D0%26pid%3DApi&q=0&b=1&p=0&a=0",
points: 0,
},
{
name: "Quinta",
image: "https://s2.qwant.com/thumbr/474x474/5/9/bcbd0c0aeb1838f6916bf452c557251d7be985a13449e49fccb567a3374d4e/OIP.pmqEiKWv47zViDGgPgbbQAHaHa.jpg?u=https%3A%2F%2Ftse.mm.bing.net%2Fth%2Fid%2FOIP.pmqEiKWv47zViDGgPgbbQAHaHa%3Fr%3D0%26pid%3DApi&q=0&b=1&p=0&a=0",
points: 0,
},
])
let { data } = $props()
let playing = $state(1)
let queueSongs = $state<Song[]>([])
let playingIndex = $state<number>()
let returnError = $state<FetchError | null>()
onMount(async () => {
let songs, index
;[returnError, songs, index] = await getQueueSongs(data.roomId)
queueSongs = songs
playingIndex = index
})
$effect(() => {
$inspect(queueSongs)
})
async function playNext() {
let songs, index
;[returnError, songs, index] = await triggerPlayNext(data.roomId)
if (returnError) return
if (songs.length != 0) queueSongs = songs
playingIndex = index
}
</script>
{returnError}
<div class="flex w-full flex-col items-center justify-center p-4 lg:p-10">
<QueueSlider {songs} {playing} />
<QueueSlider {queueSongs} {playingIndex} />
<button onclick={playNext}>Next</button>
</div>

View file

@ -0,0 +1,11 @@
import { error } from "@sveltejs/kit"
import type { PageLoad } from "../../room/[id]/$types"
export const load: PageLoad = function ({ params }) {
if (params.id) {
return {
roomId: params.id,
}
}
error(400, "Please provide a room id")
}

View file

@ -2,71 +2,54 @@
import QueueSlider from "$lib/components/QueueSlider.svelte"
import SuggestionInput from "$lib/components/SuggestionInput.svelte"
import Error from "$lib/components/Error.svelte"
import { parseSong, parseSuggestion, type Suggestion, type Song } from "$lib/types.js"
import { type Suggestion, type Song } from "$lib/types.js"
import { onMount } from "svelte"
import SuggestionList from "$lib/components/SuggestionList.svelte"
import { getQueueSongs, getSuggestions, joinRoom } from "$lib/utils.js"
import type { FetchError } from "$lib/types.js"
let { data } = $props()
let songs = $state<Song[]>([])
let playing = $state(0)
let queueSongs = $state<Song[]>([])
let playingIndex = $state(0)
let suggestions = $state<Suggestion[]>([])
let error = $state({ code: 0, message: "" })
let returnError = $state<FetchError | null>()
let wsUrl = ""
onMount(async () => {
// Join the room
let resp = await fetch("/api/join?room=" + data.roomId)
if (resp.status != 200) {
error = { code: 400, message: "Failed to join the room. Maybe wrong code or location?" }
let sugg, queue, index
;[returnError, wsUrl] = await joinRoom(data.roomId)
if (returnError) {
return
}
// Setup websocket connection
// Get room suggestions
resp = await fetch("/api/room/suggestions?room=" + data.roomId)
if (resp.status != 200) {
error = { code: 500, message: "Failed to retrive suggestions" }
;[returnError, sugg] = await getSuggestions(data.roomId)
if (returnError) {
return
}
let json = await resp.json()
json["songs"].forEach(async (i: any) => {
suggestions.push(await parseSuggestion(i))
})
suggestions = suggestions.sort((a, b) => {
return a.upvote - b.upvote
})
// Get the room queue
resp = await fetch("/api/queue?room=" + data.roomId)
if (resp.status != 200) {
error = { code: 404, message: "Room not found" }
;[returnError, queue, index] = await getQueueSongs(data.roomId)
if (returnError) {
return
}
json = await resp.json()
json["queue"].forEach(async (i: any) => {
songs.push(await parseSong(i))
})
console.log(songs)
queueSongs = queue
suggestions = sugg
playingIndex = index
})
</script>
<!-- Check if the room exists -->
{#if error.code != 0}
<Error code={error.code} message={error.message} />
{#if returnError}
<Error {returnError} />
{:else}
<div class="flex w-full flex-col items-center justify-center p-4 lg:p-10">
<QueueSlider {songs} {playing} />
<QueueSlider {queueSongs} {playingIndex} />
<div class="w-full py-6 lg:w-[30vw]">
<SuggestionInput roomId={data.roomId} />
</div>