4.1 - Projects page

Introduction

On the leftside of the dashboard a list with Spotify playlists of the user is displayed: Schermafbeelding 2020-06-17 om 14 54 25

Users can open a playlist by clicking on it 629bfabf10628fc76f56a1163ea81f56

How it works

An eventlistener is attached to each project link:

links.forEach(link => {

link.addEventListener('click', function(event){
...
   })

 })

})

What happens on the click events:

    // the default behaviour of the anchor tag is caught of
    event.preventDefault()
    // href attribute if each anchor is caught, which consists of the page it is referring to and the playlist id
    const url = link.getAttribute('href')
    // then a fetch to our own server is made with the id and token passed, these are used on the server to fetch the right playlist the Spotify api
    fetch(url + '?query=' + link.id + '&async=true' + '&token=' + token + '&id=' + link.id)
    .then(res => res.text())
    .then(html => {
        // the server than renders the component, with the right data and sends this back to the client
        // the project page element is now filled with this component and set to display block
        document.querySelector('.project-page').innerHTML = html
        section.style.display = 'block'
        // if the back button is clicked the element is set back to display none
        const closeButton = document.querySelector('.close-button')
        closeButton.addEventListener('click', () => {
            section.style.display = 'none'
        })

What happens on the server:

async function projectsRoute(req, res) {

  let options = {
    // url: `https://api.spotify.com/v1/search?q=${artist}&type=track%2Cartist&market=US&limit=10&offset=5`,
    method: 'GET',
    headers: { Authorization: 'Bearer ' + req.query.token },
  };
  // gets the playlist metadata from the spotify api(title)
  const playlist = await getDataFromSpotfy(
    `https://api.spotify.com/v1/playlists/${req.query.id}`,
    options
  );
  // gets the playlist tracks from the spotify api
  const playlistTrackList = await getDataFromSpotfy(
    `https://api.spotify.com/v1/playlists/${req.query.query}/tracks`,
    options
  );

  // loops over playlist items and only returns tracks
  const trackList = playlistTrackList.items.map((track) => {
    return track.track;
  });

  // renders the project component with the right data
  res.render(__dirname + '/view/components/project.ejs', {
    trackData: trackList,
    token: req.query.token,
    playlistData: playlist,
  });
}

Last updated

Was this helpful?