HaulinOats
HaulinOats

Reputation: 3878

Get current user's starred playlist or library and tracks/artists

I've researched this a fair amount and wasn't able to find anything addressing this specific topic.

I want to get all the artists in the current user's library or even just out of a specific playlist, like the 'starred' playlist.

When I try to get into the artists or tracks in a playlist, I get 'undefined' back.

Am I doing something wrong?

Here's some basic javascript I'm using to display the library object and all I get back is what's in the image, but I don't know how to get into individual tracks and artists. Any help?

require(['$api/models','$api/library'], function(models, library){
    'use strict';
    var Library = library.Library.forCurrentUser();
    console.log(Library.starred);
});

Here is an image of the model i'm getting back: https://i.sstatic.net/lY3pT.png

Upvotes: 0

Views: 115

Answers (1)

José M. Pérez
José M. Pérez

Reputation: 3279

It is slightly more complicate than that. Library.starred is a Playlist object that lazy loads the attributes. Thus, you need to pass what attributes you want to load, in this case tracks. Since tracks is a Collection you then need to perform a Snapshot and once you have the tracks you need to specify what attributes to load from the tracks.

Here is the code to fetch all the tracks from your starred playlist and print out their name and uri:

require(['$api/models','$api/library'], function(models, library){
    'use strict';
    var Library = library.Library.forCurrentUser();
    Library.starred.load('tracks').done(function(playlist) {
        playlist.tracks.snapshot().done(function(tracks) {
            var promises = [];
            // we fetch all the tracks
            for (var i = 0, l = tracks.length; i < l; i++) {
                var track = tracks.get(i);
                // fetch the information we need from the tracks
                // e.g. uri and name
                promises.push(track.load('uri', 'name'));
            }

            models.Promise.join(promises).done(function(tracksPromises) {
                tracksPromises.forEach(function(tp) {
                    console.log(tp.uri + ' - ' + tp.name);
                });
            });
        });
    });
});

Upvotes: 1

Related Questions