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로 재구성하기] - 마스터위(명재위) 미션 제출합니다. #19

Open
wants to merge 2 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
21 changes: 21 additions & 0 deletions ssr/api/movies.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import {
FETCH_OPTIONS,
PATH_TO_API,
TMDB_MOVIE_DETAIL_URL,
TMDB_MOVIE_LISTS,
} from '../constant.js';

export const fetchMovies = async (endpoint) => {
const response = await fetch(
TMDB_MOVIE_LISTS[PATH_TO_API[endpoint]],
FETCH_OPTIONS
);

return await response.json();
};

export const fetchMovieDetail = async (id) => {
const response = await fetch(`${TMDB_MOVIE_DETAIL_URL}${id}`, FETCH_OPTIONS);

return await response.json();
};
30 changes: 30 additions & 0 deletions ssr/constant.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
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 PATH_TO_API = {
'/': 'NOW_PLAYING',
'/now-playing': 'NOW_PLAYING',
'/popular': 'POPULAR',
'/top-rated': 'TOP_RATED',
'/upcoming': 'UPCOMING',
};
55 changes: 42 additions & 13 deletions ssr/server/routes/index.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,50 @@
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 { Router } from 'express';
import { renderMovieDetailModal, renderMovieList } from '../../views/render.js';

const router = Router();

router.get("/", (_, res) => {
const templatePath = path.join(__dirname, "../../views", "index.html");
const moviesHTML = "<p>들어갈 본문 작성</p>";
router.get('/', async (req, res) => {
const endpoint = '/now-playing';
const template = await renderMovieList(endpoint, res);

res.send(template);
});

router.get('/now-playing', async (req, res) => {
const endpoint = req.path;
const template = await renderMovieList(endpoint, res);

res.send(template);
});

router.get('/popular', async (req, res) => {
const endpoint = req.path;
const template = await renderMovieList(endpoint, res);

res.send(template);
});

router.get('/top-rated', async (req, res) => {
const endpoint = req.path;
const template = await renderMovieList(endpoint, res);

res.send(template);
});

router.get('/upcoming', async (req, res) => {
const endpoint = req.path;
const template = await renderMovieList(endpoint, res);

res.send(template);
});

router.get('/detail/:id', async (req, res) => {
let template = await renderMovieList('/now-playing', res);
const modal = await renderMovieDetailModal(req, res);

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

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

export default router;
5 changes: 5 additions & 0 deletions ssr/utils/round.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export const round = (value, decimals = 0) => {
const factor = 10 ** decimals;

return Math.round(value * factor) / factor;
};
61 changes: 61 additions & 0 deletions ssr/views/getTemplates.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { round } from '../utils/round.js';

export const getMovieItemsHTML = (movieItems) => {
return movieItems.map((movie) => {
const thumbnailUrl = `https://image.tmdb.org/t/p/w200${movie.poster_path}`;
const roundedRate = round(movie.vote_average, 1);

return /*html*/ `
<li class="movie-item">
<a href="/detail/${movie.id}" class="item">
<img class="thumbnail" src="${thumbnailUrl}" alt="${movie.title}" />
<div class="movie-info">
<p class="rate">
<img src="../assets/images/star_empty.png" class="star" />
<span>${roundedRate}</span>
</p>
<strong>${movie.title}</strong>
</div>
</a>
</li>
`;
});
};

export const getMovieDetailModalHTML = (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
} · ${movieDetail.genres.map((genre) => genre.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>
`;
};
21 changes: 13 additions & 8 deletions ssr/views/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,15 @@
<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" />
Expand All @@ -39,22 +44,22 @@ <h3>상영 중</h3>
>
</li>
<li>
<a href="/popular"
><div class="tab-item">
<a href="/popular">
<div class="tab-item">
<h3>인기순</h3>
</div></a
>
</li>
<li>
<a href="/top-rated"
><div class="tab-item">
<a href="/top-rated">
<div class="tab-item">
<h3>평점순</h3>
</div></a
>
</li>
<li>
<a href="/upcoming"
><div class="tab-item">
<a href="/upcoming">
<div class="tab-item">
<h3>상영 예정</h3>
</div></a
>
Expand Down
57 changes: 57 additions & 0 deletions ssr/views/render.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

import { fetchMovieDetail, fetchMovies } from '../api/movies.js';
import { getMovieDetailModalHTML, getMovieItemsHTML } from './getTemplates.js';
import { round } from '../utils/round.js';

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

export const renderMovieList = async (endpoint, res) => {
const movieItems = await fetchMovies(endpoint).then((data) => data.results);
const bestMovieItem = movieItems[0];
const moviesHTML = getMovieItemsHTML(movieItems).join('');

const templatePath = path.join(__dirname, './', 'index.html');
let template = fs.readFileSync(templatePath, 'utf-8');

template = template.replace('<!--${MOVIE_ITEMS_PLACEHOLDER}-->', moviesHTML);
template = template.replace(
'${background-container}',
'https://image.tmdb.org/t/p/w1920_and_h800_multi_faces/' +
bestMovieItem.backdrop_path
);
template = template.replace(
'${bestMovie.rate}',
round(bestMovieItem.vote_average)
);
template = template.replace('${bestMovie.title}', bestMovieItem.title);

template = renderTabs(template, endpoint);

return template;
ㅡ;
};

export const renderMovieDetailModal = async (req, res) => {
const { id: movieId } = req.params;
const movieDetailItem = await fetchMovieDetail(movieId).then((data) => data);

const movieDetailModalHTML = getMovieDetailModalHTML(movieDetailItem);

return movieDetailModalHTML;
};

export const renderTabs = (template, currentPath) => {
template = template.replace(
new RegExp(
`<a\\s+href="${currentPath}">\\s*<div\\s+class="tab-item">`,
'g'
),
`<a href="${currentPath}"><div class="tab-item selected">`
);

return template;
};