-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
75 lines (63 loc) · 2.16 KB
/
script.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
const tmdbKey = '<My API key>';
const tmdbBaseUrl = 'https://api.themoviedb.org/3';
const playBtn = document.getElementById('playBtn');
const getGenres = async() => {
const genreRequestEndpoint = '/genre/movie/list';
const requestParams = `?api_key=${tmdbKey}`;//Query string with it's key and value
const urlToFetch = `${tmdbBaseUrl}${genreRequestEndpoint}${requestParams}`;
try {
const response = await fetch(urlToFetch);
if (response.ok) {
const jsonResponse = await response.json();//Converting the response object to a JSON object to get the requested data
const genres = jsonResponse.genres;
return genres;
}
} catch(error) {
console.log(error);
}
};
const getMovies = async() => {
const selectedGenre = getSelectedGenre();
const discoverMovieEndpoint = '/discover/movie';
const requestParams = `?api_key=${tmdbKey}&with_genres=${selectedGenre}`;
const urlToFetch = `${tmdbBaseUrl}${discoverMovieEndpoint}${requestParams}`;
try {
const response = await fetch(urlToFetch);
if (response.ok) {
const jsonResponse = await response.json();
const movies = jsonResponse.results;
return movies;
}
} catch(error) {
console.log(error);
};
};
const getMovieInfo = async(movie) => {
const movieId = movie.id;
const movieEndpoint = `/movie/${movieId}`;
const requestParams = `?api_key=${tmdbKey}`;
const urlToFetch = `${tmdbBaseUrl}${movieEndpoint}${requestParams}`;
try {
const response = await fetch(urlToFetch);
if (response.ok) {
const jsonResponse = await response.json();
const movieInfo = jsonResponse;
return movieInfo;
}
} catch(error) {
console.log(error);
}
};
// Gets a list of movies and ultimately displays the info of a random movie from the list
const showRandomMovie = async() => {
const movieInfo = document.getElementById('movieInfo');
if (movieInfo.childNodes.length > 0) {
clearCurrentMovie();
};
const movies = await getMovies();
const randomMovie = getRandomMovie(movies);
const info = await getMovieInfo(randomMovie)
displayMovie(info);
};
getGenres().then(populateGenreDropdown);
playBtn.onclick = showRandomMovie;