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로 재구성하기] - 파란(안영훈) 미션 제출합니다. #38

Open
wants to merge 1 commit 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
99 changes: 94 additions & 5 deletions ssr/server/routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,109 @@ import { Router } from "express";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import {
fetchMovieDetails,
fetchNowPlayingMovieItems,
fetchPopularMovieItems,
fetchTopRatedMovieItems,
fetchUpcomingMovieItems,
} from "../../src/apis/movies.js";
import renderMovieList from "../../src/render/renderMovieList.js";
import renderHeader from "../../src/render/renderHeader.js";
import renderModal from "../../src/render/renderModal.js";

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

const router = Router();

router.get("/", (_, res) => {
const fetchMovieItems = async (path) => {
switch (path) {
case "/":
case "/now-playing":
return await fetchNowPlayingMovieItems();
case "/popular":
return await fetchPopularMovieItems();
case "/top-rated":
return await fetchTopRatedMovieItems();
case "/upcoming":
return await fetchUpcomingMovieItems();
default:
throw new Error("Invalid path.");
}
};

const getTemplate = (templatePath) => fs.readFileSync(templatePath, "utf-8");

const getSectionTitles = () => ({
"/now-playing": "상영 중인 영화",
"/popular": "지금 인기 있는 영화",
"/top-rated": "평점이 높은 영화",
"/upcoming": "개봉 예정 영화",
});

const replaceTemplatePlaceholders = (
template,
headerHTML,
moviesHTML,
sectionTitle,
movieModalHTML = ""
) => {
return template
.replace("<!--${HEADER_PLACEHOLDER}-->", headerHTML)
.replace(/\$\{sectionTitle\}/g, sectionTitle)
.replace("<!--${MOVIE_ITEMS_PLACEHOLDER}-->", moviesHTML)
.replace("<!--${MODAL_AREA}-->", movieModalHTML);
};

const renderPage = async (req, res, isModal = false) => {
const templatePath = path.join(__dirname, "../../views", "index.html");
const moviesHTML = "<p>들어갈 본문 작성</p>";
const currentPath =
req.path === "/" || req.path.startsWith("/detail")
? "/now-playing"
: req.path;
const movies = await fetchMovieItems(currentPath);
const featuredMovie = movies[0];
const headerHTML = renderHeader(featuredMovie);
const moviesHTML = renderMovieList(movies);
const sectionTitles = getSectionTitles();
let template = getTemplate(templatePath);

const template = fs.readFileSync(templatePath, "utf-8");
const renderedHTML = template.replace("<!--${MOVIE_ITEMS_PLACEHOLDER}-->", moviesHTML);
template = template.replace(
/<div class="tab-item ([^"]+)">/g,
(_, tabName) => {
const isSelected =
currentPath === `/${tabName}` ||
(currentPath === "/now-playing" && tabName === "now-playing");
return `<div class="tab-item ${tabName}${
isSelected ? " selected" : ""
}">`;
}
);

let movieModalHTML = "";
if (isModal) {
const id = req.params.id;
const movieDetail = await fetchMovieDetails(id);
movieModalHTML = renderModal(movieDetail);
}

const renderedHTML = replaceTemplatePlaceholders(
template,
headerHTML,
moviesHTML,
sectionTitles[currentPath],
movieModalHTML
);

res.send(renderedHTML);
});
};

router.get("/", (req, res) => renderPage(req, res));
router.get("/now-playing", (req, res) => renderPage(req, res));
router.get("/popular", (req, res) => renderPage(req, res));
router.get("/top-rated", (req, res) => renderPage(req, res));
router.get("/upcoming", (req, res) => renderPage(req, res));
router.get("/detail/:id", (req, res) => renderPage(req, res, true));

export default router;
47 changes: 47 additions & 0 deletions ssr/src/apis/movies.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import {
FETCH_OPTIONS,
TMDB_MOVIE_DETAIL_URL,
TMDB_MOVIE_LISTS,
} from "../constants.js";

export const fetchPopularMovieItems = async () => {
const response = await fetch(TMDB_MOVIE_LISTS.POPULAR, FETCH_OPTIONS);

const data = await response.json();

return data.results;
};

export const fetchNowPlayingMovieItems = async () => {
const response = await fetch(TMDB_MOVIE_LISTS.NOW_PLAYING, FETCH_OPTIONS);

const data = await response.json();

return data.results;
};

export const fetchTopRatedMovieItems = async () => {
const response = await fetch(TMDB_MOVIE_LISTS.TOP_RATED, FETCH_OPTIONS);

const data = await response.json();

return data.results;
};

