portfolio/app/api/spotify/last-played/route.ts

56 lines
1.4 KiB
TypeScript
Raw Normal View History

2023-07-29 22:40:36 +00:00
import {NextResponse} from 'next/server'
2023-02-12 18:41:17 +00:00
import {getRecentlyPlayed} from '@/lib/spotify'
type Tracks = {
items: [
{
track: {
name: string
artists: [
{
name: string
}
]
external_urls: {
spotify: string
}
album: {
name: string
images: [
{
url: string
}
]
}
}
played_at: string
}
]
}
2023-07-29 22:40:36 +00:00
export async function GET(request: Request) {
2023-02-12 18:41:17 +00:00
const response = await getRecentlyPlayed()
if (response.status > 400) {
2023-07-29 22:40:36 +00:00
return new Response(JSON.stringify({status: response.statusText}), {
status: response.status
})
2023-02-12 18:41:17 +00:00
}
const tracks = await response.json() as Tracks
const {track} = tracks.items.reduce((r, a) => r.played_at > a.played_at ? r : a)
const title = track.name;
const artist = track.artists.map(artist => artist.name).join(', ')
const songUrl = track.external_urls.spotify
const album = track.album.name
const albumImageUrl = track.album.images[0].url
2023-07-29 22:40:36 +00:00
return NextResponse.json({
2023-02-12 18:41:17 +00:00
artist,
title,
songUrl,
album,
albumImageUrl
})
}