Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[사전 미션 - CSR을 SSR로 재구성하기] - 웨디(박세현) 미션 제출합니다. #35

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions ssr/server/constant.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
export const PATH_LIST = {
POPULAR: '/popular',
UPCOMING: '/upcoming',
TOP_RATED: '/top_rated',
NOW_PLAYING: '/now_playing',
};

export const BASE_URL = 'https://api.themoviedb.org/3/movie';
export const TMDB_THUMBNAIL_URL = 'https://media.themoviedb.org/t/p/w440_and_h660_face/';
export const TMDB_ORIGINAL_URL = 'https://image.tmdb.org/t/p/original/';
export const TMDB_BANNER_URL = 'https://image.tmdb.org/t/p/w1920_and_h800_multi_faces/';
export const TMDB_MOVIE_LISTS = {
POPULAR: BASE_URL + PATH_LIST.POPULAR + '?language=ko-KR&page=1',
NOW_PLAYING: BASE_URL + PATH_LIST.NOW_PLAYING + '?language=ko-KR&page=1',
TOP_RATED: BASE_URL + PATH_LIST.TOP_RATED + '?language=ko-KR&page=1',
UPCOMING: BASE_URL + PATH_LIST.UPCOMING + '?language=ko-KR&page=1',
};
export const TMDB_MOVIE_DETAIL_URL = 'https://api.themoviedb.org/3/movie/';

export const FETCH_OPTIONS = {
method: 'GET',
headers: {
accept: 'application/json',
Authorization: 'Bearer ' + process.env.TMDB_TOKEN,
},
};
26 changes: 26 additions & 0 deletions ssr/server/parse.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { round } from '../../csr/src/utils.js';
import { TMDB_ORIGINAL_URL } from './constant.js';

export const parseMovieItem = (movieItemData) => {
return {
id: movieItemData.id,
title: movieItemData.title,
rate: movieItemData.vote_average,
background: movieItemData.backdrop_path,
};
};

export const parseMovieList = (movieList) => {
return movieList.results.map((item) => parseMovieItem(item));
};

export const parseMovieDetail = (movieDetail) => {
return {
title: movieDetail.title,
bannerUrl: TMDB_ORIGINAL_URL + movieDetail.poster_path,
releaseYear: movieDetail.release_date.split('-')[0],
description: movieDetail.overview,
genres: movieDetail.genres.map(({ name }) => name),
rate: round(movieDetail.vote_average, 1),
};
};
197 changes: 187 additions & 10 deletions ssr/server/routes/index.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,198 @@
import { Router } from "express";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { Router } from 'express';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import {
FETCH_OPTIONS,
PATH_LIST,
TMDB_BANNER_URL,
TMDB_MOVIE_DETAIL_URL,
TMDB_MOVIE_LISTS,
TMDB_THUMBNAIL_URL,
} from '../constant.js';
import { parseMovieDetail, parseMovieList } from '../parse.js';
import { convertToPath } from '../utils.js';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const router = Router();

