Skip to content

Commit

Permalink
fix: 🐛 All of the user's playlists are now fetched (instead of only 20)
Browse files Browse the repository at this point in the history
Fixes #75, fixes #47
  • Loading branch information
EricLambrecht committed Oct 13, 2019
1 parent ec9b7f0 commit d71fa23
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 13 deletions.
1 change: 1 addition & 0 deletions src/components/init/AppInitializer.vue
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export default {
try {
this.status = 'Authenticating...'
await this.$store.dispatch('user/requestToken')
this.status = 'Fetching playlists...'
await this.$router.replace({ name: 'home' })
} catch (e) {
if (e.trigger_login) {
Expand Down
33 changes: 20 additions & 13 deletions src/utils/Spotify.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,21 @@ export default class Spotify {
* @returns {Promise<Object>}
* @throws
*/
static async getUserPlaylists(options = {}) {
static async getUserPlaylists(options = { offset: 0, limit: 50 }) {
const apiResult = await api.getUserPlaylists(options)
let numberOfFetchedPlaylists = apiResult.items.length + apiResult.offset

// Do we have all playlists yet?
while (numberOfFetchedPlaylists < apiResult.total) {
// eslint-disable-next-line no-await-in-loop
const nextSlice = await api.getUserPlaylists({
offset: numberOfFetchedPlaylists,
limit: 50,
})
apiResult.items = apiResult.items.concat(nextSlice.items)
numberOfFetchedPlaylists = apiResult.items.length + apiResult.offset
}

return apiResult.items
}

Expand All @@ -85,19 +98,10 @@ export default class Spotify {
* @throws
*/
static async getPlaylistSlice(playlistId, offset = 0, limit = 0) {
const tracks = await api.getPlaylistTracks(playlistId, {
return api.getPlaylistTracks(playlistId, {
limit,
offset,
})
const numberOfFetchedTracks = tracks.items.length + tracks.offset
if (numberOfFetchedTracks < tracks.total) {
const remainingTracks = await Spotify.getTracks(
numberOfFetchedTracks,
100
)
tracks.items = tracks.items.concat(remainingTracks.items)
}
return tracks
}

/**
Expand All @@ -110,15 +114,18 @@ export default class Spotify {
const playlist = await api.getPlaylist(playlistId)

// Do we have all tracks?
const numberOfFetchedTracks =
let numberOfFetchedTracks =
playlist.tracks.items.length + playlist.tracks.offset
if (numberOfFetchedTracks < playlist.tracks.total) {
while (numberOfFetchedTracks < playlist.tracks.total) {
// eslint-disable-next-line no-await-in-loop
const nextSlice = await Spotify.getPlaylistSlice(
playlistId,
numberOfFetchedTracks,
100
)
playlist.tracks.items = playlist.tracks.items.concat(nextSlice.items)
numberOfFetchedTracks =
playlist.tracks.items.length + playlist.tracks.offset
}
return playlist
}
Expand Down

0 comments on commit d71fa23

Please sign in to comment.