portfolio/pages/api/spotify/currently-playing.ts

60 lines
1.3 KiB
TypeScript
Raw Normal View History

2022-12-06 12:54:34 +00:00
import {getCurrentlyPlaying} from '@/lib/spotify'
2023-02-12 18:41:17 +00:00
import {NextApiRequest, NextApiResponse} from 'next'
2022-12-06 12:54:34 +00:00
2023-02-12 18:41:17 +00:00
type Song = {
item: {
album: {
name: string
images: [
{
url: string
}
]
}
artists: [
{
name: string
}
]
external_urls: {
spotify: string
}
name: string
}
is_playing: boolean
}
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
2022-12-06 12:54:34 +00:00
const response = await getCurrentlyPlaying()
if (response.status === 204 || response.status > 400) {
return res.status(200).json({
isPlaying: false
})
}
2023-02-12 18:41:17 +00:00
const song = await response.json() as Song
2022-12-06 12:54:34 +00:00
const {item} = song
if (item === null) {
return res.status(200).json({
isPlaying: false
})
}
const artist = item.artists.map(artist => artist.name).join(', ')
const title = item.name;
const songUrl = item.external_urls.spotify
const album = item.album.name
const albumImageUrl = item.album.images[0].url
const isPlaying = song.is_playing;
return res.status(200).json({
artist,
title,
songUrl,
album,
albumImageUrl,
isPlaying
})
}