Last active
April 27, 2020 20:23
-
-
Save daleyjem/4035accf10a05eb42db6c2b7c85bdc95 to your computer and use it in GitHub Desktop.
Get a distinct listing of all artists from a user's playlists using Apple Music API
This file contains 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
const axios = require('axios') | |
const userToken = '<user token>' | |
const devToken = '<dev token>' | |
/** | |
* Gets a distinct array of the artists in a user's playlists | |
* @param {string} devToken The Apple-issued JWT developer token | |
* @param {string} userToken The returned Apple `musickit.authorize()` user token | |
*/ | |
async function getArtists(devToken, userToken){ | |
const headers = { | |
'Music-User-Token': userToken, | |
'Authorization': `Bearer ${devToken}` | |
} | |
/** | |
* Destructure: playlists = data.data | |
* @type {object[]} | |
*/ | |
const {data: {data: playlists}} = await axios.get('https://api.music.apple.com/v1/me/library/playlists', { | |
headers | |
}) | |
const playlistRequests = [] | |
playlists.forEach(playlist => { | |
playlistRequests.push(axios.get(`https://api.music.apple.com/v1/me/library/playlists/${playlist.id}?include=tracks`, { | |
headers | |
})) | |
}) | |
const playlistResponses = await Promise.all(playlistRequests) | |
const artists = playlistResponses.reduce((builder, playlistResponse) => { | |
/** | |
* Destructure: tracks = data.data[0].relationships.tracks.data | |
* @type {object[]} | |
*/ | |
const {data: {data: {0: {relationships: {tracks: {data: tracks}}}}}} = playlistResponse | |
// Destructure: artistName = data.data[0].relationships.tracks.data[n].attributes.artistName | |
tracks.forEach(({attributes: {artistName}}) => { | |
if (!builder.includes(artistName)) { | |
builder.push(artistName) | |
} | |
}) | |
return builder | |
}, []) | |
return artists | |
} | |
(async () => { | |
const artists = await getArtists(devToken, userToken) | |
console.log(artists) | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment