-
Notifications
You must be signed in to change notification settings - Fork 2
/
ytSubs.ts
90 lines (80 loc) · 3.01 KB
/
ytSubs.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
const axios = require('axios');
require('dotenv').config();
const Airtable = require('airtable');
interface ChannelSubscribers {
[channelId: string]: string | undefined;
}
const YT_API_KEY = process.env.YT_API_KEY;
const base = new Airtable({ apiKey: process.env.AIRTABLE_API_KEY }).base('appiQY5Sa4fJ0mGYG');
const getChannelSubscribers = async (channelId: string): Promise<number | undefined> => {
try {
const res = await axios.get(
`https://www.googleapis.com/youtube/v3/channels`,
{
params: {
part: 'statistics',
id: channelId,
key: YT_API_KEY,
},
}
);
const subscriberCount: number = parseInt(res.data.items[0].statistics.subscriberCount);
return subscriberCount;
} catch (err) {
console.error(`Error fetching subscriber count for YouTube Channel ID: ${channelId}`, err);
return undefined;
}
};
const fetchAndUpdateYouTubeSubscribers = async (channelData: ChannelSubscribers): Promise<void> => {
try {
for (const channelId in channelData) {
const recordId = channelData[channelId];
const subscriberCount: number | undefined = await getChannelSubscribers(channelId);
if (subscriberCount === undefined) {
console.error(`Error fetching subscribers for YouTube Channel ID: ${channelId}`);
continue; // Skip to next iteration if subscriber count is undefined
}
base('Countries').update([
{
"id": recordId,
"fields": {
'Youtube': subscriberCount, // Updating subscriber count
}
}
], function (err, records) {
if (err) {
console.error(`Error updating YouTube subscribers for Channel ID: ${channelId}`, err);
return;
}
records.forEach(function (record) {
console.log(`YouTube Channel ID: ${channelId}, Subs Updated: ${record.get('Youtube')}`);
});
});
}
console.log('Successfully updated YouTube subscriber counts');
} catch (err) {
console.error('Error in updating YouTube subscriber counts', err);
}
};
const channelData: ChannelSubscribers = {};
base('Countries').select({
view: 'Grid view'
}).eachPage(
function page(records, fetchNextPage) {
records.forEach(function (record) {
const channelId = record.get('Youtube Channel ID'); // Getting YouTube Channel ID
const recordId = record.id;
if (channelId && recordId) {
channelData[channelId] = recordId;
}
});
fetchNextPage();
},
function done(err) {
if (err) {
console.error('Error during Airtable fetch:', err);
return;
}
fetchAndUpdateYouTubeSubscribers(channelData);
}
);