diff --git a/ssr/server/routes/index.js b/ssr/server/routes/index.js index 84d32f2..393ad4f 100644 --- a/ssr/server/routes/index.js +++ b/ssr/server/routes/index.js @@ -2,20 +2,109 @@ import { Router } from "express"; import fs from "fs"; import path from "path"; import { fileURLToPath } from "url"; +import { + fetchMovieDetails, + fetchNowPlayingMovieItems, + fetchPopularMovieItems, + fetchTopRatedMovieItems, + fetchUpcomingMovieItems, +} from "../../src/apis/movies.js"; +import renderMovieList from "../../src/render/renderMovieList.js"; +import renderHeader from "../../src/render/renderHeader.js"; +import renderModal from "../../src/render/renderModal.js"; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const router = Router(); -router.get("/", (_, res) => { +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 getTemplate = (templatePath) => fs.readFileSync(templatePath, "utf-8"); + +const getSectionTitles = () => ({ + "/now-playing": "상영 중인 영화", + "/popular": "지금 인기 있는 영화", + "/top-rated": "평점이 높은 영화", + "/upcoming": "개봉 예정 영화", +}); + +const replaceTemplatePlaceholders = ( + template, + headerHTML, + moviesHTML, + sectionTitle, + movieModalHTML = "" +) => { + return template + .replace("", headerHTML) + .replace(/\$\{sectionTitle\}/g, sectionTitle) + .replace("", moviesHTML) + .replace("", movieModalHTML); +}; + +const renderPage = async (req, res, isModal = false) => { const templatePath = path.join(__dirname, "../../views", "index.html"); - const moviesHTML = "
들어갈 본문 작성
"; + const currentPath = + req.path === "/" || req.path.startsWith("/detail") + ? "/now-playing" + : req.path; + const movies = await fetchMovieItems(currentPath); + const featuredMovie = movies[0]; + const headerHTML = renderHeader(featuredMovie); + const moviesHTML = renderMovieList(movies); + const sectionTitles = getSectionTitles(); + let template = getTemplate(templatePath); - const template = fs.readFileSync(templatePath, "utf-8"); - const renderedHTML = template.replace("", moviesHTML); + template = template.replace( + /${ + movieDetail.release_date.split("-")[0] + } · ${movieDetail.genres.map(({ name }) => name).join(", ")}
+7.7
++ ${movieDetail.overview} +
+${ + Math.round(vote_average * 10).toFixed(1) / 10 + }
+ ${title} +