-
Notifications
You must be signed in to change notification settings - Fork 0
/
channel-broadcasts.js
76 lines (60 loc) · 2.42 KB
/
channel-broadcasts.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
// URL utility
import url from 'url'
// Google API (Which contains the Youtube API)
import { google } from 'googleapis'
module.exports = async function (req, res) {
// Break out the id param from our request's query string
const { query: { id } } = url.parse(req.url, true)
const perPage = 50
// Setup Youtube API V3 Service instance
const service = google.youtube('v3')
// Fetch data from the Youtube API
const { errors = null, data = null } = await service.search.list({
key: process.env.GOOGLE_API_KEY,
part: 'snippet',
channelId: id,
type: 'video',
eventType: 'live',
order: 'date',
maxResults: perPage
}).catch(({ errors }) => {
console.log('Error fetching broadcasts', errors)
return {
errors
}
})
// Set Cors Headers to allow all origins so data can be requested by a browser
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
// Send an error response if something went wrong
if (errors !== null) {
res.json({
errors: 'Error fetching broadcasts'
})
return
}
const items = data.items
// If there are more results then push them to our list of broadcasts
if (data.nextPageToken !== null) {
// Store the token for page #2 into our variable
let pageToken = data.nextPageToken
while (pageToken !== null) {
// Fetch data from the Youtube API
const youtubePageResponse = await service.search.list({
key: process.env.GOOGLE_API_KEY,
part: 'snippet',
channelId: id,
type: 'video',
eventType: 'live',
order: 'date',
pageToken: pageToken
})
// Add the videos from this page on to our total items list
youtubePageResponse.data.items.forEach(item => items.push(item))
// Now that we're done set up the next page token or empty out the pageToken variable so our loop will stop
pageToken = ('nextPageToken' in youtubePageResponse.data) ? youtubePageResponse.data.nextPageToken : null
}
}
console.log(`Fetched ${items.length} broadcast${(items.length !== 1) ? '' : 's'} from https://www.youtube.com/channel/${id}`)
res.json(items)
}