/
spotify.ts
97 lines (95 loc) 路 2.58 KB
/
spotify.ts
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import { NowRequest, NowResponse } from "@now/node";
import { writeGitHubFile } from "../helpers/github";
import SpotifyAPI from "spotify-web-api-node";
import { safeDump } from "js-yaml";
import {
cleanSpotifyArtistsResponse,
cleanSpotifyTracksResponse
} from "../helpers/spotify";
const spotify = new SpotifyAPI({
clientId: process.env.SPOTIFY_CLIENT_ID,
clientSecret: process.env.SPOTIFY_CLIENT_SECRET,
redirectUri: "https://anandchowdhary.com/test-callback",
accessToken: process.env.SPOTIFY_ACCESS_TOKEN,
refreshToken: process.env.SPOTIFY_REFRESH_TOKEN
});
export default async (req: NowRequest, res: NowResponse) => {
try {
const data = await spotify.refreshAccessToken();
spotify.setAccessToken(data.body.access_token);
if (!req.query.tracks) {
const longTermArtists = cleanSpotifyArtistsResponse(
(
await spotify.getMyTopArtists({
time_range: "long_term"
})
).body.items
);
const mediumTermArtists = cleanSpotifyArtistsResponse(
(
await spotify.getMyTopArtists({
time_range: "medium_term"
})
).body.items
);
const shortTermArtists = cleanSpotifyArtistsResponse(
(
await spotify.getMyTopArtists({
time_range: "short_term"
})
).body.items
);
await writeGitHubFile(
"AnandChowdhary/life-data",
"top-artists.yml",
`馃幍 ${[...shortTermArtists]
.slice(0, 5)
.map(i => i.name)
.join(", ")}`,
safeDump({
longTermArtists,
mediumTermArtists,
shortTermArtists
})
);
}
const longTermTracks = cleanSpotifyTracksResponse(
(
await spotify.getMyTopTracks({
time_range: "long_term"
})
).body.items
);
const mediumTermTracks = cleanSpotifyTracksResponse(
(
await spotify.getMyTopTracks({
time_range: "medium_term"
})
).body.items
);
const shortTermTracks = cleanSpotifyTracksResponse(
(
await spotify.getMyTopTracks({
time_range: "short_term"
})
).body.items
);
await writeGitHubFile(
"AnandChowdhary/life-data",
"top-tracks.yml",
`馃幍 ${[...shortTermTracks]
.slice(0, 5)
.map(i => i.name)
.join(", ")}`,
safeDump({
longTermTracks,
mediumTermTracks,
shortTermTracks
})
);
res.json({ done: true });
} catch (error) {
res.status(500);
res.json({ error: "Unable to add Spotify data" });
}
};