This repository has been archived by the owner on Aug 22, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapiRequest.js
95 lines (89 loc) · 2.46 KB
/
apiRequest.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
92
93
94
95
const { google } = require('googleapis');
const moment = require('moment');
const config = require('./config');
// initialize the Youtube API library
const youtube = google.youtube({
version: 'v3',
auth: config.apiKey,
});
async function buildSearch(query) {
const result = await youtube.search.list({
type: '',
q: query,
maxResults: 25,
part: 'snippet',
});
const searchResults = [];
const { items } = result.data;
items.forEach((item) => {
if (item.snippet.liveBroadcastContent !== 'upcoming') {
const searchObj = {};
const { kind } = item.id;
if (kind === 'youtube#video') {
searchObj.id = item.id.videoId;
searchObj.kind = 'video';
}
if (kind === 'youtube#playlist') {
searchObj.id = item.id.playlistId;
searchObj.kind = 'playlist';
}
if (kind === 'youtube#channel') {
searchObj.id = item.id.channelId;
searchObj.kind = 'channel';
}
searchObj.channelId = item.snippet.channelId;
searchObj.title = item.snippet.title;
searchObj.channelTitle = item.snippet.channelTitle;
let imageUrl;
try {
imageUrl = item.snippet.thumbnails.maxres.url;
} catch (err) {
imageUrl = item.snippet.thumbnails.high.url;
}
searchObj.imgSrc = imageUrl;
searchObj.description = item.snippet.description;
searchResults.push(searchObj);
}
});
return searchResults;
}
async function buildTrendingVideos() {
const result = await youtube.videos.list({
part: 'snippet',
videoCategoryId: '10',
chart: 'mostPopular',
regionCode: 'US',
maxResults: 25,
});
const videos = [];
const { items } = result.data;
items.forEach((item) => {
const videoObj = {};
videoObj.id = item.id;
videoObj.title = item.snippet.title;
let imageUrl;
try {
imageUrl = item.snippet.thumbnails.maxres.url;
} catch (err) {
imageUrl = item.snippet.thumbnails.high.url;
}
videoObj.imgSrc = imageUrl;
videos.push(videoObj);
});
return videos;
}
async function getDuration(videoId) {
let duration = 0;
await youtube.videos
.list({
id: videoId,
part: 'contentDetails',
})
.then((result) => {
duration = moment.duration(result.data.items[0].contentDetails.duration).asSeconds();
});
return duration;
}
module.exports.buildSearch = buildSearch;
module.exports.buildTrendingVideos = buildTrendingVideos;
module.exports.getDuration = getDuration;