-
Notifications
You must be signed in to change notification settings - Fork 0
/
addTracks.ts
42 lines (38 loc) · 1.01 KB
/
addTracks.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
import chalk from "npm:chalk";
export default async function addTracks(
id: string,
token: string,
uris: string[]
): Promise<void> {
function chunkArray(arr: string[]) {
const chunks = [];
for (let i = 0; i < arr.length; i += 100) {
chunks.push(arr.slice(i, i + 100));
}
return chunks;
}
const chunks = chunkArray(uris);
try {
for (const uriBatch of chunks) {
const response = await fetch(
`https://api.spotify.com/v1/playlists/${id}/tracks`,
{
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
uris: uriBatch,
}),
}
);
if (!response.ok) {
throw new Error(`Failed to add tracks: ${response.statusText}`);
}
}
console.log(chalk.green("Added tracks"));
} catch (error) {
console.error("Error adding tracks:", error);
}
}