I am looking to get all artists that a user follows from Spotify. The catch is that I can only request 50 artists at a time and only know the total number of artists after the first request. My factory looks like this:
app.factory('artists', [
"$rootScope",
"$http",
"$cookies",
"$q",
function($rootScope, $http, $cookies, $q){
return {
getUserFollowing: function(){
var allArtists = [];
var _params = {
type: 'artist',
limit: 50, // maximum
};
var _authConfig = {
'Authorization': 'Bearer ' + $cookies.get('spotify-token'),
'Content-Type': 'application/json'
};
var req = {
method: 'GET',
url: 'https://api.spotify.com/v1/me/following',
headers: _authConfig,
params: _params
};
return $http(req).then(function(res){
var artistTotal = res.data.artists.total;
allArtists = allArtists.concat(res.data.artists.items);
if(allArtists.length < artistTotal){
// send the request again to load 50 more artists
return $http({
method: 'GET',
url: res.data.artists.next,
headers: _authConfig,
}).then(function(nextRes){
allArtists = allArtists.concat(nextRes.data.artists.items);
return allArtists;
});
} else {
// need to return a promise
var dfd = $q.defer();
dfd.resolve(allArtists);
return dfd.promise;
}
});
}
};
}]);
In the above request I send an additional request (for another 50) if the user follows more than 50 artists. If they follow less than 50 artists it will return the total. I am using this factory from a controller like so:
// grab the artists they follow
artists.getUserFollowing().then(function(artistsUserFollows){
$rootScope.artistTotal = artistsUserFollows.length;
$rootScope.artists = artistsUserFollows;
});
How can I write a loop so that the getUserFollowing()
will return an array of all artists whether they follow no artists or 1000 artists? If they follow 1000 artists then we'd need to send 20 requests (1000/50) or if they follow no artists only one request.
How can I send a dynamic number of requests to get all artists a user follows, 50 at a time? Also the next url for the request (without auth header) is defined in res.data.artists.next