Personal Site

Update format for `/now-playing-sse`

This new format only includes data needed for the client to update and should be nicer to work with since its not randomly nested!
Properties dont line up to those in the spotify API but idc

vielle.dev a98cf368 24a10bee

verified
+14 -34
+14 -34
src/pages/now-playing-sse.ts
··· 1 - import { 2 - spotifyNowPlaying, 3 - SpotifyError, 4 - type nowPlaying, 5 - } from "/components/home/playing/spotify"; 1 + import { sdk } from "/components/home/playing/spotify"; 6 2 7 3 export async function GET() { 8 4 const update = async (): Promise<string> => { 9 5 // extract a subset to reduce size for client 10 6 // not huge savings but tesco yk 11 7 // + reduces chance of leaking extra data to client 12 - const playing: SpotifyError | nowPlaying = await spotifyNowPlaying() 8 + const playing = await sdk.player 9 + .getCurrentlyPlayingTrack() 13 10 .then((playing) => 14 - playing 11 + // minimise body to make faster and streamline download 12 + !!playing && "album" in playing.item 15 13 ? { 16 - type: "track" as const, 17 - name: playing.name, 18 - id: playing.id, 19 - external_urls: { 20 - spotify: playing.external_urls.spotify, 21 - }, 22 - album: { 23 - name: playing.album.name, 24 - external_urls: { 25 - spotify: playing.album.external_urls.spotify, 26 - }, 27 - images: [playing.album.images[0]], 28 - }, 29 - artists: playing.artists.map((artist) => ({ 30 - external_urls: { spotify: artist.external_urls.spotify }, 14 + id: playing.item.id, 15 + name: playing.item.name, 16 + href: playing.item.external_urls.spotify, 17 + album: playing.item.album.name, 18 + art: playing.item.album.images[0].url, 19 + artists: playing.item.artists.map((artist) => ({ 31 20 name: artist.name, 21 + href: artist.external_urls.spotify, 32 22 })), 33 23 } 34 24 : null, 35 - ) 36 - .catch((err) => { 37 - if (!(err instanceof SpotifyError)) 38 - throw new Error("Unhandled exception"); 39 - if (err.code === "NO_CONTENT") return null; 40 - 41 - console.error("/now-playing-sse", err.code, err.human, err.details, JSON.stringify(err)); 42 - return err; 43 - }); 44 - 45 - console.log("SENDING:", playing && "name" in playing ? playing.name + " by " + playing.artists.map(artist => artist.name).join(", ") : playing) 25 + ); 46 26 47 27 // SSE syntax: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#event_stream_format 48 28 return `event: playing\ndata: ${JSON.stringify(playing)}\n\n`; ··· 58 38 update() 59 39 // dont write if aborted as it can cause errors 60 40 .then((val) => 61 - !abort.signal.aborted ? (() => {console.log("sending sending frfr:", val); controller.enqueue(val); console.log("sent sent frfr:", val)})() : undefined, 41 + !abort.signal.aborted ? controller.enqueue(val) : undefined, 62 42 ) 63 43 .catch((err) => { 64 44 console.error("/now-playing-sse", "GOT ERROR:", err);