Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Spotify API: Check If A Playlist With A Specific Name Already Exists

JavaScript

const user_id = localStorage.getItem("spotify_example_user_id")
const access_token = localStorage.getItem("spotify_example_access_token")

const checkIfPlaylistExists = async (checkName) => {
  let exists = false
  let maxLoopCount = 20
  for (let i=0; i<maxLoopCount; i++) {
    const url = new URL(`https://api.spotify.com/v1/me/playlists`)
    const params = {
      offset: 50 * i,
      limit: 50
    }
    url.search = new URLSearchParams(params).toString()
    const payload = {
      method: 'GET',
      headers: {
        'Authorization': `Bearer  ${access_token}`
      },
    }
    const body = await fetch(url, payload)
    const response = await body.json()
    if (!response.next) {
      i = maxLoopCount
    }
    response.items.forEach((item) => {
      if (item.name === checkName) {
        exists = true
        i = maxLoopCount
      }
    })
  }
  return exists 
}

document.addEventListener("DOMContentLoaded", async () => {
  if (user_id) {
    console.log(await checkIfPlaylistExists("aws test 2"))
  }
})