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로 재구성하기] - 해시(김가연) 미션 제출합니다. #36

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
4 changes: 2 additions & 2 deletions ssr/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
"description": "SSR 렌더링으로 영화 목록 불러오기",
"main": "server/index.js",
"scripts": {
"start": "NODE_TLS_REJECT_UNAUTHORIZED=0 node server/index.js",
"dev": "NODE_TLS_REJECT_UNAUTHORIZED=0 nodemon server/index.js --watch"
"start": "NODE_TLS_REJECT_UNAUTHORIZED=1 node server/index.js",
"dev": "NODE_TLS_REJECT_UNAUTHORIZED=1 nodemon server/index.js --watch"
},
"type": "module",
"dependencies": {
Expand Down
7 changes: 7 additions & 0 deletions ssr/public/styles/main.css
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,13 @@ button.primary {
border-radius: 4px;
}

a.primary {
color: var(--color-white);
font-weight: bold;
background-color: var(--color-lightblue-90);
border-radius: 4px;
}

#wrap {
min-width: 1440px;
background-color: var(--color-bluegray-100);
Expand Down
1 change: 1 addition & 0 deletions ssr/server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const __dirname = path.dirname(__filename);
app.use("/assets", express.static(path.join(__dirname, "../public")));

app.use("/", movieRouter);

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

// Start server
Expand Down
104 changes: 97 additions & 7 deletions ssr/server/routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,110 @@ import { Router } from "express";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import {
fetchMovieDetails,
fetchNowPlayingMovieItems,
fetchPopularMovieItems,
fetchTopRatedMovieItems,
fetchUpcomingMovieItems,
} from "../src/api/movie.js";
import { renderMovieItems } from "../src/render/renderMovieItems.js";
import { renderHeader } from "../src/render/renderHeader.js";
import { renderMovieDetails } from "../src/render/renderMovieDetails.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 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 template = fs.readFileSync(templatePath, "utf-8");
const renderedHTML = template.replace("<!--${MOVIE_ITEMS_PLACEHOLDER}-->", moviesHTML);
const renderMoviePage = async (req, res) => {
try {
const templatePath = path.join(__dirname, "../../views", "index.html");
const currentPath = req.path === "/" ? "/now-playing" : req.path;

res.send(renderedHTML);
});
const movies = await fetchMovieItems(currentPath);
const featuredMovie = movies[0];

const moviesHTML = renderMovieItems(movies);
const headerHTML = renderHeader(featuredMovie);

let template = fs.readFileSync(templatePath, "utf-8");

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

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" : ""
}">`;
}
);

const renderedHTML = template
.replace("<!--${HEADER_PLACEHOLDER}-->", headerHTML)
.replace(/\$\{sectionTitle\}/g, sectionTitles[currentPath])
.replace("<!--${MOVIE_ITEMS_PLACEHOLDER}-->", moviesHTML);

res.send(renderedHTML);
} catch (error) {
console.error(error.message);
res.status(500).send("Internal Server Error");
}
};

const renderMovieDetailPage = async (req, res) => {
const id = req.params.id;

try {
const templatePath = path.join(__dirname, "../../views", "index.html");

const movieDetail = await fetchMovieDetails(id);
const movieDetailHTML = renderMovieDetails(movieDetail);

let template = fs.readFileSync(templatePath, "utf-8");

const renderedHTML = template.replace(
"<!--${MOVIE_ITEMS_PLACEHOLDER}-->",
movieDetailHTML
);

res.send(renderedHTML);
} catch (error) {
console.error(error.message);
res.status(500).send("Internal Server Error");
}
};

router.get("/", renderMoviePage);
router.get("/now-playing", renderMoviePage);
router.get("/popular", renderMoviePage);
router.get("/top-rated", renderMoviePage);
router.get("/upcoming", renderMoviePage);
router.get("/detail/:id", renderMovieDetailPage);

export default router;
46 changes: 46 additions & 0 deletions ssr/server/src/api/movie.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import {
FETCH_OPTIONS,
TMDB_MOVIE_DETAIL_URL,
TMDB_MOVIE_LISTS,
} from "../constant.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.results;
};
22 changes: 22 additions & 0 deletions ssr/server/src/constant.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,
},
};
27 changes: 27 additions & 0 deletions ssr/server/src/render/renderHeader.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { round } from "../../../../csr/src/utils.js";

export const renderHeader = ({ id, title, backdrop_path, vote_average }) => {
return /*html*/ `
<header>
<div
class="background-container"
style="background-image: url('https://media.themoviedb.org/t/p/original${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">${round(vote_average, 1)}</span>
</div>
<div class="title">${title}</div>
<a href="/detail/${id}" class="primary detail" >자세히 보기</ㅁ>
</div>
</div>
</div>
</header>
`;
};
38 changes: 38 additions & 0 deletions ssr/server/src/render/renderMovieDetails.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { TMDB_THUMBNAIL_URL } from "../constant.js";

export const renderMovieDetails = (movieDetail = {}) => {
const {
title,
genres = [],
vote_average = 0,
poster_path,
overview,
} = movieDetail;

return /*html*/ `
<div class="modal-background active" id="modalBackground">
<div class="modal">
<button class="close-modal" id="closeModal" onClick="location.href='/'">
<img src="/assets/images/modal_button_close.png">
</button>
<div class="modal-container">
<div class="modal-image">
<img src="${TMDB_THUMBNAIL_URL}${poster_path}" alt="${title}">
</div>
<div class="modal-description">
<h2>${title}</h2>
<p class="category">${genres.map(({ name }) => name).join(", ")}</p>
<p class="rate">
<img src="/assets/images/star_empty.png" class="star">
<span>${vote_average.toFixed(1)}</span>
</p>
<hr>
<p class="detail">
${overview}
</p>
</div>
</div>
</div>
</div>
`;
};
25 changes: 25 additions & 0 deletions ssr/server/src/render/renderMovieItems.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { round } from "../../../../csr/src/utils.js";

export const renderMovieItems = (movieItems = []) =>
movieItems
.map(
({ id, title, poster_path, vote_average }) => /*html*/ `
<li>
<a href="/detail/${id}">
<div class="item">
<img
class="thumbnail"
src="https://media.themoviedb.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>${round(vote_average, 1)}</span></p>
<strong>${title}</strong>
</div>
</div>
</a>
</li>
`
)
.join("");
21 changes: 3 additions & 18 deletions ssr/views/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -13,34 +13,19 @@
</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>
<a href="/now-playing">
<div class="tab-item">
<div class="tab-item now-playing">
<h3>상영 중</h3>
</div></a
>
</li>
<li>
<a href="/popular"
><div class="tab-item">
><div class="tab-item popular">
<h3>인기순</h3>
</div></a
>
Expand Down