-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApi_movies.js
65 lines (52 loc) · 1.76 KB
/
Api_movies.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
const https = require('https');
const apiUrl = "https://jsonmock.hackerrank.com/api/moviesdata/search/?Title="
const movieTitles = "spiderman"
function makeCall(reqUrl, titles, substr) {
let result = '';
return new Promise( (resolve, reject) => {
https.get(reqUrl, (res) => {
res.on('data', (d) => {
result += d;
});
res.on('end', () => {
try {
if (typeof result === 'string') result = JSON.parse(result);
}
catch(err) {
return reject([]);
}
let page = result.page;
let total_pages = result.total_pages;
let title = result.data;
for(let i = 0; i<title.length; i++){
titles.push(title[i].Title);
}
if (page == total_pages) {
return resolve(titles);
} else {
let url = apiUrl + substr + "&page=" + Number(Number(page) + 1);
return resolve(makeCall(url, titles, substr));
}
});
}).on('error', (e) => {
console.error(e);
reject(e);
});
});
}
function getMovies(substr) {
let reqUrl = apiUrl + substr;
let titles = [];
return new Promise( (resolve, reject) => {
makeCall(reqUrl, titles, substr)
.then( result => {
titles = result.sort();
resolve(titles);
});
});
}
getMovies(movieTitles).then(result => {
console.log("list of " + movieTitles + " movies")
console.log(result);
console.log("total movies : " + result.length);
});