You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
97 lines
2.9 KiB
97 lines
2.9 KiB
const axios = require('axios');
|
|
const qs = require('qs');
|
|
require('dotenv').config();
|
|
|
|
const client_id = process.env.SPOTIFY_API_ID; // Your client id
|
|
const client_secret = process.env.SPOTIFY_CLIENT_SECRET; // Your secret
|
|
const auth_token = Buffer.from(`${client_id}:${client_secret}`, 'utf-8').toString('base64');
|
|
|
|
const getAuth = async () => {
|
|
try {
|
|
//make post request to SPOTIFY API for access token, sending relavent info
|
|
const token_url = 'https://accounts.spotify.com/api/token';
|
|
const data = qs.stringify({ 'grant_type': 'client_credentials' });
|
|
|
|
const response = await axios.post(token_url, data, {
|
|
headers: {
|
|
'Authorization': `Basic ${auth_token}`,
|
|
'Content-Type': 'application/x-www-form-urlencoded'
|
|
}
|
|
})
|
|
//return access token
|
|
return response.data.access_token;
|
|
//console.log(response.data.access_token);
|
|
} catch (error) {
|
|
//on fail, log the error in console
|
|
console.log(error);
|
|
}
|
|
}
|
|
|
|
const getFirstTrackAlbum = async (album_id) => {
|
|
//request token using getAuth() function
|
|
const access_token = await getAuth();
|
|
//console.log(access_token);
|
|
|
|
const api_url = `https://api.spotify.com/v1/albums/${album_id}/tracks`;
|
|
//console.log(api_url);
|
|
try {
|
|
const response = await axios.get(api_url, {
|
|
headers: {
|
|
'Authorization': `Bearer ${access_token}`
|
|
}
|
|
})
|
|
.then(function (response) {
|
|
// handle success
|
|
// console.log(response.data);
|
|
|
|
let firstTrack = response.data.items[0].name;
|
|
console.log("First Track: " + firstTrack);
|
|
|
|
return response.data;
|
|
|
|
});;
|
|
//console.log(response.data);
|
|
// return response.data;
|
|
} catch (error) {
|
|
console.log(error);
|
|
}
|
|
};
|
|
|
|
const getFirstArtistAlbums = async (artist_id) => {
|
|
//request token using getAuth() function
|
|
const access_token = await getAuth();
|
|
//console.log(access_token);
|
|
|
|
const api_url = `https://api.spotify.com/v1/artists/${artist_id}/albums`;
|
|
//console.log(api_url);
|
|
try {
|
|
const response = await axios.get(api_url, {
|
|
headers: {
|
|
'Authorization': `Bearer ${access_token}`
|
|
}
|
|
})
|
|
.then(function (response) {
|
|
// handle success
|
|
// console.log(response.data);
|
|
let firstAlbum = response.data.items[0].name;
|
|
let firstAlbumId = response.data.items[0].id;
|
|
|
|
console.log("First Album: " + firstAlbum);
|
|
console.log("First Album id: " + firstAlbumId);
|
|
|
|
getFirstTrackAlbum(firstAlbumId);
|
|
|
|
return response.data;
|
|
|
|
});
|
|
// console.log(response.data);
|
|
} catch (error) {
|
|
console.log(error);
|
|
}
|
|
};
|
|
|
|
// console.log(getFirstArtistAlbums('0TnOYISbd1XYRBk9myaseg'));
|
|
getFirstArtistAlbums('0TnOYISbd1XYRBk9myaseg');
|
|
|
|
|