-
-
Save Uvacoder/996821a53331bbe5e3da351c8a443453 to your computer and use it in GitHub Desktop.
Snippet: Get Your Spotify's Top Tracks #Spotify
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { getTopTracks } from '../../lib/spotify'; | |
| export default async (_, res) => { | |
| const response = await getTopTracks(); | |
| const { items } = await response.json(); | |
| const tracks = items.slice(0, 10).map((track) => ({ | |
| artist: track.artists.map((_artist) => _artist.name).join(', '), | |
| songUrl: track.external_urls.spotify, | |
| title: track.name | |
| })); | |
| return res.status(200).json({ tracks }); | |
| }; | |
| // lib/spotify.js | |
| import fetch from 'isomorphic-unfetch'; | |
| import querystring from 'querystring'; | |
| const client_id = process.env.SPOTIFY_CLIENT_ID; | |
| const client_secret = process.env.SPOTIFY_CLIENT_SECRET; | |
| const refresh_token = process.env.SPOTIFY_REFRESH_TOKEN; | |
| const basic = Buffer.from(`${client_id}:${client_secret}`).toString('base64'); | |
| const TOP_TRACKS_ENDPOINT = `https://api.spotify.com/v1/me/top/tracks`; | |
| const TOKEN_ENDPOINT = `https://accounts.spotify.com/api/token`; | |
| const getAccessToken = async () => { | |
| const response = await fetch(TOKEN_ENDPOINT, { | |
| method: 'POST', | |
| headers: { | |
| Authorization: `Basic ${basic}`, | |
| 'Content-Type': 'application/x-www-form-urlencoded' | |
| }, | |
| body: querystring.stringify({ | |
| grant_type: 'refresh_token', | |
| refresh_token | |
| }) | |
| }); | |
| return response.json(); | |
| }; | |
| export const getTopTracks = async () => { | |
| const { access_token } = await getAccessToken(); | |
| return fetch(TOP_TRACKS_ENDPOINT, { | |
| headers: { | |
| Authorization: `Bearer ${access_token}` | |
| } | |
| }); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment