-
Notifications
You must be signed in to change notification settings - Fork 39
/
updateView.js
79 lines (69 loc) · 1.98 KB
/
updateView.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
const axios = require("axios");
const Youtuber = require("./models/youtuber-model");
async function getChannelViewCount(channelName, apiKey) {
const response = await axios.get(
"https://www.googleapis.com/youtube/v3/search",
{
params: {
part: "snippet",
q: channelName,
maxResults: 1,
type: "channel",
key: apiKey,
},
}
);
const channelId = response?.data?.items[0]?.id?.channelId;
const viewCount = await getChannelStatistics(channelId, apiKey);
return viewCount;
}
async function getChannelStatistics(channelId, apiKey) {
const response = await axios.get(
"https://www.googleapis.com/youtube/v3/channels",
{
params: {
part: "statistics",
id: channelId,
key: apiKey,
},
}
);
const viewCount = response?.data?.items[0]?.statistics?.viewCount;
return viewCount;
}
const getViews = async () => {
const apiKey = process.env.API_KEY;
try {
const youtubers = await Youtuber.find({});
const promises = youtubers.map(async (youtuber) => {
try {
const viewCount = await getChannelViewCount(youtuber.name, apiKey);
// Update the view field of the current youtuber
youtuber.totalViews = convert(viewCount);
// Save the updated youtuber to the database
await youtuber.save();
console.log(
"View count updated for: ",
youtuber.name + " " + youtuber.totalViews
);
} catch (err) {
console.log("Error in finding view count", err);
// Stop the program execution due to API limit error
return;
}
});
await Promise.all(promises);
} catch (err) {
console.log("Error in fetching YouTubers", err);
}
};
const convert = (count) => {
if (count > 1000000000) {
return (count / 1000000000).toFixed(1) + " billion";
} else if (count > 1000000) {
return (count / 1000000).toFixed(1) + " million";
} else {
return count;
}
};
module.exports = getViews;