-
Notifications
You must be signed in to change notification settings - Fork 0
/
spotify.js
59 lines (51 loc) · 1.51 KB
/
spotify.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
require('dotenv').config();
const EleventyFetch = require('@11ty/eleventy-fetch');
const fetch = require('node-fetch');
const ARTISTS_ENDPOINT = 'https://api.spotify.com/v1/me/top/artists';
const TRACKS_ENDPOINT = 'https://api.spotify.com/v1/me/top/tracks';
const TOKEN_ENDPOINT = 'https://accounts.spotify.com/api/token';
// Only get the top 5
const LIMIT = 5;
module.exports = async function () {
// Base64 encode the auth
const auth = Buffer.from(
`${process.env.SPOTIFY_CLIENT_ID}:${process.env.SPOTIFY_CLIENT_SECRET}`,
).toString('base64');
const options = {
method: 'POST',
headers: {
Authorization: `Basic ${auth}`,
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: process.env.SPOTIFY_REFRESH_TOKEN,
}),
};
const accessToken = await fetch(TOKEN_ENDPOINT, options)
.then((res) => res.json())
.then((json) => json.access_token)
.catch(console.err);
const artists = await EleventyFetch(`${ARTISTS_ENDPOINT}?limit=${LIMIT}`, {
duration: '1h',
type: 'json',
fetchOptions: {
headers: {
Authorization: `Bearer ${accessToken}`,
},
},
});
const tracks = await EleventyFetch(`${TRACKS_ENDPOINT}?limit=${LIMIT}`, {
duration: '1h',
type: 'json',
fetchOptions: {
headers: {
Authorization: `Bearer ${accessToken}`,
},
},
});
return {
artists: artists?.items ?? [],
tracks: tracks?.items ?? [],
};
};