Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
oldschoolshuffle
async function createPlaylist(simplifiedTrackArray, playlistName, addRelatedDiscography) {
//have to get userId, create a playlist in spotify with the name, and then add the tracks to it
//options is whether to addDiscography
//Note that Spotify is very picky about what counts as an 'active device' so likely don't have permission to press
//play. Also only works if the user has premium. Also spotify will only let you add 100 tracks
//per addTracksToPlaylist request, so need to split the trackUris up if more than 100 tracks
const maxTracksToAddInEachRequest = 100;
const userInfoResponse = await spotifyApi.getMe();
const name = `${playlistName} - Album Shuffled - ${addRelatedDiscography === "true" ? 'with related discography' : ''}`;
const description = 'Made with the oldschoolshuffle app to enable shuffling by album, the way music was meant to be listened to';
//es6 destructuring and renaming
const {id: userId} = userInfoResponse;
const playlistOptions = {name: name, description: description}
const newPlaylistResponse = await spotifyApi.createPlaylist(userId, playlistOptions);
const trackUris = simplifiedTrackArray.map((trackObject) => {
return trackObject.trackUri
})
try {
if (trackUris.length <maxTracksToAddInEachRequest) {
return await spotifyApi.addTracksToPlaylist(newPlaylistResponse.id, trackUris);
}
else {
const chunkedTrackUris = chunk(trackUris, maxTracksToAddInEachRequest);
const promisesOfChunkedUris = chunkedTrackUris.map(async (chunkOfTrackUris) => {
//eslint-disable-next-line
const addTracksToPlaylistResponse = await spotifyApi.addTracksToPlaylist(newPlaylistResponse.id, chunkOfTrackUris);
})
await Promise.all(promisesOfChunkedUris);
return await spotifyApi.play({context_uri: newPlaylistResponse.uri});
}
} catch(err) {
console.log('Oops - no spotify player is active so just made a playlist');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.