|
1 | 1 | // Importing axios module to make get requests
|
2 | 2 | var fetch = require('axios');
|
3 | 3 |
|
4 |
| -// Importing mongo model for storing search data |
| 4 | +// Importing mongo model for storing search data and video details |
5 | 5 | var searchData = require('../models/searchModel');
|
| 6 | +var videoData = require('../models/videoModel').videoData; |
6 | 7 |
|
7 | 8 | // Importing API_KEY
|
8 |
| -const API_KEY = require('../config/apiKey'); |
| 9 | +if(process.env.API_KEY_GITHUB){ |
| 10 | + const keys = process.env.API_KEY_GITHUB; |
| 11 | +}else{ |
| 12 | + const keys = require('../config/apiKey'); |
| 13 | +} |
| 14 | + |
| 15 | +// Stores queries for which server is already updating results in background every 10 seconds. |
| 16 | +var initializedPinging = []; |
| 17 | + |
| 18 | +// Setting globally accessible currently used API_KEY variable |
| 19 | +var KEY; |
| 20 | + |
| 21 | +// Adding a prototype function to array structure to cycle through elements |
| 22 | +// This switches API_KEY upon exhausting quota of 1 ( we have 3 api keys reserved ) |
| 23 | +function switchKeys(API_KEY){ |
| 24 | + |
| 25 | + // getting current index |
| 26 | + const i = keys.indexOf(API_KEY); |
| 27 | + |
| 28 | + // getting element in next index |
| 29 | + return keys[(i + 1)%keys.length]; |
| 30 | +} |
| 31 | + |
| 32 | + |
| 33 | +// Updating search results |
| 34 | +async function updateResults(maxResults, Query, KEY){ |
| 35 | + var url = `https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&maxResults=${maxResults}&q=${Query}&type=video&key=${KEY}`; |
9 | 36 |
|
10 |
| -// Search Function which regularly refreshes search results |
11 |
| -async function SearchResults(maxResults, Query, API_KEY, first){ |
12 |
| - var url = `https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=${maxResults}&q=${Query}&type=video&key=${API_KEY}`; |
13 |
| - |
14 | 37 | try{
|
15 | 38 | var response = await fetch(url);
|
| 39 | + // finding appropriate searchData instance to update |
| 40 | + var search = await searchData.findOne({ query: Query }); |
| 41 | + |
16 | 42 | for(i in response.data.items){
|
17 | 43 | var items = response.data.items[i];
|
18 |
| - var search = new searchData({ |
| 44 | + var video = new videoData({ |
19 | 45 | title: items.snippet.title,
|
20 | 46 | description: items.snippet.description,
|
21 | 47 | thumbnail: items.snippet.thumbnails.default.url,
|
22 | 48 | publishTime: items.snippet.publishedAt
|
23 | 49 | });
|
24 |
| - var data = await search.save(); |
25 |
| - console.log(data); |
| 50 | + // updating model's videoDetails documents |
| 51 | + search.videoDetails[i] = video; |
26 | 52 | }
|
| 53 | + await search.save(); |
| 54 | + console.log(`Updated Videos for query searched by ${Query}`); |
27 | 55 | }
|
28 | 56 | catch(err){
|
29 | 57 | console.log(err);
|
30 |
| - return err; |
31 | 58 | }
|
32 | 59 |
|
33 |
| - // setTimeout(async () => { |
34 |
| - // try{ |
35 |
| - // await SearchResults(maxResults, Query, API_KEY, false); |
36 |
| - // }catch(err){ |
37 |
| - // console.log(err); |
38 |
| - // } |
39 |
| - |
40 |
| - // }, 10000); |
| 60 | + console.log(` Again Querying for following : ${initializedPinging}`); |
| 61 | + // updating search results every 10 seconds. |
| 62 | + setTimeout(async () => { |
| 63 | + try{ |
| 64 | + await updateResults(maxResults, Query, KEY); |
| 65 | + }catch(err){ |
| 66 | + console.log(err); |
| 67 | + } |
| 68 | + }, 10000); |
| 69 | +} |
| 70 | + |
| 71 | +// Search Function which regularly refreshes search results |
| 72 | +async function SearchResults(maxResults, Query, API_KEY){ |
| 73 | + |
| 74 | + var url = `https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&maxResults=${maxResults}&q=${Query}&type=video&key=${API_KEY}`; |
| 75 | + |
| 76 | + try{ |
| 77 | + //finding appropriate searchData model, according to search query |
| 78 | + var searchDB = await searchData.findOne({ query: Query }); |
| 79 | + |
| 80 | + // if user has searched for a new query, we need to fetch via yt api and wont be able to server from db |
| 81 | + if(searchDB === null){ |
| 82 | + var response = await fetch(url); |
| 83 | + |
| 84 | + // preparing new searchData model for new query |
| 85 | + var search = new searchData({ |
| 86 | + query: Query, |
| 87 | + maxResults: maxResults |
| 88 | + }); |
| 89 | + |
| 90 | + for(i in response.data.items){ |
| 91 | + var items = response.data.items[i]; |
| 92 | + var video = new videoData({ |
| 93 | + title: items.snippet.title, |
| 94 | + description: items.snippet.description, |
| 95 | + thumbnail: items.snippet.thumbnails.default.url, |
| 96 | + publishTime: items.snippet.publishedAt |
| 97 | + }); |
| 98 | + search.videoDetails.push(video); |
| 99 | + console.log(video); |
| 100 | + } |
| 101 | + var data = await search.save(); |
| 102 | + console.log(`Initializing Pinging for query ${Query}`); |
| 103 | + |
| 104 | + // storing this query in this array so that when user requests on this same query again, the updateResults is not called again |
| 105 | + // ( otherwise it will keep requesting duplicate queries to yt api, and exhaust our key quota ) |
| 106 | + initializedPinging.push(Query); |
| 107 | + await updateResults(maxResults, Query, KEY); |
| 108 | + return data; |
| 109 | + } |
| 110 | + // If query is already searched before, we directly server from our db, as db itself is updated in background. |
| 111 | + else{ |
| 112 | + console.log(`Sending results from Database for query ${Query}`); |
41 | 113 |
|
42 |
| - if(first){ |
43 |
| - return data; |
| 114 | + if(initializedPinging.includes(Query)){ |
| 115 | + console.log(`Already pinging ${Query}`); |
| 116 | + return searchDB; |
| 117 | + } |
| 118 | + // If query is searched before, but its updation is not started ( could be due to server restart ). |
| 119 | + else{ |
| 120 | + console.log(`Initializing Pinging for query ${Query}`); |
| 121 | + initializedPinging.push(Query); |
| 122 | + await updateResults(maxResults, Query, KEY); |
| 123 | + return searchDB; |
| 124 | + } |
| 125 | + } |
| 126 | + } |
| 127 | + catch(err){ |
| 128 | + // If error is due to exhaustion of api key quota, we get a 403 response code error |
| 129 | + // Then we switch to a new key |
| 130 | + if( err.message == 'Request failed with status code 403'){ |
| 131 | + console.log(`API KEY Quota has been exhausted, switching api keys . . .`); |
| 132 | + KEY = switchKeys(API_KEY); |
| 133 | + } |
| 134 | + // notifying main controller to recall search function |
| 135 | + return "Switched API_KEYS, reinitiate request"; |
| 136 | + } |
| 137 | +} |
| 138 | + |
| 139 | + |
| 140 | +// Handler to set which API_KEY to use |
| 141 | +function setKey(){ |
| 142 | + // setting for the first time and then serving currently used key. |
| 143 | + if(KEY){ |
| 144 | + return KEY; |
| 145 | + } |
| 146 | + else{ |
| 147 | + KEY = keys[1]; |
| 148 | + return KEY; |
44 | 149 | }
|
45 | 150 | }
|
46 | 151 |
|
47 |
| -var initializedPinging = 0; |
48 | 152 |
|
49 | 153 | // Controller to provide results as per request
|
50 | 154 | const provideResults = async (req, res) => {
|
51 |
| - if(initializedPinging == 0){ |
52 |
| - var maxResults = 2; |
53 |
| - var Query = req.params.id; |
| 155 | + var maxResults = 2; |
| 156 | + var Query = req.params.searchquery; |
| 157 | + |
| 158 | + // setting initial key for every new request |
| 159 | + var key = setKey(); |
| 160 | + var data = await SearchResults(maxResults, Query, key); |
54 | 161 |
|
55 |
| - var data = await SearchResults(maxResults, Query, API_KEY, true); |
56 |
| - res.status(200).json(data); |
57 |
| - initializedPinging = 1 |
| 162 | + // if key was switched, we need to recall search function, before sending the response to user. |
| 163 | + if( data == "Switched API_KEYS, reinitiate request" ){ |
| 164 | + var data = await SearchResults(maxResults, Query, KEY); |
58 | 165 | }
|
| 166 | + |
| 167 | + res.status(200).json(data); |
59 | 168 | }
|
60 | 169 |
|
61 | 170 | module.exports = {
|
|
0 commit comments