1+ const API_URL = 'https://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=502a9f510ae5c1c188565b0f0c3ffa85&page=1'
2+ const IMG_PATH = 'https://image.tmdb.org/t/p/w500/'
3+ const main = document . getElementById ( 'main' )
4+ const SEARCH_API = 'https://api.themoviedb.org/3/search/movie?api_key=502a9f510ae5c1c188565b0f0c3ffa85&query="'
5+ const search = document . getElementById ( 'search' )
6+ const form = document . getElementById ( 'form' )
7+
8+ getMovies ( API_URL )
9+
10+
11+ async function getMovies ( url ) {
12+ const res = await fetch ( url )
13+ const data = await res . json ( )
14+ showMovies ( data . results )
15+
16+ }
17+
18+ function showMovies ( movies ) {
19+ main . innerHTML = ''
20+ movies . forEach ( movie => {
21+ const { title, poster_path, vote_average, overview } = movie
22+
23+ const movieEl = document . createElement ( 'div' )
24+ movieEl . classList . add ( 'movie' )
25+ movieEl . innerHTML = `
26+
27+ <img src="${ IMG_PATH + poster_path } " alt="${ title } ">
28+ <div class="movie-info">
29+ <h3>${ title } </h3>
30+ <span class="${ getClassByRate ( vote_average ) } ">${ vote_average } </span>
31+ </div>
32+ <div class="overview">
33+ <h3>overview</h3>
34+ ${ overview }
35+ </div>
36+
37+
38+ `
39+ main . appendChild ( movieEl )
40+ } ) ;
41+
42+ }
43+
44+
45+ function getClassByRate ( vote ) {
46+ if ( vote >= 8 ) {
47+ return "green"
48+ } else if ( vote >= 5 ) {
49+ return "orange"
50+ } else {
51+ return "red"
52+ }
53+ }
54+
55+
56+
57+ form . addEventListener ( 'submit' , e => {
58+ e . preventDefault ( )
59+ const searchTerm = search . value
60+
61+ if ( searchTerm && searchTerm !== '' ) {
62+ getMovies ( SEARCH_API + searchTerm )
63+ search . value = ''
64+ } else {
65+ window . location . reload ( )
66+ }
67+ } )
0 commit comments