-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_youtube.js
91 lines (81 loc) · 2.19 KB
/
get_youtube.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
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
import https from "node:https";
import fs from "node:fs";
const videoIdsData = JSON.parse(fs.readFileSync("./youtube_ids.json", "utf8"));
const { videoIds } = videoIdsData;
const chunkSize = 50;
const apiUrl = `https://www.googleapis.com/youtube/v3/videos?part=snippet&part=status&key=${process.env.YOUTUBE_API_KEY}&id=`;
const outputFilePath = "docs/api/youtube.json";
const fallbackData = [
{
id: "ky18YtME8UQ",
snippet: {
title: "daisyUI 3.0",
description:
"daisyUI is the most popular component library for Tailwind CSS",
channelTitle: "daisyUI",
thumbnails: {
high: {
url: "https://i.ytimg.com/vi/ky18YtME8UQ/hqdefault.jpg",
},
},
},
status: {
embeddable: true,
},
},
];
// Function to make a request to the API
function makeApiRequest(ids) {
return new Promise((resolve, reject) => {
const url = apiUrl + ids.join(",");
https
.get(url, (res) => {
let data = "";
res.on("data", (chunk) => {
data += chunk;
});
res.on("end", () => {
resolve(JSON.parse(data));
});
})
.on("error", (err) => {
reject(err);
});
});
}
// Function to chunk the videoIds array and make API requests
async function processVideoIds(videoIds) {
const results = [];
for (let i = 0; i < videoIds.length; i += chunkSize) {
const chunk = videoIds.slice(i, i + chunkSize);
const result = await makeApiRequest(chunk);
// if results has error
if (!result.error) {
results.push(result.items);
}
}
return results;
}
// Process the videoIds and save the results as JSON
processVideoIds(videoIds)
.then((results) => {
let combinedResults;
combinedResults = [].concat(...results);
if (!combinedResults.length) {
combinedResults = fallbackData;
}
fs.writeFile(
outputFilePath,
JSON.stringify(combinedResults, null, 2),
(err) => {
if (err) {
console.error("Error writing to file:", err);
} else {
console.log("Data saved to", outputFilePath);
}
},
);
})
.catch((error) => {
console.error("Error making API requests:", error);
});