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로 재구성하기] - 해리(최현웅) 미션 제출합니다. #28

Open
wants to merge 6 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
24 changes: 24 additions & 0 deletions ssr/apis/movie.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import {
FETCH_OPTIONS,
TMDB_MOVIE_DETAIL_URL,
TMDB_MOVIE_LISTS,
} from "../constants/api.js";

export const fetchMovies = async (movieType) => {
const fetchEndPoint = TMDB_MOVIE_LISTS[movieType];

const response = await fetch(fetchEndPoint, FETCH_OPTIONS);
const allMovieData = await response.json();

return allMovieData.results;
};

export const fetchMovieDetail = async (movieId) => {
const url = `${TMDB_MOVIE_DETAIL_URL}${movieId}`;
const params = new URLSearchParams({
language: "ko-KR",
});
const response = await fetch(url + "?" + params, FETCH_OPTIONS);

return await response.json();
};
22 changes: 22 additions & 0 deletions ssr/constants/api.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 = {
nowPlaying: BASE_URL + "/now_playing?language=ko-KR&page=1",
popular: BASE_URL + "/popular?language=ko-KR&page=1",
topRated: 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,
},
};
24 changes: 24 additions & 0 deletions ssr/constants/path.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
export const MOVIE_PAGE_PATH = {
home: "/",
nowPlaying: "/now-playing",
popular: "/popular",
topRated: "/top-rated",
upcoming: "/upcoming",
detail: "/detail/:movieId",
};

const switchMoviePaths = (originalPaths, rootPath) => {
const switchedPaths = {};

Object.entries(originalPaths).forEach(([key, value]) => {
if (value === "/") {
switchedPaths[value] = rootPath;
} else {
switchedPaths[value] = key;
}
});

return switchedPaths;
};

export const MOVIE_TYPE_KEY = switchMoviePaths(MOVIE_PAGE_PATH, "nowPlaying");
9 changes: 9 additions & 0 deletions ssr/constants/placeholder.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export const HTML_PLACEHOLDERS = {
movieList: "<!--${MOVIE_ITEMS_PLACEHOLDER}-->",
movieTabs: "<!--${MOVIE_TABS}-->",
movieDetailModal: "<!--${MODAL_AREA}-->",
bestMovieDetailTrigger: "<!--${BEST_MOVIE_DETAIL_TRIGGER}-->",
bestMovieRate: "${bestMovie.rate}",
bestMovieTitle: "${bestMovie.title}",
bestMovieBackgroundImage: "${background-container}",
};
18 changes: 18 additions & 0 deletions ssr/constants/tabs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
export const MOVIE_TABS = [
{
href: "/now-playing",
label: "상영 중",
},
{
href: "/popular",
label: "인기순",
},
{
href: "/top-rated",
label: "평점순",
},
{
href: "/upcoming",
label: "상영 에정",
},
];
19 changes: 19 additions & 0 deletions ssr/server/handler/movie-detail-modal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { renderMovieDetailModal } from "../render/movie-detail-modal.js";
import { renderMoviePageHTML } from "../render/movie-page.js";

import { fetchMovieDetail, fetchMovies } from "../../apis/movie.js";

export const fetchAndRenderMovieDetailModal = async (req, res) => {
const { movieId } = req.params;

const movieList = await fetchMovies("nowPlaying");
const movieDetail = await fetchMovieDetail(movieId);
const moviePageTemplate = renderMoviePageHTML(
req.path,
movieList,
movieList[0]
);
const renderedHTML = renderMovieDetailModal(moviePageTemplate, movieDetail);

res.send(renderedHTML);
};
13 changes: 13 additions & 0 deletions ssr/server/handler/movie-page.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { renderMoviePageHTML } from "../render/movie-page.js";

import { fetchMovies } from "../../apis/movie.js";
import { MOVIE_TYPE_KEY } from "../../constants/path.js";

export const fetchAndRenderMoviePage = async (req, res) => {
const movieListType = MOVIE_TYPE_KEY[req.path];

const movieList = await fetchMovies(movieListType);
const renderedHTML = renderMoviePageHTML(req.path, movieList, movieList[0]);

res.send(renderedHTML);
};
4 changes: 2 additions & 2 deletions ssr/server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import path from "path";
import { fileURLToPath } from "url";

import movieRouter from "./routes/index.js";

// import membersRouter from "./routes/members.js"; // 본 미션 참고를 위한 코드이며 사전 미션에서는 사용하지 않습니다.
// app.use("/members", membersRouter); // 본 미션 참고를 위한 코드이며 사전 미션에서는 사용하지 않습니다. 뉑~~~

const app = express();
const PORT = 3000;
Expand All @@ -13,9 +15,7 @@ const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

app.use("/assets", express.static(path.join(__dirname, "../public")));

app.use("/", movieRouter);
// app.use("/members", membersRouter); // 본 미션 참고를 위한 코드이며 사전 미션에서는 사용하지 않습니다.

