feat: websockets & realtime updates

This commit is contained in:
Mat12143 2025-08-02 05:04:30 +02:00
parent 2a167ba8ad
commit 0bf67061f8
4 changed files with 41 additions and 46 deletions

View file

@ -2,12 +2,12 @@
import QueueSlider from "$lib/components/QueueSlider.svelte"
import SuggestionInput from "$lib/components/SuggestionInput.svelte"
import Error from "$lib/components/Error.svelte"
import { type Suggestion, type Song } from "$lib/types.js"
import { onMount } from "svelte"
import { type Suggestion, type Song, parseSong, parseSuggestion } from "$lib/types.js"
import { onDestroy, 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"
import { io } from "socket.io-client"
import { io, Socket } from "socket.io-client"
let { data } = $props()
@ -18,23 +18,20 @@
let returnError = $state<FetchError | null>()
let wsUrl = ""
let socket: Socket
onMount(async () => {
// Join the room
socket = io("/", { path: "/ws" })
let sugg, queue, index
;[returnError, wsUrl] = await joinRoom(data.roomId)
;[returnError] = await joinRoom(data.roomId)
if (returnError) {
return
}
;[returnError, sugg] = await getSuggestions(data.roomId)
if (returnError) return
// Setup websocket connection
let socket = io("/", { path: "/ws" })
await socket.emitWithAck("join_room", { id: data.roomId })
;[returnError, queue, index] = await getQueueSongs(data.roomId)
if (returnError) {
return
@ -43,6 +40,28 @@
queueSongs = queue
suggestions = sugg
playingIndex = index
// Setup websocket connection
await socket.emitWithAck("join_room", { id: data.roomId })
socket.on("queue_update", async (d) => {
const songs = await Promise.all(d.queue.map(parseSong))
queueSongs = songs
playingIndex = d.index
})
socket.on("new_vote", async (d) => {
const updated = await parseSuggestion(d.song)
suggestions = suggestions.map((s) => (s.uuid === updated.uuid ? updated : s))
})
socket.on("new_song", async (d) => {
const song = await parseSuggestion(d.song)
suggestions = [...suggestions, song]
})
})
onDestroy(() => {
if (socket) socket.disconnect()
})
</script>