Skip to content

Instantly share code, notes, and snippets.

@cdaz5
Created May 25, 2018 23:57
Show Gist options
  • Select an option

  • Save cdaz5/ea7e5561710f67e5c8f79eee63640a14 to your computer and use it in GitHub Desktop.

Select an option

Save cdaz5/ea7e5561710f67e5c8f79eee63640a14 to your computer and use it in GitHub Desktop.
savePlayList(playListName, trackURIs) {
if (!playListName || !trackURIs.length) {
return;
}
const newAccessToken = this.getAccessToken();
let userId;
let playListId;
const header = {
Authorization: `Bearer ${newAccessToken}`
};
return fetch('https://api.spotify.com/v1/me', {
headers: header
})
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error('Error - User ID Obtain Failed!');
})
.then(jsonResponse => {
userId = jsonResponse.id;
})
.then(() => {
return fetch(`https://api.spotify.com/v1/users/${userId}/playlists`, {
method: 'POST',
headers: header,
body: JSON.stringify({ name: playListName })
});
})
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error('Error - Playlist ID Obtain Failed!');
})
.then(jsonResponse => {
playListId = jsonResponse.id;
})
.then(() => {
return fetch(`https://api.spotify.com/v1/users/${userId}/playlists/${playListId}/tracks`, {
method: 'POST',
headers: header,
body: JSON.stringify({ uris: trackURIs })
});
})
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error('Request failed!');
})
.then(jsonResponse => {
console.log(jsonResponse);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment