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로 재구성하기] - 에프이(박철민) 미션 제출합니다. #15

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

const loadMovieDetail = async (id) => {
const url = TMDB_MOVIE_DETAIL_URL + id;
const params = new URLSearchParams({
language: 'ko-KR',
});
const response = await fetch(url + '?' + params, FETCH_OPTIONS);

return await response.json();
};

export default loadMovieDetail;
15 changes: 15 additions & 0 deletions ssr/server/apis/movies.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { FETCH_OPTIONS, TMDB_MOVIE_LISTS } from '../constants/movies.js';

const loadMovies = async (url) => {
const response = await fetch(url, FETCH_OPTIONS);
const data = await response.json();

return data.results;
};

const loadPopularMovies = async () => await loadMovies(TMDB_MOVIE_LISTS.popular);
const loadNowPlayingMovies = async () => await loadMovies(TMDB_MOVIE_LISTS.nowPlaying);
const loadTopRatedMovies = async () => await loadMovies(TMDB_MOVIE_LISTS.topRated);
const loadUpcomingMovies = async () => await loadMovies(TMDB_MOVIE_LISTS.upcoming);

export { loadPopularMovies, loadNowPlayingMovies, loadTopRatedMovies, loadUpcomingMovies };
20 changes: 20 additions & 0 deletions ssr/server/constants/movies.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
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',
nowPlaying: BASE_URL + '/now_playing?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,
},
};
6 changes: 6 additions & 0 deletions ssr/server/constants/tabList.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export const TAB_LIST = [
{ name: 'now-playing', description: '상영 중' },
{ name: 'popular', description: '인기순' },
{ name: 'top-rated', description: '평점순' },
{ name: 'upcoming', description: '상영 예정' },
];
53 changes: 41 additions & 12 deletions ssr/server/routes/index.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,48 @@
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 generateMovieList from '../utils/generateMovieList.js';
import loadMovieDetail from '../apis/details.js';
import renderModal from '../utils/renderModal.js';

const router = Router();

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

res.send(renderedHTML);
});

router.get('/now-playing', async (_, res) => {
const renderedHTML = await generateMovieList('now-playing');

res.send(renderedHTML);
});

router.get('/popular', async (_, res) => {
const renderedHTML = await generateMovieList('popular');

res.send(renderedHTML);
});

router.get('/top-rated', async (_, res) => {
const renderedHTML = await generateMovieList('top-rated');

res.send(renderedHTML);
});

router.get('/upcoming', async (_, res) => {
const renderedHTML = await generateMovieList('upcoming');

res.send(renderedHTML);
});

router.get('/detail/:movieId', async (req, res) => {
const movieId = req.params.movieId;
const movieDetail = await loadMovieDetail(movieId);

const template = fs.readFileSync(templatePath, "utf-8");
const renderedHTML = template.replace("<!--${MOVIE_ITEMS_PLACEHOLDER}-->", moviesHTML);
const renderedHTML = (await generateMovieList('now-playing')).replace(
'<!--${MODAL_AREA}-->',
renderModal(movieDetail)
);

res.send(renderedHTML);
});
Expand Down
48 changes: 48 additions & 0 deletions ssr/server/utils/generateMovieList.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { loadNowPlayingMovies, loadPopularMovies, loadTopRatedMovies, loadUpcomingMovies } from '../apis/movies.js';
import { TAB_LIST } from '../constants/tabList.js';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import renderMovieItem from './renderMovieItem.js';
import renderTabMenu from './renderTabMenu.js';
import { TMDB_BANNER_URL } from '../constants/movies.js';

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

const generateMovieList = async (selectedTab = 'now-playing') => {
const templatePath = path.join(__dirname, '../../views', 'index.html');

const template = fs.readFileSync(templatePath, 'utf-8');

const movieLists = await Promise.all([
loadNowPlayingMovies(),
loadPopularMovies(),
loadTopRatedMovies(),
loadUpcomingMovies(),
]);

const FocusedIndex = TAB_LIST.findIndex((tab) => tab.name === selectedTab);

const bestMovie = movieLists[FocusedIndex][0];
const bestMovieRate = bestMovie.vote_average.toFixed(1);
const bestMovieTitle = bestMovie.title;
const bestMovieBackgroundImageSrc = TMDB_BANNER_URL + bestMovie.backdrop_path;

const moviesHTML = movieLists[FocusedIndex].map((movie) => {
return renderMovieItem(movie);
}).join('');

const tabHTML = renderTabMenu(`${selectedTab}`).join('');

const movieListHTML = template
.replace('${bestMovie.rate}', bestMovieRate)
.replace('${bestMovie.title}', bestMovieTitle)
.replace('${background-container}', bestMovieBackgroundImageSrc)
.replace('<!--${MOVIE_ITEMS_PLACEHOLDER}-->', moviesHTML)
.replace('<!--${TAB_PLACEHOLDER}-->', tabHTML);

return movieListHTML;
};

export default generateMovieList;
39 changes: 39 additions & 0 deletions ssr/server/utils/renderModal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { TMDB_ORIGINAL_URL } from '../constants/movies.js';

const renderModal = (detail) => {
const bannerUrl = TMDB_ORIGINAL_URL + detail.poster_path;
const releaseYear = detail.release_date.split('-')[0];
const genres = detail.genres.map((genre) => genre.name).join(', ');

const CloseButtonImageSrc = '../assets/images/modal_button_close.png';
const StarEmptyImageSrc = '../assets/images/star_empty.png';

return /* html */ `
<div class="modal-background active" id="modalBackground">
<div class="modal">
<button class="close-modal" id="closeModal">
<img src='${CloseButtonImageSrc}' />
</button>
<div class="modal-container">
<div class="modal-image">
<img src='${bannerUrl}' />
</div>
<div class="modal-description">
<h2>${detail.title}</h2>
<p class="category">
${releaseYear} · ${genres}
</p>
<p class="rate">
<img src='${StarEmptyImageSrc}' class="star" />
<span>${detail.vote_average}</span>
</p>
<hr />
<p class="detail">${detail.overview}</p>
</div>
</div>
</div>
</div>
`;
};

export default renderModal;
26 changes: 26 additions & 0 deletions ssr/server/utils/renderMovieItem.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { TMDB_THUMBNAIL_URL } from '../constants/movies.js';

const renderMovieItem = (movie) => {
const thumbnailFullUrl = TMDB_THUMBNAIL_URL + '/' + movie.poster_path;

const StarEmptyImgSrc = './assets/images/star_empty.png';

return /* html */ `
<li>
<a href='/detail/${movie.id}'>
<div class="item">
<img class="thumbnail" src=${thumbnailFullUrl} alt=${movie.title} />
<div class="item-desc">
<p class="rate">
<img src=${StarEmptyImgSrc} class="star" />
<span>${movie.vote_average.toFixed(1)}</span>
</p>
<strong>${movie.title}</strong>
</div>
</div>
</a>
</li>
`;
};

export default renderMovieItem;
Loading