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로 재구성하기] - 렛서(김다은) 미션 제출합니다. #29

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
6 changes: 6 additions & 0 deletions package-lock.json

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

20 changes: 20 additions & 0 deletions ssr/public/scripts/modal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
document.addEventListener('DOMContentLoaded', () => {
const modalBackground = document.querySelector('.modal-background');
const modalCloseButton = document.querySelector('.close-modal');

if (modalCloseButton) {
modalCloseButton.addEventListener('click', () => {
if (modalBackground) {
modalBackground.remove();
}
});
}

if (modalBackground) {
modalBackground.addEventListener('click', (event) => {
if (event.target === modalBackground) {
modalBackground.remove();
}
});
}
});
22 changes: 22 additions & 0 deletions ssr/server/api/constants.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',
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,
},
};
49 changes: 49 additions & 0 deletions ssr/server/api/movies.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import {
FETCH_OPTIONS,
TMDB_MOVIE_DETAIL_URL,
TMDB_MOVIE_LISTS,
} from './constants.js';

const loadMovies = async (url) => {
try {
const response = await fetch(url, FETCH_OPTIONS);

if (!response.ok) {
throw new Error(`Failed to fetch movies: ${response.status}`);
}

const data = await response.json();
return data;
} catch (error) {
console.error(error);
}
};

const fetchMovies = {
popular: async () => {
const data = await loadMovies(TMDB_MOVIE_LISTS.popular);
return data;
},

nowPlaying: async () => {
const data = await loadMovies(TMDB_MOVIE_LISTS.nowPlaying);
return data;
},

upcoming: async () => {
const data = await loadMovies(TMDB_MOVIE_LISTS.upcoming);
return data;
},

topRated: async () => {
const data = await loadMovies(TMDB_MOVIE_LISTS.topRated);
return data;
},

detail: async (id) => {
const data = await loadMovies(`${TMDB_MOVIE_DETAIL_URL}${id}`);
return data;
},
};

export default fetchMovies;
74 changes: 65 additions & 9 deletions ssr/server/routes/index.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,77 @@
import { Router } from "express";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { Router } from 'express';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

import fetchMovies from '../api/movies.js';
import {
getBannerHTML,
getModalHTML,
getMoviesHTML,
getTabsHTML,
} from '../templates/movie.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 placeholders = {
banner: '<!-- ${BANNER_PLACEHOLDER} -->',
movies: '<!-- ${MOVIE_ITEMS_PLACEHOLDER} -->',
modal: '<!-- ${MODAL_AREA} -->',
tabs: '<!-- ${TABS_PLACEHOLDER} -->',
};

const renderMoviePage = async ({
res,
category = 'nowPlaying',
movieId = null,
}) => {
const templatePath = path.join(__dirname, '../../views', 'index.html');

const movies = await fetchMovies[category]();
const movieDetail = movieId ? await fetchMovies.detail(movieId) : null;

const bannerHTML = await getBannerHTML(movies.results[0]);
const tabsHTML = getTabsHTML(category);
const moviesHTML = await getMoviesHTML(movies);
const modalHTML = movieDetail ? await getModalHTML(movieDetail) : '';

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

const renderedHTML = template
.replace(placeholders.banner, bannerHTML)
.replace(placeholders.tabs, tabsHTML)
.replace(placeholders.movies, moviesHTML)
.replace(placeholders.modal, modalHTML);

res.send(renderedHTML);
};

router.get('/', async (_, res) => {
await renderMoviePage({ res });
});

router.get('/now-playing', async (_, res) => {
await renderMoviePage({ category: 'nowPlaying', res });
});

router.get('/popular', async (_, res) => {
await renderMoviePage({ category: 'popular', res });
});

router.get('/upcoming', async (_, res) => {
await renderMoviePage({ category: 'upcoming', res });
});

router.get('/top-rated', async (_, res) => {
await renderMoviePage({ category: 'topRated', res });
});

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

export default router;
131 changes: 131 additions & 0 deletions ssr/server/templates/movie.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import {
TMDB_BANNER_URL,
TMDB_ORIGINAL_URL,
TMDB_THUMBNAIL_URL,
} from '../api/constants.js';

export const getBannerHTML = async (movie) => {
const { vote_average: rate, title, backdrop_path: backdropPath } = movie;

return /*html*/ `
<header>
<div
class="background-container"
style="background-image: url('${TMDB_BANNER_URL + backdropPath}')"
>
<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">${rate.toFixed(1)}</span>
</div>
<div class="title">${title}</div>
<button class="primary detail">자세히 보기</button>
</div>
</div>
</div>
</header>

<script src="../assets/scripts/tab.js"></script>
`;
};

export const getTabsHTML = (category) => {
const tabs = {
nowPlaying: { href: '/now-playing', label: '상영 중' },
popular: { href: '/popular', label: '인기' },
upcoming: { href: '/upcoming', label: '개봉 예정' },
topRated: { href: '/top-rated', label: '평점 높은 순' },
};

return Object.entries(tabs)
.map(([menu, { href, label }]) => {
return /*html*/ `
<li>
<a href="${href}">
<div class="tab-item ${menu === category && 'selected'}">
<h3>${label}</h3>
</div>
</a>
</li>
`;
})
.join('\n');
};

export const getMoviesHTML = async (movies) => {
return movies.results
.map(
({
id,
title,
vote_average: rate,
poster_path: thumbnailPath,
}) => /*html*/ `
<li>
<a href="/detail/${id}">
<div class="item">
<img class="thumbnail" src=${
TMDB_THUMBNAIL_URL + '/' + thumbnailPath
} alt=${title} />
<div class="item-desc">
<p class="rate">
<img src="../assets/images/star_empty.png" class="star" />
<span>${rate.toFixed(1)}</span>
</p>
<strong>${title}</strong>
</div>
</div>
</a>
</li>
`
)
.join('\n');
};

export const getModalHTML = async (movieDetail) => {
const {
poster_path: posterPath,
title,
release_date: releaseDate,
genres,
vote_average: rate,
overview: description,
} = 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" alt="Close button" />
</button>
<div class="modal-container">
<div class="modal-image">
<img src="${
TMDB_ORIGINAL_URL + posterPath
}" alt="${title} 포스터" />
</div>
<div class="modal-description">
<h2>${title}</h2>
<p class="category">
${releaseDate.substring(0, 4)} · ${genres
.map(({ name }) => name)
.join(', ')}
</p>
<p class="rate">
<img src="../assets/images/star_empty.png" class="star" alt="Star icon" />
<span>${rate.toFixed(1)}</span>
</p>
<hr />
<p class="detail">${description}</p>
</div>
</div>
</div>
</div>

<script src="../assets/scripts/modal.js"></script>
`;
};
50 changes: 4 additions & 46 deletions ssr/views/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -13,58 +13,16 @@
</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>
<!-- ${BANNER_PLACEHOLDER} -->
<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>
<!-- ${TABS_PLACEHOLDER} -->
</ul>
<main>
<section>
<h2>지금 인기 있는 영화</h2>
<ul class="thumbnail-list">
<!--${MOVIE_ITEMS_PLACEHOLDER}-->
<!-- ${MOVIE_ITEMS_PLACEHOLDER} -->
</ul>
</section>
</main>
Expand All @@ -75,6 +33,6 @@ <h2>지금 인기 있는 영화</h2>
<p><img src="../assets/images/woowacourse_logo.png" width="180" /></p>
</footer>
</div>
<!--${MODAL_AREA}-->
<!-- ${MODAL_AREA} -->
</body>
</html>