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로 재구성하기] - 올리(이예진) 미션 제출합니다. #17

Open
wants to merge 4 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
84 changes: 84 additions & 0 deletions ssr/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 5 additions & 4 deletions ssr/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,17 @@
"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": "cross-env NODE_TLS_REJECT_UNAUTHORIZED=0 node server/index.js",
"dev": "cross-env NODE_TLS_REJECT_UNAUTHORIZED=0 nodemon server/index.js --watch"
},
"type": "module",
"dependencies": {
"express": "^4.18.2",
"node-fetch": "^3.3.2"
},
"devDependencies": {
"nodemon": "^3.1.6",
"dotenv": "^16.0.0"
"cross-env": "^7.0.3",
"dotenv": "^16.0.0",
"nodemon": "^3.1.6"
}
}
157 changes: 157 additions & 0 deletions ssr/server/controllers/moviesController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
// 영화 데이터와 관련된 로직 처리
import fetch from "node-fetch";
import {
TMDB_MOVIE_LISTS,
FETCH_OPTIONS,
TMDB_BANNER_URL,
TMDB_THUMBNAIL_URL,
TAB_DATA,
} from "../../src/constants.js";
import path from "path";
import fs from "fs";
import { fileURLToPath } from "url";

// 현재 파일 경로와 디렉터리 경로 설정
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const getFullThumbNailURL = (thumbnailUrl) => {
return TMDB_THUMBNAIL_URL + "/" + thumbnailUrl;
};

const getBestMovie = (movies) => {
return movies.reduce(
(best, movie) => (movie.vote_average > best.vote_average ? movie : best),
movies[0]
);
};

const getMovieListInnerHTML = (movie) => {
return `
<div class="item">
<a href="/detail/${movie.id}">
<img class="thumbnail" src=${getFullThumbNailURL(
movie.poster_path
)} alt=""/>
</a>
<div class="item-desc">
<p class="rate">
<img src="/assets/images/star_empty.png" class="star"/>
<span>${(Math.round(movie.vote_average * 10) / 10).toFixed(
1
)}</span>
</p>
<strong>${movie.title}</strong>
</div>
</div>
`;
};

const getMovieDetailModalInnerHTML = (movieDetail) => {
return `
<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
}" alt="Movie Poster" />
</div>
<div class="modal-description">
<h2>${movieDetail.title}</h2>
<p class="category">
${new Date(movieDetail.release_date).getFullYear()} ·
${movieDetail.genres.map((genre) => genre.name).join(", ")}
</p>
<p class="rate">
<img src="../assets/images/star_filled.png" class="star" />
<span>${movieDetail.vote_average.toFixed(1)}</span>
</p>
<hr />
<p class="detail">${movieDetail.overview}</p>
</div>
</div>
</div>
</div>
<script>
document.addEventListener("DOMContentLoaded", () => {
const closeModal = document.getElementById("closeModal");
closeModal.addEventListener("click", () => {
document.getElementById("modalBackground").remove();
document.getElementById("${TAB_DATA[0].title}-tab")
history.pushState(null, null, '/'); // URL을 목록 페이지로 변경
});
});
</script>
`;
};

export const renderMoviesPage = async (req, res, listType, movieId = null) => {
try {
const currentPath = req.path === "/" ? "/now-playing" : req.path; // 현재 요청된 URL 경로

const tabsHTML = TAB_DATA.map((tab) => {
const selectedClass = currentPath === tab.path ? "selected" : "";
return `
<li>
<a id="${tab.title}-tab" href="${tab.path}">
<div class="tab-item ${selectedClass}">
<h3>${tab.title}</h3>
</div>
</a>
</li>
`;
}).join("");

const response = await fetch(TMDB_MOVIE_LISTS[listType], FETCH_OPTIONS);
const moviesData = await response.json();

// 최고 평점 영화 추출
const bestMovie = getBestMovie(moviesData.results);

const bestMovieBanner = bestMovie
? TMDB_BANNER_URL + bestMovie.backdrop_path
: "";
const bestMovieTitle = bestMovie ? bestMovie.title : "No title";
const bestMovieRate = bestMovie ? bestMovie.vote_average.toFixed(1) : "";

// 영화 목록 데이터를 HTML로 변환
const moviesHTML = moviesData.results
.map((movie) => getMovieListInnerHTML(movie))
.join("");

let modalHTML = "";

// 만약 movieId가 주어졌다면 영화 상세 정보로 모달 생성
if (movieId) {
const movieResponse = await fetch(
`https://api.themoviedb.org/3/movie/${movieId}?api_key=${process.env.TMDB_TOKEN}`,
FETCH_OPTIONS
);
const movieDetail = await movieResponse.json();

modalHTML = getMovieDetailModalInnerHTML(movieDetail);
}

// 템플릿 파일 읽기
const templatePath = path.join(__dirname, "../../views", "index.html");
const template = fs.readFileSync(templatePath, "utf-8");

// 템플릿에 영화 데이터 및 모달 데이터 삽입
let renderedHTML = template
.replace("${TAB_ITEMS_PLACEHOLDER}", tabsHTML)
.replace("${background-container}", bestMovieBanner)
.replace("${MOVIE_ITEMS_PLACEHOLDER}", moviesHTML)
.replace("${bestMovie.title}", bestMovieTitle)
.replace("${bestMovie.rate}", bestMovieRate)
.replace("${MODAL_AREA}", modalHTML);

res.send(renderedHTML);
} catch (error) {
console.error("Error fetching movies:", error);
res.status(500).send("Server Error");
}
};
21 changes: 4 additions & 17 deletions ssr/server/routes/index.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,8 @@
import { Router } from "express";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import express from "express";
import moviesRouter from "./movies.js";

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

const router = Router();

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

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

res.send(renderedHTML);
});
router.use("/", moviesRouter);

export default router;
23 changes: 23 additions & 0 deletions ssr/server/routes/movies.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import express from "express";
import { renderMoviesPage } from "../controllers/moviesController.js";

// 각각의 경로에서 영화 데이터를 가져와 렌더링하는 라우트
const router = express.Router();

router.get("/", (req, res) => {
renderMoviesPage(req, res, "NOW_PLAYING");
});

router.get("/now-playing", (req, res) =>
renderMoviesPage(req, res, "NOW_PLAYING")
);

router.get("/popular", (req, res) => renderMoviesPage(req, res, "POPULAR"));
router.get("/top-rated", (req, res) => renderMoviesPage(req, res, "TOP_RATED"));
router.get("/upcoming", (req, res) => renderMoviesPage(req, res, "UPCOMING"));
router.get("/detail/:id", (req, res) => {
const movieId = req.params.id;
renderMoviesPage(req, res, "POPULAR", movieId); // 영화 목록과 모달 함께 렌더링
});

export default router;
29 changes: 29 additions & 0 deletions ssr/src/constants.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
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,
},
};

export const TAB_DATA = [
{ path: "/now-playing", title: "상영 중" },
{ path: "/popular", title: "인기순" },
{ path: "/top-rated", title: "평점순" },
{ path: "/upcoming", title: "상영 예정" },
];
Loading