Skip to content

Instantly share code, notes, and snippets.

Created September 12, 2018 19:05
What would you like to do?
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 = => {
return trackObject.trackUri
try {
if (trackUris.length <maxTracksToAddInEachRequest) {
return await spotifyApi.addTracksToPlaylist(, trackUris);
else {
const chunkedTrackUris = chunk(trackUris, maxTracksToAddInEachRequest);
const promisesOfChunkedUris = (chunkOfTrackUris) => {
const addTracksToPlaylistResponse = await spotifyApi.addTracksToPlaylist(, chunkOfTrackUris);
await Promise.all(promisesOfChunkedUris);
return await{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