router.get("/", (_, res) => {
const templatePath = path.join(__dirname, "../../views", "index.html");
const moviesHTML = "<p>들어갈 본문 작성</p>";
const fetchMovies = async (type) => {
const response = await fetch(TMDB_MOVIE_LISTS[type], FETCH_OPTIONS);
const data = await response.json();

const template = fs.readFileSync(templatePath, "utf-8");
const renderedHTML = template.replace("<!--${MOVIE_ITEMS_PLACEHOLDER}-->", moviesHTML);
return parseMovieList(data);
};

res.send(renderedHTML);
const renderMovieList = (movieList = []) => {
return movieList.map(
({ id, title, background, rate }) => /*html*/ `
<li>
<a href="/detail/${id}">
<div class="item">
<img
class="thumbnail"
src="${TMDB_THUMBNAIL_URL}/${background}"
alt="${title}"
/>
<div class="item-desc">
<p class="rate"><img src="../assets/images/star_empty.png" class="star" />
<!-- 이미지 경로는 index.html파일의 위치부터 상대경로임 -->
<span>${rate}</span></p>
<strong>${title}</strong>
</div>
</div>
</a>
</li>
`,
);
};

const getFile = (filePath, fileName) => {
const compositedFilePate = path.join(__dirname, filePath, fileName);
return fs.readFileSync(compositedFilePate, 'utf-8');
};

const renderTabList = (type) => {
const curPath = convertToPath(type);
const tabList = [
{ path: PATH_LIST.NOW_PLAYING, name: '상영중' },
{ path: PATH_LIST.POPULAR, name: '인기순' },
{ path: PATH_LIST.TOP_RATED, name: '평점순' },
{ path: PATH_LIST.UPCOMING, name: '상영 예정' },
];

return tabList.map(
({ path, name }) => /*html*/ `
<li>
<a href='${path}'>
<div class="tab-item ${curPath === path ? 'selected' : ''}">
<h3>${name}</h3>
</div>
</a>
</li>
`,
);
};

const renderMovieListPage = async (type) => {
const movieList = await fetchMovies(type);
const topRatedMovie = movieList[0];

let HTMLTemplate = getFile('../../views', 'index.html');

const movieListHTML = renderMovieList(movieList).join('');
const tabListHTML = renderTabList(type).join('');

HTMLTemplate = HTMLTemplate.replace('<!--${MOVIE_ITEMS_PLACEHOLDER}-->', movieListHTML);
HTMLTemplate = HTMLTemplate.replace('<!--${TAB_ITEMS_PLACEHOLDER}-->', tabListHTML);
HTMLTemplate = HTMLTemplate.replace('${background-container}', TMDB_BANNER_URL + topRatedMovie.background);
HTMLTemplate = HTMLTemplate.replace('${bestMovie.rate}', topRatedMovie.rate);
HTMLTemplate = HTMLTemplate.replace('${bestMovie.title}', topRatedMovie.title);

return HTMLTemplate;
};

const fetchMovieDetail = async (movieId) => {
const response = await fetch(TMDB_MOVIE_DETAIL_URL + movieId, FETCH_OPTIONS);
const data = await response.json();

return parseMovieDetail(data);
};

const renderMovieDetailModalHTML = ({ bannerUrl, title, releaseYear, description, genres, rate }) => {
return /*html*/ `
<div class='modal-background active' id='modalBackground'>
<div class='modal'>
<button class='close-modal' id='closeModal'>
<img src='../assets/images/modal_button_close.png' />
</button>
<div class='modal-container'>
<div class='modal-image'>
<img src="${bannerUrl}" />
</div>
<div class='modal-description'>
<h2>${title}</h2>
<p class='category'>${releaseYear}, ${genres}</p>
<p class='rate'>
<img src='../assets/images/star_filled.png' class='star' />
<span>${rate}</span>
</p>
<hr />
<p class='detail'>${description}
</p>
</div>
</div>
</div>
</div>
`;
};
const renderMovieDetailModal = async (movieId) => {
const movieDetail = await fetchMovieDetail(movieId);

let template = await renderMovieListPage('NOW_PLAYING');
template = template.replace('<!--${MODAL_AREA}-->', renderMovieDetailModalHTML(movieDetail));

return template;
};

router.get('/', async (_, res) => {
try {
res.send(await renderMovieListPage('NOW_PLAYING'));
} catch (error) {
console.error('Error fetching movies:', error);
res.status(500).send('Internal Server Error');
}
});

router.get(PATH_LIST.NOW_PLAYING, async (_, res) => {
try {
res.send(await renderMovieListPage('NOW_PLAYING'));
} catch (error) {
console.error('Error fetching movies:', error);
res.status(500).send('Internal Server Error');
}
});

router.get(PATH_LIST.TOP_RATED, async (_, res) => {
try {
res.send(await renderMovieListPage('TOP_RATED'));
} catch (error) {
console.error('Error fetching movies for TOP_RATED:', error);
res.status(500).send('Internal Server Error');
}
});

router.get(PATH_LIST.UPCOMING, async (_, res) => {
try {
res.send(await renderMovieListPage('UPCOMING'));
} catch (error) {
console.error('Error fetching movies for UPCOMING:', error);
res.status(500).send('Internal Server Error');
}
});

router.get(PATH_LIST.POPULAR, async (_, res) => {
try {
res.send(await renderMovieListPage('POPULAR'));
} catch (error) {
console.error('Error fetching movies for POPULAR:', error);
res.status(500).send('Internal Server Error');
}
});

router.get('/detail/:id', async (req, res) => {
const { id } = req.params; // URL 파라미터에서 id 추출

try {
console.log(`Fetching details for movie with ID: ${id}`);
// 예: 특정 영화의 상세 정보를 가져오는 함수를 호출할 수 있습니다.
res.send(await renderMovieDetailModal(id)); // ID를 전달하는 경우
} catch (error) {
console.error('Error fetching movies for DETAIL:', error);
res.status(500).send('Internal Server Error');
}
});

export default router;
3 changes: 3 additions & 0 deletions ssr/server/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const convertToPath = (key) => {
return '/' + key.toLowerCase();
};
29 changes: 1 addition & 28 deletions ssr/views/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -31,34 +31,7 @@ <h1 class="logo"><img src="../assets/images/logo.png" alt="MovieList" /></h1>
</header>
<div class="container">
<ul class="tab">
<li>
<a href="/now-playing">
<div class="tab-item">
<h3>상영 중</h3>
</div></a
>
</li>
<li>
<a href="/popular"
><div class="tab-item">
<h3>인기순</h3>
</div></a
>
</li>
<li>
<a href="/top-rated"
><div class="tab-item">
<h3>평점순</h3>
</div></a
>
</li>
<li>
<a href="/upcoming"
><div class="tab-item">
<h3>상영 예정</h3>
</div></a
>
</li>
<!--${TAB_ITEMS_PLACEHOLDER}-->
</ul>
<main>
<section>
Expand Down