export const fetchUpcomingMovieItems = async () => {
const response = await fetch(TMDB_MOVIE_LISTS.UPCOMING, FETCH_OPTIONS);

const data = await response.json();

return data.results;
};

export const fetchMovieDetails = async (id) => {
const url = `${TMDB_MOVIE_DETAIL_URL}${id}?language=ko-KR`;

const response = await fetch(url, FETCH_OPTIONS);

const data = await response.json();

return data;
};
22 changes: 22 additions & 0 deletions ssr/src/constants.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
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 + "/popular?language=ko-KR&page=1",
NOW_PLAYING: BASE_URL + "/now_playing?language=ko-KR&page=1",
TOP_RATED: BASE_URL + "/top_rated?language=ko-KR&page=1",
UPCOMING: BASE_URL + "/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,
},
};
31 changes: 31 additions & 0 deletions ssr/src/render/renderHeader.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
const renderHeader = (bestMovie) => {
return /*html*/ `
<header>
<div
class="background-container"
style="background-image: url('https://media.themoviedb.org/t/p/original${
bestMovie.backdrop_path
}')"
>
<div class="overlay" aria-hidden="true"></div>
<div class="top-rated-container">
<h1 class="logo">
<img src="../assets/images/logo.png" alt="MovieList" />
</h1>
<div class="top-rated-movie">
<div class="rate">
<img src="../assets/images/star_empty.png" class="star" />
<span class="rate-value">${
Math.round(bestMovie.vote_average * 10).toFixed(1) / 10
}</span>
</div>
<div class="title">${bestMovie.title}</div>
<button class="primary detail">자세히 보기</button>
</div>
</div>
</div>
</header>
`;
};

export default renderHeader;
39 changes: 39 additions & 0 deletions ssr/src/render/renderModal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
const renderModal = (movieDetail) => {
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="https://image.tmdb.org/t/p/original/${
movieDetail.poster_path
}.jpg" />
</div>
<div class="modal-description">
<h2>${movieDetail.title}</h2>
<p class="category">${
movieDetail.release_date.split("-")[0]
} · ${movieDetail.genres.map(({ name }) => name).join(", ")}</p>
<p class="rate"><img src="../assets/images/star_filled.png" class="star" /><span>7.7</span></p>
<hr />
<p class="detail">
${movieDetail.overview}
</p>
</div>
</div>
</div>
</div>
<!-- 모달 창 닫기 스크립트 -->
<script>
const modalBackground = document.getElementById("modalBackground");
const closeModal = document.getElementById("closeModal");
document.addEventListener("DOMContentLoaded", () => {
closeModal.addEventListener("click", () => {
modalBackground.classList.remove("active");
});
});
</script>
`;
};

export default renderModal;
26 changes: 26 additions & 0 deletions ssr/src/render/renderMovieList.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const renderMovieList = (movieItems = []) =>
movieItems
.map(
({ id, title, poster_path, vote_average }) => /*html*/ `
<li>
<a href="/detail/${id}">
<div class="item">
<img
class="thumbnail"
src="https://image.tmdb.org/t/p/w440_and_h660_face/${poster_path}"
alt="${title}"
/>
<div class="item-desc">
<p class="rate"><img src="../assets/images/star_empty.png" class="star" /><span>${
Math.round(vote_average * 10).toFixed(1) / 10
}</span></p>
<strong>${title}</strong>
</div>
</div>
</a>
</li>
`
)
.join("");

export default renderMovieList;
19 changes: 2 additions & 17 deletions ssr/views/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -13,22 +13,7 @@
</head>
<body>
<div id="wrap">
<header>
<div class="background-container" style="background-image: url('${background-container}')">
<div class="overlay" aria-hidden="true"></div>
<div class="top-rated-container">
<h1 class="logo"><img src="../assets/images/logo.png" alt="MovieList" /></h1>
<div class="top-rated-movie">
<div class="rate">
<img src="../assets/images/star_empty.png" class="star" />
<span class="rate-value">${bestMovie.rate}</span>
</div>
<div class="title">${bestMovie.title}</div>
<button class="primary detail">자세히 보기</button>
</div>
</div>
</div>
</header>
<!--${HEADER_PLACEHOLDER}-->
<div class="container">
<ul class="tab">
<li>
Expand Down Expand Up @@ -62,7 +47,7 @@ <h3>상영 예정</h3>
</ul>
<main>
<section>
<h2>지금 인기 있는 영화</h2>
<h2>${sectionTitle}</h2>
<ul class="thumbnail-list">
<!--${MOVIE_ITEMS_PLACEHOLDER}-->
</ul>
Expand Down