// Start server
app.listen(PORT, () => {
Expand Down
56 changes: 56 additions & 0 deletions ssr/server/render/movie-detail-modal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { HTML_PLACEHOLDERS } from "../../constants/placeholder.js";
import { TMDB_ORIGINAL_URL } from "../../constants/api.js";
import { MOVIE_PAGE_PATH } from "../../constants/path.js";

export const renderMovieDetailModal = (moviePageTemplate, movieDetail) => {
const movieDetailHTML = getMovieDetailModalHTML(movieDetail);

return moviePageTemplate.replace(
HTML_PLACEHOLDERS.movieDetailModal,
movieDetailHTML
);
};

const getMovieDetailModalHTML = (movieDetail) => {
const { poster_path, title, genres, overview, vote_average, description } =
movieDetail;

const genresNames = genres.map((g) => g.name);
const posterImageUrl = `${TMDB_ORIGINAL_URL}${poster_path}`;
const roundedRate = vote_average.toFixed(1);

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="${posterImageUrl}" />
</div>
<div class="modal-description">
<h2>${title}</h2>
<p class="category">2024 · ${genresNames.join(", ")}</p>
<p class="rate"><img src="/assets/images/star_filled.png" class="star" />
<span>${roundedRate}</span>
</p>
<hr />
<p class="detail">
${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");
window.location.href = ${MOVIE_PAGE_PATH.nowPlaying}
});
});
</script>
`;
};
93 changes: 93 additions & 0 deletions ssr/server/render/movie-page.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";

import { MOVIE_TABS } from "../../constants/tabs.js";
import { MOVIE_PAGE_PATH } from "../../constants/path.js";
import { TMDB_BANNER_URL } from "../../constants/api.js";
import { HTML_PLACEHOLDERS } from "../../constants/placeholder.js";

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

export const renderMoviePageHTML = (currentPath, movieList = [], bestMovie) => {
const templatePath = path.join(__dirname, "../../views", "index.html");
const template = fs.readFileSync(templatePath, "utf-8");

const { backdrop_path, vote_average, title, id: bestMovieId } = bestMovie;
const backdropImageUrl = `${TMDB_BANNER_URL}${backdrop_path}`;
const roundedRate = vote_average.toFixed(1);

const movieListHTML = getMovieListHTML(movieList);
const movieTabsHTML = getMovieTabsHTML(currentPath);
const bestMovieDetailModalTriggerHTML =
getBestMovieDetailModalTriggerHtml(bestMovieId);

return template
.replace(HTML_PLACEHOLDERS.bestMovieBackgroundImage, backdropImageUrl)
.replace(
HTML_PLACEHOLDERS.bestMovieDetailTrigger,
bestMovieDetailModalTriggerHTML
)
.replace(HTML_PLACEHOLDERS.movieTabs, movieTabsHTML)
.replace(HTML_PLACEHOLDERS.bestMovieTitle, title)
.replace(HTML_PLACEHOLDERS.bestMovieRate, roundedRate)
.replace(HTML_PLACEHOLDERS.movieList, movieListHTML);
};

const checkIsSelectedTab = (currentPath, tabHref) => {
if (
currentPath === MOVIE_PAGE_PATH.home &&
tabHref === MOVIE_PAGE_PATH.nowPlaying
)
return true;

return currentPath !== MOVIE_PAGE_PATH.home && currentPath === tabHref;
};

const getBestMovieDetailModalTriggerHtml = (id) => {
return /*html*/ `<button class="primary detail" onClick="window.location.href='detail/${id}'">자세히 보기</button>`;
};

export const getMovieTabsHTML = (currentPath) => {
return MOVIE_TABS.map(({ href, label }) => {
const isSelectedTab = checkIsSelectedTab(currentPath, href);

return /*html*/ `
<li>
<a href="${href}">
<div class="tab-item ${isSelectedTab ? "selected" : ""}">
<h3>${label}</h3>
</div>
</a>
</li>
`;
}).join("");
};

export const getMovieListHTML = (movieList = []) => {
return movieList
.map(({ id, title, poster_path, vote_average }) => {
const thumbnailUrl = `${TMDB_BANNER_URL}${poster_path}`;
const roundedRate = vote_average.toFixed(1);

return /*html*/ `
<li>
<a href="/detail/${id}">
<div class="item">
<img
class="thumbnail"
src="${thumbnailUrl}"
alt="${title}"
/>
<div class="item-desc">
<p class="rate"><img src="../assets/images/star_empty.png" class="star" /><span>${roundedRate}</span></p>
<strong>${title}</strong>
</div>
</div>
</a>
</li>
`;
})
.join("");
};
23 changes: 10 additions & 13 deletions ssr/server/routes/index.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,18 @@
import { Router } from "express";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
import { MOVIE_PAGE_PATH } from "../../constants/path.js";

const router = Router();
import { fetchAndRenderMovieDetailModal } from "../handler/movie-detail-modal.js";
import { fetchAndRenderMoviePage } from "../handler/movie-page.js";

router.get("/", (_, res) => {
const templatePath = path.join(__dirname, "../../views", "index.html");
const moviesHTML = "<p>들어갈 본문 작성</p>";
const router = Router();

const template = fs.readFileSync(templatePath, "utf-8");
const renderedHTML = template.replace("<!--${MOVIE_ITEMS_PLACEHOLDER}-->", moviesHTML);
router.get(MOVIE_PAGE_PATH.home, fetchAndRenderMoviePage);
router.get(MOVIE_PAGE_PATH.nowPlaying, fetchAndRenderMoviePage);
router.get(MOVIE_PAGE_PATH.popular, fetchAndRenderMoviePage);
router.get(MOVIE_PAGE_PATH.topRated, fetchAndRenderMoviePage);
router.get(MOVIE_PAGE_PATH.upcoming, fetchAndRenderMoviePage);

res.send(renderedHTML);
});
router.get(MOVIE_PAGE_PATH.detail, fetchAndRenderMovieDetailModal);

export default router;
40 changes: 9 additions & 31 deletions ssr/views/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -14,51 +14,29 @@
<body>
<div id="wrap">
<header>
<div class="background-container" style="background-image: url('${background-container}')">
<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>
<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>
<!--${BEST_MOVIE_DETAIL_TRIGGER}-->
</div>
</div>
</div>
</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>
<!--${MOVIE_TABS}-->
</ul>
<main>
<section>
Expand Down