-
Notifications
You must be signed in to change notification settings - Fork 0
feat: source last month's top 5 from Spotify official top tracks API #88
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,21 +1,54 @@ | ||
| import { NextResponse } from "next/server"; | ||
| import { | ||
| createListeningSupabase, | ||
| getLastMonthTopFiveTracks, | ||
| } from "@/lib/listening-supabase"; | ||
| getSpotifyAccessToken, | ||
| invalidateSpotifyAccessTokenCache, | ||
| } from "@/lib/spotify-access-token"; | ||
| import { | ||
| mapSpotifyTopTracks, | ||
| type SpotifyTopTracksPayload, | ||
| } from "@/lib/spotify-top-tracks"; | ||
|
|
||
| // Spotify's official "last ~4 weeks" top tracks; requires the `user-top-read` scope. | ||
| const TOP_TRACKS_URL = "https://api.spotify.com/v1/me/top/tracks?time_range=short_term&limit=5"; | ||
|
|
||
| export const revalidate = 600; | ||
|
|
||
| const responseHeaders = { | ||
| "Cache-Control": "public, s-maxage=600, stale-while-revalidate=120", | ||
| } as const; | ||
|
|
||
| function fetchTopTracks(accessToken: string) { | ||
| return fetch(TOP_TRACKS_URL, { | ||
| headers: { Authorization: `Bearer ${accessToken}` }, | ||
| cache: "no-store", | ||
| }); | ||
| } | ||
|
|
||
| export async function GET() { | ||
| const db = createListeningSupabase(); | ||
| const tracks = await getLastMonthTopFiveTracks(db); | ||
|
|
||
| return NextResponse.json( | ||
| { tracks }, | ||
| { | ||
| headers: { | ||
| "Cache-Control": "public, s-maxage=600, stale-while-revalidate=120", | ||
| }, | ||
| } | ||
| ); | ||
| const emptyResponse = () => | ||
| NextResponse.json({ tracks: [] }, { headers: responseHeaders }); | ||
|
|
||
| const accessToken = await getSpotifyAccessToken(); | ||
| if (!accessToken) return emptyResponse(); | ||
|
|
||
| let res = await fetchTopTracks(accessToken); | ||
|
|
||
| if (res.status === 401) { | ||
| invalidateSpotifyAccessTokenCache(); | ||
| const retryToken = await getSpotifyAccessToken(); | ||
| if (!retryToken) return emptyResponse(); | ||
| res = await fetchTopTracks(retryToken); | ||
| } | ||
|
|
||
| if (!res.ok) return emptyResponse(); | ||
|
|
||
| try { | ||
| const payload = (await res.json()) as SpotifyTopTracksPayload; | ||
| return NextResponse.json( | ||
| { tracks: mapSpotifyTopTracks(payload) }, | ||
| { headers: responseHeaders } | ||
| ); | ||
| } catch { | ||
| return emptyResponse(); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| import { describe, expect, it } from "vitest"; | ||
| import { mapSpotifyTopTracks } from "./spotify-top-tracks"; | ||
|
|
||
| describe("mapSpotifyTopTracks", () => { | ||
| it("maps items preserving Spotify's affinity order and caps at five", () => { | ||
| const payload = { | ||
| items: Array.from({ length: 7 }, (_, i) => ({ | ||
| id: `id-${i}`, | ||
| name: `Track ${i}`, | ||
| artists: [{ name: "Artist A" }, { name: "Artist B" }], | ||
| album: { | ||
| images: [ | ||
| { url: `https://img/${i}/small`, width: 64, height: 64 }, | ||
| { url: `https://img/${i}/large`, width: 640, height: 640 }, | ||
| ], | ||
| }, | ||
| external_urls: { spotify: `https://open.spotify.com/track/id-${i}` }, | ||
| })), | ||
| }; | ||
|
|
||
| const tracks = mapSpotifyTopTracks(payload); | ||
| expect(tracks).toHaveLength(5); | ||
| expect(tracks[0]).toEqual({ | ||
| title: "Track 0", | ||
| artist: "Artist A, Artist B", | ||
| albumArt: "https://img/0/large", | ||
| songUrl: "https://open.spotify.com/track/id-0", | ||
| }); | ||
| expect(tracks.map((t) => t.title)).toEqual([ | ||
| "Track 0", | ||
| "Track 1", | ||
| "Track 2", | ||
| "Track 3", | ||
| "Track 4", | ||
| ]); | ||
| }); | ||
|
|
||
| it("skips items without an id and builds fallback song URLs", () => { | ||
| const tracks = mapSpotifyTopTracks({ | ||
| items: [ | ||
| { name: "No id" }, | ||
| { id: "abc", name: "Has id" }, | ||
| ], | ||
| }); | ||
| expect(tracks).toHaveLength(1); | ||
| expect(tracks[0]).toEqual({ | ||
| title: "Has id", | ||
| artist: "", | ||
| albumArt: "", | ||
| songUrl: "https://open.spotify.com/track/abc", | ||
| }); | ||
| }); | ||
|
|
||
| it("returns an empty list for an empty payload", () => { | ||
| expect(mapSpotifyTopTracks({})).toEqual([]); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| import { | ||
| formatSpotifyArtistNames, | ||
| pickAlbumArtFromSpotifyImages, | ||
| type SpotifyArtist, | ||
| type SpotifyImage, | ||
| } from "./spotify-now-playing-helpers"; | ||
|
|
||
| export type ListeningHighlightTrack = { | ||
| title: string; | ||
| artist: string; | ||
| albumArt: string; | ||
| songUrl: string; | ||
| }; | ||
|
|
||
| export type SpotifyTopTracksPayload = { | ||
| items?: { | ||
| id?: string; | ||
| name?: string; | ||
| artists?: SpotifyArtist[]; | ||
| album?: { images?: SpotifyImage[] }; | ||
| external_urls?: { spotify?: string }; | ||
| }[]; | ||
| }; | ||
|
|
||
| /** Maps Spotify `GET /me/top/tracks` items (already ranked by affinity) to card rows. */ | ||
| export function mapSpotifyTopTracks(payload: SpotifyTopTracksPayload): ListeningHighlightTrack[] { | ||
| return (payload.items ?? []) | ||
| .filter((item) => item.id) | ||
| .slice(0, 5) | ||
| .map((item) => ({ | ||
| title: item.name ?? "", | ||
| artist: formatSpotifyArtistNames(item.artists), | ||
| albumArt: pickAlbumArtFromSpotifyImages(item.album?.images), | ||
| songUrl: | ||
| item.external_urls?.spotify ?? | ||
| `https://open.spotify.com/track/${encodeURIComponent(item.id!)}`, | ||
| })); | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Add a timeout to the Spotify fetch.
fetchTopTrackshas noAbortController/timeout. If Spotify's API stalls, the request will hang until the platform's function timeout kicks in, tying up the request thread on every retry path (initial call and the 401 retry).🕐 Proposed fix: add a request timeout
function fetchTopTracks(accessToken: string) { - return fetch(TOP_TRACKS_URL, { - headers: { Authorization: `Bearer ${accessToken}` }, - cache: "no-store", - }); + return fetch(TOP_TRACKS_URL, { + headers: { Authorization: `Bearer ${accessToken}` }, + cache: "no-store", + signal: AbortSignal.timeout(5000), + }); }Also applies to: 34-41
🤖 Prompt for AI Agents