How to get videos from youtube in node

Issue #417

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
class Youtube {
async getVideos(playlistId, pageToken) {
const options = {
key: clientKey,
part: 'id,contentDetails,snippet',
playlistId: playlistId,
maxResult: 100,
pageToken
}

return new Promise((resolve, reject) => {
try {
youtube.playlistItems.list(options, (error, result) => {
if (isValid(result)) {
resolve(result)
} else {
throw error
}
})
} catch (e) {
reject(e)
}
})
}
}

Response look like

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
{
"kind": "youtube#playlistItemListResponse",
"etag": "\"p4VTdlkQv3HQeTEaXgvLePAydmU/ZNTrH71d3sV6gR6BWPeamXI1HhE\"",
"nextPageToken": "CAUQAA",
"pageInfo": {
"totalResults": 32,
"resultsPerPage": 5
},
"items": [
{
"kind": "youtube#playlistItem",
"etag": "\"p4VTdlkQv3HQeTEaXgvLePAydmU/pt-bElhU3f7Q6c1Wc0URk9GJN-w\"",
"id": "UExDbDVOTTRxRDN1X0w4ZEpyV1liTEI4RmNVYW9BSERGdC4yODlGNEE0NkRGMEEzMEQy",
"snippet": {
"publishedAt": "2019-04-11T06:09:26.000Z",
"channelId": "UCuPue-GLK4nVX8klxQITIOw",
"title": "abc",
"description": "abc",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/ZefmzgLabCA/default.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/ZefmzgLabCA/mqdefault.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/ZefmzgLabCA/hqdefault.jpg",
"width": 480,
"height": 360
},
"standard": {
"url": "https://i.ytimg.com/vi/ZefmzgLabCA/sddefault.jpg",
"width": 640,
"height": 480
},
"maxres": {
"url": "https://i.ytimg.com/vi/ZefmzgLabCA/maxresdefault.jpg",
"width": 1280,
"height": 720
}
},
"channelTitle": "try! Swift Conference",
"playlistId": "PLCl5NM4qD3u_L8dJrWYbLB8FcUaoAHDFt",
"position": 0,
"resourceId": {
"kind": "youtube#video",
"videoId": "ZefmzgLabCA"
}
}
}
]
}

To handle pagination

1
2
3
4
5
6
7
8
9
async getVideosLoop(playlistId, nextPageToken, items, count) {
const response = await this.getVideos(playlistId, nextPageToken)
const newItems = items.concat(response.data.items)
if (isValid(response.data.nextPageToken) && count < 10) {
return this.getVideosLoop(playlistId, response.data.nextPageToken, newItems, count + 1)
} else {
return newItems
}
}

To get playlist title, use playlists.list

Read more

Comments