thelinmichael / spotify-web-api-node

A Node.js wrapper for Spotify's Web API.
http://thelinmichael.github.io/spotify-web-api-node/
MIT License
3.11k stars 497 forks source link

how to iterate with next options? #45

Closed twilly86 closed 8 years ago

twilly86 commented 8 years ago

I'm looking at iterating through a list of tracks in a playlist. The limit is set at 20 right now. How do I use this framework to iterate through all records? Could you point me towards an example?

Thanks!

twilly86 commented 8 years ago

This is what I came up with so far, let me know if you have any suggestions on how to improve this.

function getPlaylists( callback){

        var options = { offset: offset};
        console.log(" * getPlaylists", options);

         spotifyApi.getUserPlaylists('me',options)
            .then(function(data) {

                offset += data.body.limit;

                data.body.items.forEach(function(val, index){
                    playlists.push(val);
                });

                if(data.body.next != null){    
                    getPlaylists(callback);   
                }else{
                    console.log(data.body);
                     callback();    
                }
        });

    };
JMPerez commented 8 years ago

@twilly86 Do you want to go through the tracks of a playlist, or through the user's playlists? This is a thin wrapper that doesn't expose a way to traverse the collection, so you need to do this manually.

Generally speaking, you can either make one request after the other, as you mentioned, or you can take a different approach, a bit more complex. You could make a request for the first page of elements, then, since you know how many items are in the collection, you can make requests in parallel to get the rest of pages. Problem is you will quickly get rate limited by the API unless you add some delay between requests... so this doesn't give you a way better solution than making requests in a serial manner.

twilly86 commented 8 years ago

Good call, thanks for your help!