Skip to content

Instantly share code, notes, and snippets.

@jonchretien
Last active June 9, 2019 14:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonchretien/2265b2f6769ef7fdbd908937f554cd69 to your computer and use it in GitHub Desktop.
Save jonchretien/2265b2f6769ef7fdbd908937f554cd69 to your computer and use it in GitHub Desktop.
Retrieve a unique list of my top albums on Spotify
#!/usr/bin/env node
// module dependencies
const fs = require('fs');
const axios = require('axios');
const config = require('../config/local');
/**
* Request my top albums from the Spotify API.
*/
async function getTopAlbums() {
try {
const response = await axios({
url: 'https://api.spotify.com/v1/me/top/tracks',
method: 'get',
params: {
time_range: 'medium_term',
limit: '10',
offset: '5',
},
headers: {
Authorization: `Bearer ${config.bearer_token}`,
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
},
});
return response.data.items;
} catch (error) {
console.error('😵 Oh nose!', error.response.status);
}
}
/**
* Normalize album data.
*/
function normalizeAlbumData(albums) {
return albums.reduce((accum, curr) => {
const artistNames = accum.map(val => val.artist_name);
const currentArtist = curr.artists[0].name;
if (artistNames.includes(currentArtist)) {
return accum;
}
const music = {
artist_name: currentArtist,
cover_art: curr.album.images[0].url,
release_name: curr.album.name,
url: curr.album.external_urls.spotify,
};
return accum.concat(music);
}, []);
}
/**
* Write normalized data to JSON file.
*/
function generateJson(normalized) {
fs.writeFileSync(
'source/data/my-top-albums.json',
JSON.stringify(normalized, null, 2)
);
}
getTopAlbums().then(response => {
const normalized = normalizeAlbumData(response);
generateJson(normalized);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment