1
votes

I am trying to do a web app that uses the Spotify API (using node.js as server) but I've recently come across a problem I can't solve. Basically, I want to compare the content of two playlists but since the API only gives 100 tracks per request, I can't find a way to get this done. I already tried to use loops inside requests but I doesn't seem to work.

request.get(options, function(error, response, body) {
var data = [];
data.push(JSON.parse(JSON.stringify(body)));
let urls = [];
for (let i = 0; i < data[0].total; i = i + data[0].limit){
  urls.push('https://api.spotify.com/v1/me/tracks?offset='+i);
}
data = [];
for (let i = 0; i < urls.length; i++) {
  options.url = urls[i];
  request.get(options, function(error, response, body) {
    let tmp = JSON.parse(JSON.stringify(body));
    let items = tmp.items
    if (items != null){
      for(let o of tmp.items) {
        data.push(o.track.name);
      }

      if (tmp.next == null){
        return res.send(JSON.stringify(data));
        console.log('done');
      }
    }
  });
}
1

1 Answers

1
votes

You could use recursion to get all tracks in a playlist. You could have a method that gets the playlist page then loop call it until you don't have any more tracks to retrieve. Just as an example, here is a possible solution in pseudo code. I've written this quickly so forgive any bugs...

function getplaylisttracks(playlistid, pagesize,offset) {
   //call 'get tracks' api with pagesize and offset
   //return response
}

var offset = 0;
var pagesize = 100;
var continueloop = true;

var result = getplaylisttracks(YOURID, pagesize, offset);

do {    
    try {
        //*** process result tracks into your array here ***
        if(result.next!=null) {
           offset = offset+pagesize;
           result = getplaylisttracks(YOURID, pagesize, offset);
        }
        else {
            continueloop = false;
        }
    }
    catch(e) { 
       //handle error here...
       continueloop = false;
    }
} 
while(continueloop);

Once you have all the tracks for each playlist you could run a comparison