-
Notifications
You must be signed in to change notification settings - Fork 0
/
getAlbumTracks.ts
56 lines (47 loc) · 1.25 KB
/
getAlbumTracks.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
async function getAlbumTracks(
id: string,
token: string
): Promise<string[] | null> {
const headers = new Headers({
Authorization: `Bearer ${token}`,
Accept: "application/json",
"Content-Type": "application/json",
});
try {
const res = await fetch(
`https://api.spotify.com/v1/albums/${id}/tracks?limit=50`,
{
method: "GET",
headers,
}
);
if (!res.ok) {
console.error(`Error: ${res.status} - ${res.statusText}`);
return null;
}
const data = await res.json();
const trackUris = data.items.map((track: { uri: string }) => track.uri);
return trackUris;
} catch (error) {
console.error(`Error getting tracks for ${id}`, error);
throw error;
}
}
export default async function getAllTracks(
ids: string[],
token: string
): Promise<string[] | null> {
// Pass index to keep the albums in order
const promises = ids.map((id, index) =>
getAlbumTracks(id, token).then((uris) => ({
uris,
index,
}))
);
const results = await Promise.all(promises);
results.sort((a, b) => a.index - b.index);
return results
.map(({ uris }) => uris)
.filter((id) => id !== null)
.flat();
}