#TIL 14일차(TMDB API 불러오기[2])

앙꼬·2024년 5월 8일

부트캠프

목록 보기
14/59


Step 1

   const url = `/3/movie/${movieId}?append_to_response=credits,release_dates`;
  • url에서 release_dates 부분이 영화 관람 등급에 해당하는 부분이다.
if (movieDetails.certification !== undefined) {
            certificationData = await getMovieCertifications(movieId);
            // 관람 등급 정보를 movieDetails 객체에 할당
            movieDetails.certification = certificationData.certification;
        }
 		return movieDetails;
  • 영화 상세데이터에 관람 등급이 없을 수도 있기 때문에 if문을 통해 해당 정보가 존재하는지 확인한다.
  • 등급 정보가 존재하는 경우에는 getMovieCertifications 함수를 호출하여 해당 영화의 관람 등급 정보를 가져온다.

Step 2

const url = `/3/movie/${movieId}/release_dates?language=${currentLanguage}`;
  • TMDB API에서 영화의 등급 정보를 요청하는 URL을 구성한다.
const movieCertifications = await ApiFetch(url);
        // API 응답을 받은 results 배열을 다시 변수에 할당함. (재사용)
        const certificationResults = movieCertifications.results;
  • 가져온 등급 정보는 movieCertifications 변수에 할당되고, 이를 통해 results 배열을 얻는다.
 // 영상물 등급 정보 fetch로 응답받은 배열의 길이가 0보다 길면 (데이터가 있으면) 아래 조건문을 실행함.
        if (certificationResults && certificationResults.length > 0) {
            // 배열에서 'US'가 iso_3166_1 코드로 갖는 데이터를 찾아 변수에 할당함.
            const usReleaseData = certificationResults.find(result => result.iso_3166_1 === 'US');
            // usReleaseData가 존재하고, release_dates 배열에 데이터가 0보다 길면 (데이터가 있으면) 아래 조건문을 실행함.
            if (usReleaseData && usReleaseData.release_dates.length > 0) {
                // 첫 번째 release_dates의 certification(영상물 등급 정보) 값을 변수에 재할당함.
                certification = usReleaseData.release_dates[0].certification;
            }
        }
  • certificationResults 배열이 존재하고, 길이가 0보다 큰지 확인한다.
  • usReleaseData 변수를 사용하여 ISO 3166-1 코드가 'US'인 데이터를 찾는다.
  • 만약 usReleaseData가 존재하고, release_dates 배열에 데이터가 존재한다면, 첫 번째 요소의 등급 정보를 가져온다.

Step 3

이 부분은 한/영 변환하는 분으로 기능 구현으로 인해(어쩔수 없는 부분) 코드가 좀 많이 바뀌어서 그냥 전체적으로 짧게 코드를 설명하도록 하겠다.

 let certificationHTML = '';
    // movieCertifications 변수는 영상물 등급 정보 API Fetch의 결과임. 이 객체에서 certification이라는 영상물 등급 정보가 존재하면서, 그 값이 'no information'이 아니면 아래의 조건문을 실행함.
    if (movieCertifications && movieCertifications.certification && movieCertifications.certification !== 'No Information') {
        // 로컬스토리지에 저장한 현재 언어 정보를 변수에 할당 (재사용 목적)
        let currentLanguage = localStorage.getItem('currentLanguage');
        // 현재 언어 정보가 영어일 때 TMDB에서 가져온 미국 기준 영상물 등급 정보를 detail 페이지에 출력함.
        if (currentLanguage === 'en-US') {
            certificationHTML = `
                <hr class="certification_hr">
                <h5 class="detail_certifications">${movieCertifications.certification}</h5>
            `;
            // 그러나 현재 언어 정보가 한국어일 때는 직접 한국어로 치환시켜 저장한 객체 certificationKR 에서 일치하는 프로퍼티를 찾아 값을 반환함.
        } else if (currentLanguage === 'ko-KR') {
            const certificationKey = movieCertifications.certification;
            // 치환된 영상물 등급 정보를 다시 변수에 담아서 아래 템플릿 리터럴에서 출력시킴.
            const certificationValue = certificationKR[certificationKey];
            if (certificationValue) {
                certificationHTML = `
                    <hr class="certification_hr">
                    <h5 class="detail_certifications">${certificationValue}</h5>
                `;
            }
        }
    }
  • movieCertifications, 즉 영상물 등급 정보가 존재하고 그 값이 'No Information'이 아닌 경우에만 조건문 내부의 코드가 실행된다
  • 즉 여기에 있는 html코드는 선택한 영화의 관람 등급 정보가 있을 때에만 출력된다.

Step 4

Promise.all([
        fetchMovieDetails(movieId),
        getMovieCertifications(movieId) // 관람 등급 정보도 가져오기
    ])
  • Promise.all()을 사용하면 두 작업이 모두 완료될 때까지 기다릴 수 있고, 그 후에 결과를 함께 처리할 수 있다.
  • 즉 영화 상세 데이터와 관람 등급 정보를 동시에 가져와서 화면에 표시하기 위해 필요하다.
profile
프론트 개발자 꿈꾸는 중

0개의 댓글