Here is my Spotify module
let userAccessToken;
const Spotify = {
getAccessToken() {
if (userAccessToken) {
return userAccessToken;
}
// get url access token
const urlAccessToken = window.location.href.match(/access_token=([^&]*)/);
const expiresInMatchUrl = window.location.href.match(/expires_in=([^&]*)/);
if (urlAccessToken && expiresInMatchUrl) {
userAccessToken = urlAccessToken[1];
const expiresIn = Number(expiresInMatchUrl[1]);
// This clears the parameters, allowing us to grab the access token when it expires
window.setTimeout(() => userAccessToken = '', expiresIn * 1000);
window.history.pushState('Access Token', null, '/');
return userAccessToken;
} else {
const accessUrl = `https://accounts.spotify.com/authorize?client_id=${clientId}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectUri}`;
window.location = accessUrl;
}
},
search(term) {
const accessToken = Spotify.getAccessToken();
return fetch(`https://api.spotify.com/v1/search?type=track&q=${term}`, {
headers: {
Authorization: `Bearer ${accessToken}`
}
}).then(response => {
return response.json();
}).then(jsonResponse => {
if (!jsonResponse.tracks) {
return [];
}
return jsonResponse.tracks.items.map(track => ({
id: track.id,
name: track.name,
artist: track.artists[0].name,
album: track.album.name,
url: track.uri
}));
});
},
savePlaylist(name, trackUris) {
console.log(`from savePlaylist: ${trackUris}`);
if (!name || !trackUris.length) {
return;
}
const accessToken = Spotify.getAccessToken();
const headers = { Authorization: `Bearer ${accessToken}` };
let userId;
return fetch('https://api.spotify.com/v1/me', {
headers: headers
}).then(response => response.json())
.then(jsonResponse => {
userId = jsonResponse.id;
return fetch(`https://api.spotify.com/v1/users/${userId}/playlists`, {
headers: headers,
method: 'POST',
body: JSON.stringify({ name: name })
}).then(response => response.json()).then(jsonResponse => {
const playlistId = jsonResponse.id;
return fetch(`https://api.spotify.com/v1/users/${userId}/playlists/${playlistId}/tracks`, {
headers: headers,
method: 'POST',
body: JSON.stringify({ uris: trackUris })
});
});
});
}
}
export default Spotify;