Skip to content

Commit

Permalink
feat(lib): create getAlbumCover function for get music cover from S…
Browse files Browse the repository at this point in the history
…potify database
  • Loading branch information
mateusfg7 committed May 1, 2024
1 parent 673fda8 commit 455a49d
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions src/lib/get-album-cover.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// this is a workaround to get track cover from spotify if lastfm fails to get the image

const ENDPOINT = 'https://api.spotify.com/v1/search?q='

const CLIENT_ID = process.env.SPOTIFY_CLIENT_ID as string
const CLIENT_SECRET = process.env.SPOTIFY_CLIENT_SECRET as string
const REFRESH_TOKEN = process.env.SPOTIFY_REFRESH_TOKEN as string

const BASIC = Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString('base64')

const TOKEN_ENDPOINT = 'https://accounts.spotify.com/api/token'

const getAccessToken = async () => {
const response = await fetch(TOKEN_ENDPOINT, {
method: 'POST',
headers: {
Authorization: `Basic ${BASIC}`,
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: REFRESH_TOKEN
})
})
return await response.json()
}

export const getAlbumCover = async (track: string) => {
const { access_token } = await getAccessToken()
const URL = ENDPOINT + encodeURI(track) + '&type=track&market=IN&limit=1'
const res = await fetch(URL, {
headers: {
Authorization: `Bearer ${access_token}`
}
}).then(async res => {
return res.json()
})

const { name, album, external_urls, preview_url } = await res.tracks.items[0]

return {
name,
releaseDate: album.release_date,
coverArt: album.images[1],
external_urls,
preview_url
}
}

0 comments on commit 455a49d

Please sign in to comment.