Dataset Viewer
Auto-converted to Parquet
code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -0,0 +1,32 @@ +import * as S from './Header.styled'; + +interface HeaderProps extends React.InputHTMLAttributes<HTMLInputElement> { + searchKeyword: string; + onSearch: (keyword: string) => void; +} + +function LargeHeader({ searchKeyword, onSearch, ...rest }: HeaderProps) { + return ( + <S.Layout> + <a href="https://chosim-dvlpr.github.io/react-movie-review/"> + <S.LogoButton> + <S.LogoImage src="./logo.png" /> + </S.LogoButton> + </a> + <S.InputBox $isExpanded={true}> + <S.Input + {...rest} + value={searchKeyword} + onChange={(event: React.ChangeEvent<HTMLInputElement>) => + onSearch(event.target.value) + } + $isDisabled={false} + disabled={false} + /> + <S.SearchIcon src="./search_button.png" /> + </S.InputBox> + </S.Layout> + ); +} + +export default LargeHeader;
Unknown
๋ผ์šฐํŒ…์ด ๋”ฐ๋กœ ํ•„์š”ํ•˜์ง€ ์•Š์•„์„œ a ํƒœ๊ทธ๋กœ ๋Œ€์ฒดํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,20 @@ +import { DISPLAY_SIZE } from '../../../constants/displaySize'; +import LargeHeader from './LargeHeader'; +import MobileHeader from './MobileHeader'; + +interface HeaderProps { + searchKeyword: string; + onSearch: (keyword: string) => void; +} + +function Header({ searchKeyword, onSearch }: HeaderProps) { + const isMobile = document.documentElement.clientWidth <= DISPLAY_SIZE.mobile; + + return isMobile ? ( + <MobileHeader searchKeyword={searchKeyword} onSearch={onSearch} /> + ) : ( + <LargeHeader searchKeyword={searchKeyword} onSearch={onSearch} /> + ); +} + +export default Header;
Unknown
HTMLInputElement๋ฅผ ์ƒ์†๋ฐ›์œผ๋ฉด์„œ rest props๋ฅผ ๋„˜๊ฒจ์ฃผ๊ณ  ์žˆ์ง€๋งŒ ํ˜„์žฌ๋กœ์„œ๋Š” ์ด ๊ธฐ๋Šฅ๋“ค์„ ํ™œ์šฉํ•˜๊ณ  ์žˆ๋Š” ๊ฒƒ ๊ฐ™์ง€ ์•Š์•„์š”. ๊ทธ๋ฆฌ๊ณ  ๋ณดํ†ต ์ด๋Ÿฐ ํŒจํ„ด์€ ๊ณตํ†ต ์ปดํฌ๋„ŒํŠธ์—์„œ ๋งŽ์ด ์‚ฌ์šฉํ•˜๋Š”๋ฐ, ์š” ํ—ค๋”๋Š” common์— ๋“ค์–ด์žˆ๊ธฐ๋Š” ํ•˜์ง€๋งŒ ํŠน์ • ๋””์ž์ธ๊ณผ ๊ตฌํ˜„์— ํŠนํ™”๋œ ๊ฒƒ ๊ฐ™์•„์„œ ์ด๋ ‡๊ฒŒ ํ™•์žฅ์„ฑ์„ ์—ด์–ด๋‘” ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค! + common ํด๋”์—๋งŒ _๊ฐ€ ๋ถ™์–ด์žˆ๋Š”๋ฐ ์ฒ˜์Œ ๋ณด๋Š” ์ปจ๋ฒค์…˜์ด๋ผ ์–ด๋–ค ์˜๋ฏธ์ธ์ง€๋„ ๊ถ๊ธˆํ•ด์š” ใ…Žใ…Ž
@@ -0,0 +1,58 @@ +import React, { useReducer } from 'react'; +import * as S from './Header.styled'; + +interface HeaderProps extends React.InputHTMLAttributes<HTMLInputElement> { + searchKeyword: string; + onSearch: (keyword: string) => void; +} + +type State = boolean; +type Action = { type: 'TOGGLE' } | { type: 'OPEN' } | { type: 'CLOSE' }; + +function reducer(state: State, action: Action): State { + switch (action.type) { + case 'TOGGLE': + return !state; + case 'OPEN': + return true; + case 'CLOSE': + return false; + default: + return state; + } +} + +function MobileHeader({ searchKeyword, onSearch, ...rest }: HeaderProps) { + const [isExpanded, updateState] = useReducer(reducer, false); + + const handleSearchIconClick = () => { + updateState({ type: 'TOGGLE' }); + }; + + return ( + <S.Layout> + <a href="https://chosim-dvlpr.github.io/react-movie-review/"> + <S.LogoButton> + <S.LogoImage src="./logo.png" /> + </S.LogoButton> + </a> + <S.InputBox $isExpanded={isExpanded}> + <S.Input + {...rest} + value={searchKeyword} + onChange={(event: React.ChangeEvent<HTMLInputElement>) => + onSearch(event.target.value) + } + $isDisabled={!isExpanded} + disabled={!isExpanded} + /> + <S.SearchIcon + src="./search_button.png" + onClick={handleSearchIconClick} + /> + </S.InputBox> + </S.Layout> + ); +} + +export default MobileHeader;
Unknown
์˜ค input์ด ์–ด์ฐจํ”ผ ๋‹๋ณด๊ธฐ ํด๋ฆญ ์ „์—๋Š” ์—ด๋ฆฌ์ง€ ์•Š์•„์„œ ๋†“์น˜๊ธฐ ์‰ฌ์› ์„ํ…๋ฐ ๊ผผ๊ผผํ•˜๊ฒŒ disabled๊นŒ์ง€ ์ฑ™๊ฒจ์ฃผ์…จ๋„ค์š”! ๐Ÿ‘ ์ด๋ ‡๊ฒŒ UI์—์„œ input์ด ์‚ฌ์šฉ ๋ถˆ๊ฐ€๋Šฅํ•  ๋•Œ disabled๋ฅผ ๋ช…์‹œํ•ด์ค€ ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ด์š”. ์ €๋Š” UI์™€ ์ฝ”๋“œ์˜ ์ผ์น˜ + ๋ถˆํ•„์š”ํ•œ DOM ์กฐ์ž‘ ๋ฐฉ์ง€ ์ •๋„๋กœ ์ƒ๊ฐํ–ˆ๋Š”๋ฐ ๋งž๋‚˜์šฉ?
@@ -0,0 +1,58 @@ +import React, { useReducer } from 'react'; +import * as S from './Header.styled'; + +interface HeaderProps extends React.InputHTMLAttributes<HTMLInputElement> { + searchKeyword: string; + onSearch: (keyword: string) => void; +} + +type State = boolean; +type Action = { type: 'TOGGLE' } | { type: 'OPEN' } | { type: 'CLOSE' }; + +function reducer(state: State, action: Action): State { + switch (action.type) { + case 'TOGGLE': + return !state; + case 'OPEN': + return true; + case 'CLOSE': + return false; + default: + return state; + } +} + +function MobileHeader({ searchKeyword, onSearch, ...rest }: HeaderProps) { + const [isExpanded, updateState] = useReducer(reducer, false); + + const handleSearchIconClick = () => { + updateState({ type: 'TOGGLE' }); + }; + + return ( + <S.Layout> + <a href="https://chosim-dvlpr.github.io/react-movie-review/"> + <S.LogoButton> + <S.LogoImage src="./logo.png" /> + </S.LogoButton> + </a> + <S.InputBox $isExpanded={isExpanded}> + <S.Input + {...rest} + value={searchKeyword} + onChange={(event: React.ChangeEvent<HTMLInputElement>) => + onSearch(event.target.value) + } + $isDisabled={!isExpanded} + disabled={!isExpanded} + /> + <S.SearchIcon + src="./search_button.png" + onClick={handleSearchIconClick} + /> + </S.InputBox> + </S.Layout> + ); +} + +export default MobileHeader;
Unknown
Action์„ ๊ฐ์ฒด๋กœ ๋งŒ๋“  ์ด์œ ๋Š” ํ™•์žฅ์„ฑ ๋•Œ๋ฌธ์ผ๊นŒ์š”? ์ €๋ผ๋ฉด ๊ฐ„๋‹จํ•œ ํ”„๋กœ๊ทธ๋žจ์—์„œ๋Š” ๋‹จ์ˆœ ๋ฌธ์ž์—ด union ํƒ€์ž…์œผ๋กœ ๋งŒ๋“ค์—ˆ์„ ๊ฒƒ ๊ฐ™๋„ค์œ ใ…Žใ…Žใ…Ž
@@ -0,0 +1,58 @@ +import React, { useReducer } from 'react'; +import * as S from './Header.styled'; + +interface HeaderProps extends React.InputHTMLAttributes<HTMLInputElement> { + searchKeyword: string; + onSearch: (keyword: string) => void; +} + +type State = boolean; +type Action = { type: 'TOGGLE' } | { type: 'OPEN' } | { type: 'CLOSE' }; + +function reducer(state: State, action: Action): State { + switch (action.type) { + case 'TOGGLE': + return !state; + case 'OPEN': + return true; + case 'CLOSE': + return false; + default: + return state; + } +} + +function MobileHeader({ searchKeyword, onSearch, ...rest }: HeaderProps) { + const [isExpanded, updateState] = useReducer(reducer, false); + + const handleSearchIconClick = () => { + updateState({ type: 'TOGGLE' }); + }; + + return ( + <S.Layout> + <a href="https://chosim-dvlpr.github.io/react-movie-review/"> + <S.LogoButton> + <S.LogoImage src="./logo.png" /> + </S.LogoButton> + </a> + <S.InputBox $isExpanded={isExpanded}> + <S.Input + {...rest} + value={searchKeyword} + onChange={(event: React.ChangeEvent<HTMLInputElement>) => + onSearch(event.target.value) + } + $isDisabled={!isExpanded} + disabled={!isExpanded} + /> + <S.SearchIcon + src="./search_button.png" + onClick={handleSearchIconClick} + /> + </S.InputBox> + </S.Layout> + ); +} + +export default MobileHeader;
Unknown
useReducer๋ฅผ ์‹ค์ œ๋กœ ์“ฐ๋Š” ์ฝ”๋“œ๋Š” ์ฒ˜์Œ ๋ณด๋„ค์š”! ๋งค์ผ useState๋งŒ ์ƒ๊ฐํ–ˆ๋Š”๋ฐ ๋ฆฌํ”„๋ ˆ์‹œ๊ฐ€ ๋˜๋Š”๊ตฐ์š”ใ…‹ใ…‹ใ…‹ ๋‹ค๋งŒ ์ง€๊ธˆ action ์ค‘์—์„œ ์‹ค์งˆ์ ์œผ๋กœ ์‚ฌ์šฉํ•˜๋Š” ๋™์ž‘์€ TOGGLE๋ฟ์ธ ๊ฒƒ ๊ฐ™์€๋ฐ OPEN๊ณผ CLOSE๊ฐ€ ๋ช…์‹œ๋œ ์ด์œ , ๋ฆฌ๋“€์„œ๋ฅผ ์‚ฌ์šฉํ•œ ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค~~
@@ -0,0 +1,81 @@ +import styled from 'styled-components'; +import media from '../../../styles/mediaQueries'; + +export const Layout = styled.header` + display: flex; + align-items: center; + justify-content: space-between; + gap: 1rem; + + position: relative; + + width: 100%; + height: 6rem; + padding: 0.8rem 3.2rem; + + border-bottom: 1px solid rgba(255, 255, 255, 0.5); + box-shadow: 0px 4px 8px 0px rgba(255, 255, 255, 0.2); + + color: ${({ theme }) => theme.colors.white}; + background-color: rgba(17, 17, 17, 1); +`; + +export const LogoImage = styled.img` + width: 12.3rem; + height: 2rem; +`; + +export const LogoButton = styled.button` + cursor: pointer; +`; + +export const InputBox = styled.div<{ $isExpanded: boolean }>` + display: flex; + flex-direction: row; + align-items: center; + justify-content: space-between; + gap: 0.8rem; + + right: 3.2rem; + + width: 100%; + max-width: 32rem; + height: 4.4rem; + padding: 1rem 1.4rem; + + border: 1px solid rgba(208, 213, 221, 1); + border-radius: 0.8rem; + + overflow: hidden; + background-color: ${({ theme }) => theme.colors.white}; + transition: width 0.2s ease; + + ${({ $isExpanded }) => media.mobile` + position: absolute; + width: ${$isExpanded ? 'calc(100% - 6.4rem)' : '4.8rem'}; + max-width: 100%; + height: 4.4rem; + `}; +`; + +export const Input = styled.input<{ $isDisabled: boolean }>` + width: 100%; + height: 100%; + + pointer-events: ${({ $isDisabled }) => ($isDisabled ? 'none' : 'auto')}; + transition: width 0.2s ease; + + ${({ $isDisabled }) => media.mobile` + display: ${$isDisabled ? 'none' : 'block'}; + + width: ${$isDisabled ? 0 : '100%'}; + height: ${$isDisabled ? 0 : '100%'}; + `} +`; + +export const SearchIcon = styled.img` + width: 1.8rem; + height: 1.8rem; + + cursor: pointer; +`;
TypeScript
ํƒœ๊ทธ๊ฐ€ header๋ฉด ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”~!
@@ -0,0 +1,52 @@ +import React, { Suspense, useEffect, useState } from 'react'; +import { createPortal } from 'react-dom'; +import * as S from './Modal.styled'; +import useEscapeKey from '../../../hooks/useEscapeKey'; +import ModalBackdrop from './ModalBackdrop'; +import SkeletonModal from '../Skeleton/SkeletonModal'; + +interface ModalProps { + isOpen: boolean; + onClose: () => void; + children: React.ReactNode; +} + +const ANIMATION_DURATION_TIME = 200; + +const Modal = ({ children, isOpen, onClose }: ModalProps) => { + const portalElement = document.getElementById('modal') as HTMLElement; + const [isRender, setIsRender] = useState(isOpen); + + useEscapeKey(isOpen, onClose); + + useEffect(() => { + if (isOpen) { + setIsRender(true); + } else { + const timer = setTimeout(() => { + setIsRender(false); + }, ANIMATION_DURATION_TIME); + return () => clearTimeout(timer); + } + }, [isOpen]); + + if (!portalElement || !isRender) { + return null; + } + + const modalLayout = ( + <S.Layout> + <ModalBackdrop onClick={onClose} /> + <S.ContentLayout + $isRender={isRender && isOpen} + $animationTime={ANIMATION_DURATION_TIME} + > + <Suspense fallback={<SkeletonModal />}>{children}</Suspense> + </S.ContentLayout> + </S.Layout> + ); + + return isRender && createPortal(modalLayout, portalElement); +}; + +export default Modal;
Unknown
์–ด๋–ค ํšจ๊ณผ์˜€์„๊นŒ์š”?!
@@ -0,0 +1,23 @@ +import Title from '../../_common/Title/Title'; +import MovieList from '../MovieList/MovieList'; +import * as S from '../Movie.styled'; + +interface ContentProps { + searchKeyword: string; +} + +function Content({ searchKeyword }: ContentProps) { + const titleContent = + searchKeyword.length > 0 + ? `${searchKeyword} ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ` + : '์ง€๊ธˆ ์ธ๊ธฐ์žˆ๋Š” ์˜ํ™”'; + + return ( + <S.ContentLayout> + <Title content={titleContent} /> + <MovieList keyword={searchKeyword} /> + </S.ContentLayout> + ); +} + +export default Content;
Unknown
์˜ค ์œ„์—์„œ searchKeyword ๊ฐ’์„ ๋ฐ›์•„์˜ค๋˜ ๋””๋ฐ”์šด์Šค๋ฅผ ๊ฑธ์–ด์„œ ์ƒˆ ๊ฐ’์„ ๋ฐ›์•„์˜ค๋Š”๊ตฐ์šฉ ๊ทธ๋Ÿฐ๋ฐ ๋””๋ฐ”์šด์Šค ์ฒ˜๋ฆฌ๋ฅผ searchKeyword๋ฅผ ์†Œ์œ ํ•œ ๋ถ€๋ชจ ์ปดํฌ๋„ŒํŠธ๊ฐ€ ์•„๋‹ˆ๋ผ Content์—์„œ ํ•ด ์ฃผ๋Š” ์ด์œ ๊ฐ€ ์žˆ๋‚˜์š”? ๋””๋ฐ”์šด์Šค ๋กœ์ง์ด Content๋ฅผ ๊ฑฐ์ณ์•ผ ๋‚˜์˜ค๋Š” ์ƒํ™ฉ์ด ์•„๋‹ˆ๋ผ์„œ ๋ถ€๋ชจ ์ปดํฌ๋„ŒํŠธ๊ฐ€ ๋‹ด๋‹นํ•˜๋Š” ๊ฒŒ ์กฐ๊ธˆ ๋” ๋‚ซ๋‹ค๋Š” ์ƒ๊ฐ์ž…๋‹ˆ๋‹ค. (Single Source of Truth ๋ฉด์—์„œ) ๋˜ ์—ญํ• ์„ ์ง๊ด€์ ์œผ๋กœ ๋‚˜๋ˆ ๋ณผ ๋•Œ๋„ debounce ์ฑ…์ž„์€ ๊ฒ€์ƒ‰์ฐฝ ์ชฝ์—์„œ ๋‹ด๋‹นํ•˜๊ณ  Content๋Š” ๊ทธ ๊ฐ’์„ ๋ฐ›์•„์„œ ์“ฐ๊ธฐ๋งŒ ํ•˜๋Š” ๊ฒŒ ์ž์—ฐ์Šค๋Ÿฌ์›Œ ๋ณด์ธ๋‹ค๊ณ  ์ƒ๊ฐํ•ด์š”~!
@@ -0,0 +1,59 @@ +import { useState } from 'react'; +import { useModalContext } from '../../../contexts/ModalContext'; +import Modal from '../../_common/Modal/Modal'; +import * as S from '../Movie.styled'; +import MovieDetail from '../MovieDetail/MovieDetail'; +import MovieItem from '../MovieItem/MovieItem'; +import FetchTargetBox from '../../_common/FetchTargetBox/FetchTargetBox'; +import SkeletonColumn from '../../_common/Skeleton/SkeletonColumn'; +import useInfiniteScroll from '../../../hooks/useInfiniteScroll'; +import useMovieQuery from '../../../hooks/useMovieQuery'; + +interface MovieListProps { + keyword: string; +} + +function MovieList({ keyword }: MovieListProps) { + const [selectedMovie, setSelectedMovie] = useState<number>(0); + + const { isOpenModal, openModal, closeModal } = useModalContext(); + + const handleModalOpen = (movieId: number) => { + setSelectedMovie(movieId); + openModal('movie'); + }; + + const { + movieList, + fetchNextPage, + isFetchingNextPage, + hasNextPage, + isLoading, + } = useMovieQuery({ keyword }); + + const { nextFetchTargetRef } = useInfiniteScroll({ + fetchNextPage, + hasNextPage, + movieList, + }); + + return ( + <S.MovieListLayout> + <S.ItemList> + {isLoading && <SkeletonColumn count={20} />} + {movieList.map(movie => ( + <MovieItem movie={movie} key={movie.id} onClick={handleModalOpen} /> + ))} + </S.ItemList> + {!isFetchingNextPage && hasNextPage && ( + <FetchTargetBox ref={nextFetchTargetRef} /> + )} + + <Modal onClose={() => closeModal('movie')} isOpen={isOpenModal}> + <MovieDetail movieId={selectedMovie} /> + </Modal> + </S.MovieListLayout> + ); +} + +export default MovieList;
Unknown
id ๊ฐ’์„ ๊ด€๋ฆฌํ•˜๋‹ˆ๊นŒ ๋ณ€์ˆ˜๋ช…์—์„œ๋„ ๋ช…ํ™•ํ•˜๊ฒŒ Id์ž„์ด ๋“œ๋Ÿฌ๋‚˜๋ฉด ์ข‹๊ฒ ์–ด์š”!
@@ -0,0 +1,131 @@ +import axios from 'axios'; +import { API_URL, TMDB_URL } from './constant'; +import { Movie, MovieDetail } from '../types/movie.type'; + +interface GetPopularMoviesResponse { + page: number; + results: Movie[]; + total_pages: number; + total_results: number; +} + +export const getPopularMovies = async ({ + page, +}: { + page: number; +}): Promise<GetPopularMoviesResponse> => { + try { + const response = await axios.get( + `${TMDB_URL}/movie/popular?${new URLSearchParams({ + api_key: import.meta.env.VITE_API_KEY, + language: 'ko-KR', + page: `${page}`, + })}`, + ); + + return response.data; + } catch (error) { + throw new Error('Failed to fetch popular movies'); + } +}; + +interface GetSearchedMoviesResponse { + page: number; + results: Movie[]; + total_pages: number; + total_results: number; +} + +export const getSearchedMovies = async ({ + page, + keyword, +}: { + page: number; + keyword: string; +}): Promise<GetSearchedMoviesResponse> => { + try { + const response = await axios({ + method: 'GET', + url: `${TMDB_URL}/search/movie`, + params: { + api_key: import.meta.env.VITE_API_KEY, + include_adult: 'false', + language: 'ko-KR', + page, + query: keyword, + }, + headers: { + accept: 'application/json', + Authorization: `Bearer ${import.meta.env.VITE_API_KEY}`, + }, + }); + + return response.data; + } catch (error) { + throw new Error('Failed to fetch popular movies'); + } +}; + +export const getMovie = async ({ + movieId, +}: { + movieId: number; +}): Promise<MovieDetail> => { + try { + const response = await axios({ + method: 'GET', + url: `${TMDB_URL}/movie/${movieId}`, + params: { + api_key: import.meta.env.VITE_API_KEY, + language: 'ko-KR', + }, + headers: { + accept: 'application/json', + Authorization: `Bearer ${import.meta.env.VITE_API_KEY}`, + }, + }); + + return response.data; + } catch (error) { + throw new Error('Failed to fetch popular movies'); + } +}; + +export const getRating = async ({ + movieId, +}: { + movieId: number; +}): Promise<number> => { + try { + const response = await axios({ + method: 'GET', + url: `${API_URL}/rating/${movieId}`, + }); + + return response.data; + } catch (error) { + throw new Error('Failed to fetch popular movies'); + } +}; + +export const updateRating = async ({ + movieId, + rating, +}: { + movieId: number; + rating: number; +}): Promise<{ rating: number }> => { + try { + const response = await axios({ + method: 'POST', + url: `${API_URL}/rating/${movieId}`, + data: { + rating, + }, + }); + + return { rating: response.data }; + } catch (error) { + throw new Error('Failed to fetch popular movies'); + } +};
TypeScript
axios๋„ ๊ฑฐ์˜ ๋ฐ˜๋…„๋งŒ์— ๋ณด๋„ค์š”...ใ…‹ใ…‹ใ…‹ใ…‹ใ…‹ใ…‹ ํ™•์‹คํžˆ fetch ์ฝ”๋“œ๊ฐ€ ๋” ๊ฐ„๊ฒฐํ•ด์ง€๋Š”๊ตฐ์š” page๋ฅผ ๋ณด๋‚ผ ๋•Œ String()์ด ์•„๋‹ˆ๋ผ ํ…œํ”Œ๋ฆฟ ๋ฆฌํ„ฐ๋Ÿด์„ ์‚ฌ์šฉํ•œ ๊ฒŒ ๋ˆˆ์— ๋„๋„ค์š”!
@@ -0,0 +1,136 @@ +import styled from 'styled-components'; +import media from '../../../styles/mediaQueries'; + +export const Layout = styled.div` + width: 100%; + height: 100%; +`; + +// Text + +export const TitleText = styled.p` + ${({ theme }) => theme.font.body}; + text-align: center; +`; + +export const CaptionText = styled.p` + ${({ theme }) => theme.font.caption}; +`; + +export const CaptionBoldText = styled.p` + ${({ theme }) => theme.font.caption}; + font-weight: 700; + white-space: nowrap; +`; + +export const OverviewText = styled.p` + ${({ theme }) => theme.font.caption}; + text-align: start; +`; + +export const RatingDescriptionText = styled.p` + ${({ theme }) => theme.font.caption}; + + ${media.tablet` + display: none; + `} +`; + +// Box Layout + +export const TitleBox = styled.div` + position: relative; + width: 100%; + + padding: 1.8rem 0; + border-bottom: 1px solid rgba(241, 241, 241, 0.25); +`; + +export const ContentBox = styled.div` + display: flex; + flex-direction: row; + gap: 3.2rem; + + width: 100%; + height: calc(100% - 6.4rem); + + padding: 3.6rem 3.2rem 4.8rem; +`; + +export const DetailBox = styled.div` + display: flex; + flex-direction: column; + justify-content: space-between; + align-items: flex-start; +`; + +export const DetailHeaderBox = styled.div` + display: flex; + flex-direction: row; + gap: 1.6rem; +`; + +export const DetailContentBox = styled.div` + display: flex; + flex-direction: column; + gap: 1.6rem; + + -webkit-line-clamp: 10; + -webkit-box-orient: vertical; + + text-overflow: ellipsis; + overflow: hidden; + white-space: normal; +`; + +export const DetailVoteBox = styled.div` + display: flex; + flex-direction: row; + align-items: center; + gap: 1.2rem; + + width: 100%; + padding: 1.6rem; + border-radius: 1.6rem; + + background: ${({ theme }) => theme.colors.greyScale2}; + + ${media.tablet` + justify-content: center; + `} +`; + +export const StarImageVoteBox = styled.div` + display: flex; + flex-direction: row; +`; + +export const ThumbnailImageBox = styled.div` + width: 29.2rem; + height: 43.3rem; +`; + +// Image + +export const ThumbnailImage = styled.img` + ${media.desktop` + width: 26rem; + height: 40rem; + `} + + ${media.tablet` + display: none; + `} +`; + +export const StarImage = styled.img` + width: 2.6rem; + height: 2.6rem; + + cursor: pointer; + + ${media.tablet` + width: 3.2rem; + height: 3.2rem; + `} +`;
TypeScript
์ €๋Š” ํ•ญ์ƒ ์Šคํƒ€์ผ๋ง ๋Œ€์ƒ์ด ๋˜๋Š” ์š”์†Œ์˜ ๊ธฐ๋Šฅ๋งŒ ์ƒ๊ฐํ•ด์„œ styled component์˜ ์ด๋ฆ„์„ ์ง€์—ˆ๋Š”๋ฐ ์ ์šฉํ•  ์Šคํƒ€์ผ๋กœ ์ด๋ฆ„์„ ๋ถ™์ด๋‹ˆ๊นŒ ๋” ์ง๊ด€์ ์ด๊ณ  ํŽธํ•˜๋„ค์š” ๐Ÿ˜Š ์™œ ์ด ์ƒ๊ฐ์„ ๋ชป ํ–ˆ์ง€?!
@@ -0,0 +1,136 @@ +import styled from 'styled-components'; +import media from '../../../styles/mediaQueries'; + +export const Layout = styled.div` + width: 100%; + height: 100%; +`; + +// Text + +export const TitleText = styled.p` + ${({ theme }) => theme.font.body}; + text-align: center; +`; + +export const CaptionText = styled.p` + ${({ theme }) => theme.font.caption}; +`; + +export const CaptionBoldText = styled.p` + ${({ theme }) => theme.font.caption}; + font-weight: 700; + white-space: nowrap; +`; + +export const OverviewText = styled.p` + ${({ theme }) => theme.font.caption}; + text-align: start; +`; + +export const RatingDescriptionText = styled.p` + ${({ theme }) => theme.font.caption}; + + ${media.tablet` + display: none; + `} +`; + +// Box Layout + +export const TitleBox = styled.div` + position: relative; + width: 100%; + + padding: 1.8rem 0; + border-bottom: 1px solid rgba(241, 241, 241, 0.25); +`; + +export const ContentBox = styled.div` + display: flex; + flex-direction: row; + gap: 3.2rem; + + width: 100%; + height: calc(100% - 6.4rem); + + padding: 3.6rem 3.2rem 4.8rem; +`; + +export const DetailBox = styled.div` + display: flex; + flex-direction: column; + justify-content: space-between; + align-items: flex-start; +`; + +export const DetailHeaderBox = styled.div` + display: flex; + flex-direction: row; + gap: 1.6rem; +`; + +export const DetailContentBox = styled.div` + display: flex; + flex-direction: column; + gap: 1.6rem; + + -webkit-line-clamp: 10; + -webkit-box-orient: vertical; + + text-overflow: ellipsis; + overflow: hidden; + white-space: normal; +`; + +export const DetailVoteBox = styled.div` + display: flex; + flex-direction: row; + align-items: center; + gap: 1.2rem; + + width: 100%; + padding: 1.6rem; + border-radius: 1.6rem; + + background: ${({ theme }) => theme.colors.greyScale2}; + + ${media.tablet` + justify-content: center; + `} +`; + +export const StarImageVoteBox = styled.div` + display: flex; + flex-direction: row; +`; + +export const ThumbnailImageBox = styled.div` + width: 29.2rem; + height: 43.3rem; +`; + +// Image + +export const ThumbnailImage = styled.img` + ${media.desktop` + width: 26rem; + height: 40rem; + `} + + ${media.tablet` + display: none; + `} +`; + +export const StarImage = styled.img` + width: 2.6rem; + height: 2.6rem; + + cursor: pointer; + + ${media.tablet` + width: 3.2rem; + height: 3.2rem; + `} +`;
TypeScript
์š”๊ธฐ overflow-y ์†์„ฑ์ด ์žˆ์–ด์•ผ ํ•  ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,59 @@ +import { useState } from 'react'; +import { useModalContext } from '../../../contexts/ModalContext'; +import Modal from '../../_common/Modal/Modal'; +import * as S from '../Movie.styled'; +import MovieDetail from '../MovieDetail/MovieDetail'; +import MovieItem from '../MovieItem/MovieItem'; +import FetchTargetBox from '../../_common/FetchTargetBox/FetchTargetBox'; +import SkeletonColumn from '../../_common/Skeleton/SkeletonColumn'; +import useInfiniteScroll from '../../../hooks/useInfiniteScroll'; +import useMovieQuery from '../../../hooks/useMovieQuery'; + +interface MovieListProps { + keyword: string; +} + +function MovieList({ keyword }: MovieListProps) { + const [selectedMovie, setSelectedMovie] = useState<number>(0); + + const { isOpenModal, openModal, closeModal } = useModalContext(); + + const handleModalOpen = (movieId: number) => { + setSelectedMovie(movieId); + openModal('movie'); + }; + + const { + movieList, + fetchNextPage, + isFetchingNextPage, + hasNextPage, + isLoading, + } = useMovieQuery({ keyword }); + + const { nextFetchTargetRef } = useInfiniteScroll({ + fetchNextPage, + hasNextPage, + movieList, + }); + + return ( + <S.MovieListLayout> + <S.ItemList> + {isLoading && <SkeletonColumn count={20} />} + {movieList.map(movie => ( + <MovieItem movie={movie} key={movie.id} onClick={handleModalOpen} /> + ))} + </S.ItemList> + {!isFetchingNextPage && hasNextPage && ( + <FetchTargetBox ref={nextFetchTargetRef} /> + )} + + <Modal onClose={() => closeModal('movie')} isOpen={isOpenModal}> + <MovieDetail movieId={selectedMovie} /> + </Modal> + </S.MovieListLayout> + ); +} + +export default MovieList;
Unknown
queries๋ฅผ ๊ฐ์ฒด๋กœ ๋งŒ๋“ค๊ณ  key๋ฅผ name์œผ๋กœ ํ•˜๋ฉด ์–ด๋–ค ๋ฆฌ์†Œ์Šค๋ฅผ ์œ„ํ•œ ์ฟผ๋ฆฌ์ธ์ง€ ๋” ์ž˜ ๋“œ๋Ÿฌ๋‚  ๊ฒƒ ๊ฐ™์•„์š”~ ๊ทผ๋ฐ ๊ฐ์ฒด๋ผ์„œ ์ฝ”๋“œ๊ฐ€ ์ข€ ๋” ๋ณต์žกํ•ด์ง€๊ฒ ๋„ค์š” ๐Ÿ˜—
@@ -0,0 +1,59 @@ +import { useState } from 'react'; +import { useModalContext } from '../../../contexts/ModalContext'; +import Modal from '../../_common/Modal/Modal'; +import * as S from '../Movie.styled'; +import MovieDetail from '../MovieDetail/MovieDetail'; +import MovieItem from '../MovieItem/MovieItem'; +import FetchTargetBox from '../../_common/FetchTargetBox/FetchTargetBox'; +import SkeletonColumn from '../../_common/Skeleton/SkeletonColumn'; +import useInfiniteScroll from '../../../hooks/useInfiniteScroll'; +import useMovieQuery from '../../../hooks/useMovieQuery'; + +interface MovieListProps { + keyword: string; +} + +function MovieList({ keyword }: MovieListProps) { + const [selectedMovie, setSelectedMovie] = useState<number>(0); + + const { isOpenModal, openModal, closeModal } = useModalContext(); + + const handleModalOpen = (movieId: number) => { + setSelectedMovie(movieId); + openModal('movie'); + }; + + const { + movieList, + fetchNextPage, + isFetchingNextPage, + hasNextPage, + isLoading, + } = useMovieQuery({ keyword }); + + const { nextFetchTargetRef } = useInfiniteScroll({ + fetchNextPage, + hasNextPage, + movieList, + }); + + return ( + <S.MovieListLayout> + <S.ItemList> + {isLoading && <SkeletonColumn count={20} />} + {movieList.map(movie => ( + <MovieItem movie={movie} key={movie.id} onClick={handleModalOpen} /> + ))} + </S.ItemList> + {!isFetchingNextPage && hasNextPage && ( + <FetchTargetBox ref={nextFetchTargetRef} /> + )} + + <Modal onClose={() => closeModal('movie')} isOpen={isOpenModal}> + <MovieDetail movieId={selectedMovie} /> + </Modal> + </S.MovieListLayout> + ); +} + +export default MovieList;
Unknown
์˜ต์ €๋ฒ„ ๊ด€๋ จ ๋™์ž‘์„ ๋ณ„๋„์˜ ํ›…์œผ๋กœ ๋ถ„๋ฆฌํ•˜๋ฉด ์ฝ”๋“œ๊ฐ€ ๋” ๊ฐ„๊ฒฐํ•ด์งˆ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,59 @@ +import { useState } from 'react'; +import { useModalContext } from '../../../contexts/ModalContext'; +import Modal from '../../_common/Modal/Modal'; +import * as S from '../Movie.styled'; +import MovieDetail from '../MovieDetail/MovieDetail'; +import MovieItem from '../MovieItem/MovieItem'; +import FetchTargetBox from '../../_common/FetchTargetBox/FetchTargetBox'; +import SkeletonColumn from '../../_common/Skeleton/SkeletonColumn'; +import useInfiniteScroll from '../../../hooks/useInfiniteScroll'; +import useMovieQuery from '../../../hooks/useMovieQuery'; + +interface MovieListProps { + keyword: string; +} + +function MovieList({ keyword }: MovieListProps) { + const [selectedMovie, setSelectedMovie] = useState<number>(0); + + const { isOpenModal, openModal, closeModal } = useModalContext(); + + const handleModalOpen = (movieId: number) => { + setSelectedMovie(movieId); + openModal('movie'); + }; + + const { + movieList, + fetchNextPage, + isFetchingNextPage, + hasNextPage, + isLoading, + } = useMovieQuery({ keyword }); + + const { nextFetchTargetRef } = useInfiniteScroll({ + fetchNextPage, + hasNextPage, + movieList, + }); + + return ( + <S.MovieListLayout> + <S.ItemList> + {isLoading && <SkeletonColumn count={20} />} + {movieList.map(movie => ( + <MovieItem movie={movie} key={movie.id} onClick={handleModalOpen} /> + ))} + </S.ItemList> + {!isFetchingNextPage && hasNextPage && ( + <FetchTargetBox ref={nextFetchTargetRef} /> + )} + + <Modal onClose={() => closeModal('movie')} isOpen={isOpenModal}> + <MovieDetail movieId={selectedMovie} /> + </Modal> + </S.MovieListLayout> + ); +} + +export default MovieList;
Unknown
์˜ค์˜น ์ด ๋ฐฉ์‹ ๊น”๋”ํ•˜๊ณ  ์ข‹๋„ค์š” ๐Ÿ‘๐Ÿ‘ ๋ฆฌํŒฉํ† ๋งํ•˜๋Ÿฌ ๊ฐ€์•ผ๊ฒ ... ๐Ÿ˜‚
@@ -0,0 +1,6 @@ +import styled from 'styled-components'; + +export const Layout = styled.div` + width: 100%; + height: 10vh; +`;
TypeScript
ํฌ๊ธฐ ์„ ์ • ๊ธฐ์ค€์ด ๊ถ๊ธˆํ•ด์š”!
@@ -0,0 +1,29 @@ +import { Movie } from '../../../types/movie.type'; +import * as S from '../Movie.styled'; + +interface MovieItemProps { + movie: Movie; + onClick: (movieId: number) => void; +} + +function MovieItem({ movie, onClick }: MovieItemProps) { + return ( + <li key={movie.id} onClick={() => onClick(movie.id)}> + <S.ItemCard> + <S.ItemThumbnail + src={`https://image.tmdb.org/t/p/w220_and_h330_face${movie.poster_path}`} + loading="lazy" + alt={movie.title} + /> + + <S.ItemTitle>{movie.title}</S.ItemTitle> + <S.ItemScoreBox> + <S.ItemScore>{movie.vote_average.toFixed(1)} </S.ItemScore> + <S.StarImage src="./star_filled.png" alt="๋ณ„์ " /> + </S.ItemScoreBox> + </S.ItemCard> + </li> + ); +} + +export default MovieItem;
Unknown
์—ฌ๊ธฐ์„œ๋„ ์†Œ์ˆ˜์  ๋ณด์ •์„ ํ•ด์•ผ ํ•  ๊ฒƒ ๊ฐ™์•„์œ 
@@ -0,0 +1,112 @@ +import { TMDB } from '../../../constants/url'; +import useMovie from '../../../queries/useMovie'; +import useRating from '../../../queries/useRating'; +import useUpdateStars from '../../../queries/useUpdateStars'; +import * as S from './MovieDetail.styled'; + +interface MovieDetailProps { + movieId: number; +} + +const RATING_TEXT = (rating: number) => { + if (rating === 10) { + return '์ตœ๊ณ ์˜ˆ์š”'; + } else if (rating >= 8) { + return '์ข‹์•„์š”'; + } else if (rating >= 6) { + return '๋‚˜์˜์ง€ ์•Š์•„์š”'; + } else if (rating >= 4) { + return '๊ทธ๋ƒฅ ๊ทธ๋ž˜์š”'; + } else if (rating >= 2) { + return '๋ณ„๋กœ์˜ˆ์š”'; + } + return '์•„์ง ์ ์ˆ˜๋ฅผ ๋งค๊ธฐ์ง€ ์•Š์•˜์–ด์š”.'; +}; + +function MovieDetail({ movieId }: MovieDetailProps) { + const { movieDetail } = useMovie(movieId); + const { rating } = useRating(movieId); + const { updateRating } = useUpdateStars(movieId); + const { updateRating: errorUpdateRating } = useUpdateStars(1); + + const filledStars = Math.floor(rating / 2); + return ( + <S.Layout> + <S.TitleBox> + <S.TitleText>{movieDetail.title}</S.TitleText> + </S.TitleBox> + + <S.ContentBox> + <S.ThumbnailImageBox> + <S.ThumbnailImage + src={`${TMDB.POSTER_PATH}${movieDetail.poster_path}`} + /> + </S.ThumbnailImageBox> + + <S.DetailBox> + <S.DetailContentBox> + <S.DetailHeaderBox> + <S.CaptionText> + {movieDetail.genres.flatMap(genre => genre.name).join(', ')} + </S.CaptionText> + <S.StarImage src="./star_filled.png" alt="๋ณ„์ " /> + <S.CaptionText> + {movieDetail.vote_average.toFixed(1)} + </S.CaptionText> + </S.DetailHeaderBox> + <S.OverviewText>{movieDetail.overview}</S.OverviewText> + </S.DetailContentBox> + + <S.DetailVoteBox> + <S.CaptionBoldText>ํ† ์ŠคํŠธ ํ™•์ธ์„ ์œ„ํ•œ ๋ณ„์ </S.CaptionBoldText> + <S.StarImageVoteBox> + {[...Array(5)].map((_, index) => ( + <button + onClick={() => errorUpdateRating({ rating: (index + 1) * 2 })} + > + <S.StarImage + key={index} + src={ + index < filledStars + ? './star_filled.png' + : './star_empty.png' + } + alt={index < filledStars ? 'filled star' : 'empty star'} + /> + </button> + ))} + </S.StarImageVoteBox> + <S.CaptionText>{rating !== 0 && rating}</S.CaptionText> + </S.DetailVoteBox> + + <S.DetailVoteBox> + <S.CaptionBoldText>๋‚ด ๋ณ„์ </S.CaptionBoldText> + <S.StarImageVoteBox> + {[...Array(5)].map((_, index) => ( + <button + onClick={() => updateRating({ rating: (index + 1) * 2 })} + > + <S.StarImage + key={index} + src={ + index < filledStars + ? './star_filled.png' + : './star_empty.png' + } + alt={index < filledStars ? 'filled star' : 'empty star'} + /> + </button> + ))} + </S.StarImageVoteBox> + <S.CaptionText>{rating !== 0 && rating}</S.CaptionText> + <S.RatingDescriptionText> + {RATING_TEXT(rating)} + </S.RatingDescriptionText> + </S.DetailVoteBox> + </S.DetailBox> + </S.ContentBox> + </S.Layout> + ); +} + +export default MovieDetail;
Unknown
์ ‘๊ทผ์„ฑ์„ ์œ„ํ•ด button ํƒœ๊ทธ๋กœ ๊ฐ์‹ธ๋Š” ๊ฒŒ ์ข‹์„ ๊ฒƒ ๊ฐ™์€๋ฐ ์‹œ๊ฐ„์ƒ์˜ ์ด์œ ๋กœ img์— ๋ฐ”๋กœ onClick์ด ๋ถ™์€ ๊ฑธ๊นŒ์š”? ๊ทธ๋ฆฌ๊ณ  StarImageVoteBox ์ดํ•˜ ์ปดํฌ๋„ŒํŠธ๋“ค์„ ๋ณ„๋„๋กœ ๋ถ„๋ฆฌํ•˜์ง€ ์•Š์€ ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค(Content์—์„œ ๋” ๊ฐ„๋‹จํ•œ ์ปดํฌ๋„ŒํŠธ์ธ Title์€ ๋ถ„๋ฆฌ๋˜์–ด ์žˆ๊ธธ๋ž˜์š”~!)
@@ -0,0 +1,20 @@ +import { DISPLAY_SIZE } from '../../../constants/displaySize'; +import LargeHeader from './LargeHeader'; +import MobileHeader from './MobileHeader'; + +interface HeaderProps { + searchKeyword: string; + onSearch: (keyword: string) => void; +} + +function Header({ searchKeyword, onSearch }: HeaderProps) { + const isMobile = document.documentElement.clientWidth <= DISPLAY_SIZE.mobile; + + return isMobile ? ( + <MobileHeader searchKeyword={searchKeyword} onSearch={onSearch} /> + ) : ( + <LargeHeader searchKeyword={searchKeyword} onSearch={onSearch} /> + ); +} + +export default Header;
Unknown
์˜ค Header์—์„œ๋Š” ์‚ฌ์šฉ๋˜์ง€ ์•Š๋Š”๋ฐ ๋“ค์–ด๊ฐ€์žˆ๊ตฐ์š”! Header๋Š” ๋‹จ์ˆœํžˆ ๋ ˆ์ด์•„์›ƒ ๊ธฐ๋Šฅ๋งŒ ํ•˜๊ณ  ์žˆ์–ด์„œ ํƒ€์ž…์„ ํ™•์žฅํ•˜์ง€ ์•Š์•„๋„ ๋  ๊ฒƒ ๊ฐ™์•„์š” ์งš์–ด์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ด์š”~! > common ํด๋”์—๋งŒ _๊ฐ€ ๋ถ™์–ด์žˆ๋Š”๋ฐ ์ฒ˜์Œ ๋ณด๋Š” ์ปจ๋ฒค์…˜์ด๋ผ ์–ด๋–ค ์˜๋ฏธ์ธ์ง€๋„ ๊ถ๊ธˆํ•ด์š” ใ…Žใ…Ž _๋Š” ํด๋” ์ตœ์ƒ๋‹จ์— ๋„์›Œ์ง€๋„๋ก ํ•˜๊ธฐ ์œ„ํ•ด ๋„ฃ์€ ์ปจ๋ฒค์…˜์ด๋ž๋‹ˆ๋‹ค!๐Ÿค—
@@ -0,0 +1,58 @@ +import React, { useReducer } from 'react'; +import * as S from './Header.styled'; + +interface HeaderProps extends React.InputHTMLAttributes<HTMLInputElement> { + searchKeyword: string; + onSearch: (keyword: string) => void; +} + +type State = boolean; +type Action = { type: 'TOGGLE' } | { type: 'OPEN' } | { type: 'CLOSE' }; + +function reducer(state: State, action: Action): State { + switch (action.type) { + case 'TOGGLE': + return !state; + case 'OPEN': + return true; + case 'CLOSE': + return false; + default: + return state; + } +} + +function MobileHeader({ searchKeyword, onSearch, ...rest }: HeaderProps) { + const [isExpanded, updateState] = useReducer(reducer, false); + + const handleSearchIconClick = () => { + updateState({ type: 'TOGGLE' }); + }; + + return ( + <S.Layout> + <a href="https://chosim-dvlpr.github.io/react-movie-review/"> + <S.LogoButton> + <S.LogoImage src="./logo.png" /> + </S.LogoButton> + </a> + <S.InputBox $isExpanded={isExpanded}> + <S.Input + {...rest} + value={searchKeyword} + onChange={(event: React.ChangeEvent<HTMLInputElement>) => + onSearch(event.target.value) + } + $isDisabled={!isExpanded} + disabled={!isExpanded} + /> + <S.SearchIcon + src="./search_button.png" + onClick={handleSearchIconClick} + /> + </S.InputBox> + </S.Layout> + ); +} + +export default MobileHeader;
Unknown
๋งž์•„์š”! ๊ทธ๋ฆฌ๊ณ  input์ด ๋‹ซํ˜€ ์žˆ๋Š” ๊ฒฝ์šฐ input์„ ํด๋ฆญํ–ˆ์„ ๋•Œ ๊ฐ’์ด ์ž…๋ ฅ๋˜๋ฉด์„œ ๋‹๋ณด๊ธฐ ๋ฒ„ํŠผ ์œ„๋กœ ๋ณด์—ฌ์ง€๋Š” ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ•ด์„œ disabled ์†์„ฑ์„ ์ถ”๊ฐ€ํ–ˆ์Šต๋‹ˆ๋‹น
@@ -0,0 +1,58 @@ +import React, { useReducer } from 'react'; +import * as S from './Header.styled'; + +interface HeaderProps extends React.InputHTMLAttributes<HTMLInputElement> { + searchKeyword: string; + onSearch: (keyword: string) => void; +} + +type State = boolean; +type Action = { type: 'TOGGLE' } | { type: 'OPEN' } | { type: 'CLOSE' }; + +function reducer(state: State, action: Action): State { + switch (action.type) { + case 'TOGGLE': + return !state; + case 'OPEN': + return true; + case 'CLOSE': + return false; + default: + return state; + } +} + +function MobileHeader({ searchKeyword, onSearch, ...rest }: HeaderProps) { + const [isExpanded, updateState] = useReducer(reducer, false); + + const handleSearchIconClick = () => { + updateState({ type: 'TOGGLE' }); + }; + + return ( + <S.Layout> + <a href="https://chosim-dvlpr.github.io/react-movie-review/"> + <S.LogoButton> + <S.LogoImage src="./logo.png" /> + </S.LogoButton> + </a> + <S.InputBox $isExpanded={isExpanded}> + <S.Input + {...rest} + value={searchKeyword} + onChange={(event: React.ChangeEvent<HTMLInputElement>) => + onSearch(event.target.value) + } + $isDisabled={!isExpanded} + disabled={!isExpanded} + /> + <S.SearchIcon + src="./search_button.png" + onClick={handleSearchIconClick} + /> + </S.InputBox> + </S.Layout> + ); +} + +export default MobileHeader;
Unknown
์ฒ˜์Œ์—๋Š” ํ™•์žฅ์„ฑ์„ ์—ผ๋‘ํ•˜๊ณ  ๊ฐ์ฒด๋กœ ๋งŒ๋“ค์—ˆ๋Š”๋ฐ ์ด ๊ฒฝ์šฐ์—๋Š” `isExpanded`์˜ boolean ์ƒํƒœ ๋ณ€๊ฒฝ๋งŒ์„ ๋ชฉ์ ์œผ๋กœ ํ•˜๋‹ˆ ๊ฐ์ฒด๋กœ ๋งŒ๋“ค์ง€ ์•Š๊ณ  ์˜ฌ๋ฆฌ๊ฐ€ ์ œ์•ˆํ•œ ๋ฐฉ์‹๋„ ๊ดœ์ฐฎ์„ ๊ฒƒ ๊ฐ™๋‹ค๋Š” ์ƒ๊ฐ์ด ๋“œ๋„ค์š”~!
@@ -0,0 +1,58 @@ +import React, { useReducer } from 'react'; +import * as S from './Header.styled'; + +interface HeaderProps extends React.InputHTMLAttributes<HTMLInputElement> { + searchKeyword: string; + onSearch: (keyword: string) => void; +} + +type State = boolean; +type Action = { type: 'TOGGLE' } | { type: 'OPEN' } | { type: 'CLOSE' }; + +function reducer(state: State, action: Action): State { + switch (action.type) { + case 'TOGGLE': + return !state; + case 'OPEN': + return true; + case 'CLOSE': + return false; + default: + return state; + } +} + +function MobileHeader({ searchKeyword, onSearch, ...rest }: HeaderProps) { + const [isExpanded, updateState] = useReducer(reducer, false); + + const handleSearchIconClick = () => { + updateState({ type: 'TOGGLE' }); + }; + + return ( + <S.Layout> + <a href="https://chosim-dvlpr.github.io/react-movie-review/"> + <S.LogoButton> + <S.LogoImage src="./logo.png" /> + </S.LogoButton> + </a> + <S.InputBox $isExpanded={isExpanded}> + <S.Input + {...rest} + value={searchKeyword} + onChange={(event: React.ChangeEvent<HTMLInputElement>) => + onSearch(event.target.value) + } + $isDisabled={!isExpanded} + disabled={!isExpanded} + /> + <S.SearchIcon + src="./search_button.png" + onClick={handleSearchIconClick} + /> + </S.InputBox> + </S.Layout> + ); +} + +export default MobileHeader;
Unknown
์˜ค ์ •๋ง ํ† ๊ธ€๋งŒ ์‚ฌ์šฉ ์ค‘์ด๊ตฐ์š”,,, open๊ณผ close๋Š” ์Šต๊ด€์ ์œผ๋กœ ์ž‘์„ฑํ–ˆ๋˜ ๊ฒƒ ๊ฐ™๋„ค์š” ใ…‹ใ…‹ใ…‹์ฃผ์˜ํ•ด์•ผ๊ฒ ์–ด์š”๐Ÿ˜‚ `useReducer`๋ฅผ ์‚ฌ์šฉํ•œ ์ด์œ ๋Š” `isExpanded` state๋ฅผ ์—…๋ฐ์ดํŠธ ํ•˜๋Š” ๋ฐฉ์‹์„ ๋ช…์‹œ์ ์œผ๋กœ ๋‚˜ํƒ€๋‚ด๊ธฐ ์œ„ํ•จ์ด์—ˆ์–ด์š”! `useState`๋Š” ์ƒํƒœ๋ฅผ ์–ด๋–ค ๊ฐ’์œผ๋กœ ๋ณ€๊ฒฝํ•˜๋Š”์ง€ ๋‚˜ํƒ€๋‚ธ๋‹ค๋ฉด, `useReducer`๋Š” ์–ด๋–ค ๋ฐฉ์‹์œผ๋กœ ๋ณ€๊ฒฝํ• ์ง€๋ฅผ ๋ณด์—ฌ์ค„ ์ˆ˜ ์žˆ๋‹ค๊ณ  ์ƒ๊ฐํ•ด์„œ `useReducer`๋ฅผ ์‚ฌ์šฉํ–ˆ์Šต๋‹ˆ๋‹ท
@@ -0,0 +1,49 @@ +package christmas.domain; + +import christmas.error.ErrorCode; +import java.util.Arrays; + +public enum MenuItem { + + ์–‘์†ก์ด์Šคํ”„(6_000, "์–‘์†ก์ด์Šคํ”„", MenuCategory.Appetizers), + ํƒ€ํŒŒ์Šค(5_500, "ํƒ€ํŒŒ์Šค", MenuCategory.Appetizers), + ์‹œ์ €์ƒ๋Ÿฌ๋“œ(8_000, "์‹œ์ €์ƒ๋Ÿฌ๋“œ", MenuCategory.Appetizers), + ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ(55_000, "ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ", MenuCategory.MainDishes), + ๋ฐ”๋น„ํ๋ฆฝ(54_000, "๋ฐ”๋น„ํ๋ฆฝ", MenuCategory.MainDishes), + ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€(35_000, "ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€", MenuCategory.MainDishes), + ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€(25_000, "ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€", MenuCategory.MainDishes), + ์ดˆ์ฝ”์ผ€์ดํฌ(15_000, "์ดˆ์ฝ”์ผ€์ดํฌ", MenuCategory.Desserts), + ์•„์ด์Šคํฌ๋ฆผ(5_000, "์•„์ด์Šคํฌ๋ฆผ", MenuCategory.Desserts), + ์ œ๋กœ์ฝœ๋ผ(3_000, "์ œ๋กœ์ฝœ๋ผ", MenuCategory.Drinks), + ๋ ˆ๋“œ์™€์ธ(60_000, "๋ ˆ๋“œ์™€์ธ", MenuCategory.Drinks), + ์ƒดํŽ˜์ธ(25_000, "์ƒดํŽ˜์ธ", MenuCategory.Drinks); + + private final int price; + private final String name; + private final MenuCategory category; + + MenuItem(int price, String name, MenuCategory category) { + this.price = price; + this.name = name; + this.category = category; + } + + public static MenuItem getMenuList(String menuName) { + return Arrays.stream(MenuItem.values()) + .filter(menuItem -> menuItem.name.equals(menuName)) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException(ErrorCode.INVALID_MENU_FORMAT.getMessage())); + } + + public int getPrice() { + return price; + } + + public String getName() { + return name; + } + + public MenuCategory getCategory() { + return category; + } +}
Java
MenuItem์„ enum์œผ๋กœ ๋งŒ๋“œ๋Š” ๋ฐฉ์‹์ด ์ข‹์•„๋ณด์—ฌ์š”!
@@ -0,0 +1,69 @@ +package christmas.domain.benefit; + +import christmas.domain.Calender; +import christmas.domain.Order; +import java.time.LocalDate; +import java.util.Arrays; +import java.util.List; +import java.util.function.Function; + +public enum BenefitCategory { + + ํ‰์ผํ• ์ธ("ํ‰์ผํ• ์ธ", 2_023, input -> { + + LocalDate date = (LocalDate) input; + if (date.getDayOfWeek().getValue() == 7) { + return true; + } + return date.getDayOfWeek().getValue() <= 4 && date.getDayOfWeek().getValue() >= 1; + }), + ์ฃผ๋งํ• ์ธ("์ฃผ๋งํ• ์ธ", 2_023, input -> { + + LocalDate date = (LocalDate) input; + return date.getDayOfWeek().getValue() <= 6 && date.getDayOfWeek().getValue() >= 5; + }), + ํŠน๋ณ„ํ• ์ธ("ํŠน๋ณ„ํ• ์ธ", 1_000, input -> { + + LocalDate date = (LocalDate) input; + return date.getDayOfWeek().getValue() == 7 || date.getDayOfMonth() == 25; + }), + ์ฆ์ •์ด๋ฒคํŠธ("์ฆ์ •์ด๋ฒคํŠธ", 25_000, input -> false), + ํฌ๋ฆฌ์Šค๋งˆ์Šค_๋””๋ฐ์ดํ• ์ธ("ํฌ๋ฆฌ์Šค๋งˆ์Šค_๋””๋ฐ์ดํ• ์ธ", 100, input -> { + LocalDate date = (LocalDate) input; + if (date.getDayOfMonth() <= 25) { + return true; + } + return false; + }), + ; + + private final String name; + private final int price; + private final Function<Object, Boolean> dateValidator; + + BenefitCategory(String name, int price, Function<Object, Boolean> dateValidator) { + this.name = name; + this.price = price; + this.dateValidator = dateValidator; + } + + public String getName() { + return name; + } + + public int getPrice() { + return price; + } + + public static List<BenefitCategory> getAvailableBenefitItems(Calender calender, Order order) { + List<BenefitCategory> benefitItems = new java.util.ArrayList<>(Arrays.stream(BenefitCategory.values()) + .filter(benefitItem -> benefitItem.dateValidator.apply(calender.getDate())) + .toList()); + + if (order.calculateTotalPrice() >= 120_000) { + benefitItems.add(์ฆ์ •์ด๋ฒคํŠธ); + } + + return benefitItems; + } +}
Java
enum ํด๋ž˜์Šค ๋‚ด๋ถ€์— ๋กœ์ง์ด ๋งŽ์œผ๋ฉด ๋„ˆ๋ฌด ๋ณต์žกํ•˜์ง€๋Š” ์•Š์„๊นŒ์š”?
@@ -0,0 +1,69 @@ +package christmas.domain.benefit; + +import christmas.domain.Calender; +import christmas.domain.Order; +import java.time.LocalDate; +import java.util.Arrays; +import java.util.List; +import java.util.function.Function; + +public enum BenefitCategory { + + ํ‰์ผํ• ์ธ("ํ‰์ผํ• ์ธ", 2_023, input -> { + + LocalDate date = (LocalDate) input; + if (date.getDayOfWeek().getValue() == 7) { + return true; + } + return date.getDayOfWeek().getValue() <= 4 && date.getDayOfWeek().getValue() >= 1; + }), + ์ฃผ๋งํ• ์ธ("์ฃผ๋งํ• ์ธ", 2_023, input -> { + + LocalDate date = (LocalDate) input; + return date.getDayOfWeek().getValue() <= 6 && date.getDayOfWeek().getValue() >= 5; + }), + ํŠน๋ณ„ํ• ์ธ("ํŠน๋ณ„ํ• ์ธ", 1_000, input -> { + + LocalDate date = (LocalDate) input; + return date.getDayOfWeek().getValue() == 7 || date.getDayOfMonth() == 25; + }), + ์ฆ์ •์ด๋ฒคํŠธ("์ฆ์ •์ด๋ฒคํŠธ", 25_000, input -> false), + ํฌ๋ฆฌ์Šค๋งˆ์Šค_๋””๋ฐ์ดํ• ์ธ("ํฌ๋ฆฌ์Šค๋งˆ์Šค_๋””๋ฐ์ดํ• ์ธ", 100, input -> { + LocalDate date = (LocalDate) input; + if (date.getDayOfMonth() <= 25) { + return true; + } + return false; + }), + ; + + private final String name; + private final int price; + private final Function<Object, Boolean> dateValidator; + + BenefitCategory(String name, int price, Function<Object, Boolean> dateValidator) { + this.name = name; + this.price = price; + this.dateValidator = dateValidator; + } + + public String getName() { + return name; + } + + public int getPrice() { + return price; + } + + public static List<BenefitCategory> getAvailableBenefitItems(Calender calender, Order order) { + List<BenefitCategory> benefitItems = new java.util.ArrayList<>(Arrays.stream(BenefitCategory.values()) + .filter(benefitItem -> benefitItem.dateValidator.apply(calender.getDate())) + .toList()); + + if (order.calculateTotalPrice() >= 120_000) { + benefitItems.add(์ฆ์ •์ด๋ฒคํŠธ); + } + + return benefitItems; + } +}
Java
์ฆ์ • ์ด๋ฒคํŠธ๋Š” ๋‚ ์งœ์™€๋Š” ๊ด€๋ จ์ด ์—†๋Š” ์ด๋ฒคํŠธ๋ผ function์ด ๋”ฐ๋กœ ์‚ฌ์šฉ๋˜์ง€ ์•Š๋„ค์š”. ์ฆ์ • ์ด๋ฒคํŠธ๋„ ์ด ํด๋ž˜์Šค์—์„œ ์ฒ˜๋ฆฌํ•˜๋Š”๊ฒŒ ์ข‹์€๊ฐ€์š”?
@@ -0,0 +1,40 @@ +package christmas.domain.benefit; + +import christmas.domain.Calender; +import christmas.domain.Order; +import christmas.domain.benefit.benefitItems.BenefitItem; +import christmas.domain.benefit.benefitItems.ChristmasBenefit; +import christmas.domain.benefit.benefitItems.GiftBenefit; +import christmas.domain.benefit.benefitItems.SpecialBenefit; +import christmas.domain.benefit.benefitItems.WeekdaysBenefit; +import christmas.domain.benefit.benefitItems.WeekendBenefit; +import java.util.ArrayList; +import java.util.List; + +public class BenefitItemFactory { + + public static List<BenefitItem> createBenefitItems(List<BenefitCategory> benefitCategory, Calender calender, Order order) { + List<BenefitItem> benefitItems = new ArrayList<>(); + for(BenefitCategory category : benefitCategory) { + benefitItems.add(createBenefitItem(category, calender, order)); + } + return benefitItems; + } + + private static BenefitItem createBenefitItem(BenefitCategory category, Calender calender, Order order) { + switch(category) { + case ํ‰์ผํ• ์ธ: + return WeekdaysBenefit.of(category, calender, order); + case ์ฃผ๋งํ• ์ธ: + return WeekendBenefit.of(category, calender, order); + case ํฌ๋ฆฌ์Šค๋งˆ์Šค_๋””๋ฐ์ดํ• ์ธ: + return ChristmasBenefit.of(category, calender, order); + case ํŠน๋ณ„ํ• ์ธ: + return SpecialBenefit.of(category, calender, order); + case ์ฆ์ •์ด๋ฒคํŠธ: + return GiftBenefit.of(category, calender, order); + default: + throw new IllegalArgumentException("์ž˜๋ชป๋œ ํ˜œํƒ ์นดํ…Œ๊ณ ๋ฆฌ์ž…๋‹ˆ๋‹ค."); + } + } +}
Java
ํŒฉํ† ๋ฆฌ ํŒจํ„ด์„ ์‚ฌ์šฉํ•˜์‹  ๊ฒƒ ๊ฐ™์€๋ฐ ์—ฌ๊ธฐ์„œ ํŒฉํ† ๋ฆฌ ํŒจํ„ด์„ ์‚ฌ์šฉํ•˜๋ฉด ์–ด๋–ค ์ด์ ์„ ์–ป์„ ์ˆ˜ ์žˆ๋Š”์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,40 @@ +package christmas.domain.benefit; + +import christmas.domain.Calender; +import christmas.domain.Order; +import christmas.domain.benefit.benefitItems.BenefitItem; +import christmas.domain.benefit.benefitItems.ChristmasBenefit; +import christmas.domain.benefit.benefitItems.GiftBenefit; +import christmas.domain.benefit.benefitItems.SpecialBenefit; +import christmas.domain.benefit.benefitItems.WeekdaysBenefit; +import christmas.domain.benefit.benefitItems.WeekendBenefit; +import java.util.ArrayList; +import java.util.List; + +public class BenefitItemFactory { + + public static List<BenefitItem> createBenefitItems(List<BenefitCategory> benefitCategory, Calender calender, Order order) { + List<BenefitItem> benefitItems = new ArrayList<>(); + for(BenefitCategory category : benefitCategory) { + benefitItems.add(createBenefitItem(category, calender, order)); + } + return benefitItems; + } + + private static BenefitItem createBenefitItem(BenefitCategory category, Calender calender, Order order) { + switch(category) { + case ํ‰์ผํ• ์ธ: + return WeekdaysBenefit.of(category, calender, order); + case ์ฃผ๋งํ• ์ธ: + return WeekendBenefit.of(category, calender, order); + case ํฌ๋ฆฌ์Šค๋งˆ์Šค_๋””๋ฐ์ดํ• ์ธ: + return ChristmasBenefit.of(category, calender, order); + case ํŠน๋ณ„ํ• ์ธ: + return SpecialBenefit.of(category, calender, order); + case ์ฆ์ •์ด๋ฒคํŠธ: + return GiftBenefit.of(category, calender, order); + default: + throw new IllegalArgumentException("์ž˜๋ชป๋œ ํ˜œํƒ ์นดํ…Œ๊ณ ๋ฆฌ์ž…๋‹ˆ๋‹ค."); + } + } +}
Java
๊ตฌํ˜„ ์กฐ๊ฑด์— switch ๋ฌธ์€ ์‚ฌ์šฉ ๊ธˆ์ง€๋ผ๊ณ  ๋˜์–ด ์žˆ์–ด์„œ... if๋ฌธ์œผ๋กœ ์ถฉ๋ถ„ํžˆ ๋ฐ”๊ฟ€ ์ˆ˜ ์žˆ์–ด ๋ณด์—ฌ์„œ ํฌ๊ฒŒ ์ค‘์š”ํ•˜์ง„ ์•Š์€ ๊ฒƒ ๊ฐ™์•„์š”
@@ -0,0 +1,54 @@ +package christmas.domain.benefit; + +import christmas.domain.Calender; +import christmas.domain.Order; +import christmas.domain.benefit.benefitItems.BenefitItem; +import java.util.List; + +public class Benefits { + + public static final int GIFT_PRICE = 25_000; + private List<BenefitItem> benefitItems; + + public Benefits(Calender calender, Order order) { + List<BenefitCategory> benefitCategory = BenefitCategory.getAvailableBenefitItems(calender, order); + this.benefitItems = BenefitItemFactory.createBenefitItems(benefitCategory, calender, order); + } + + public List<BenefitItem> getBenefitItems() { + return benefitItems; + } + + public int getBenefitPrice() { + return benefitItems.stream() + .mapToInt(BenefitItem::getDiscountPrice) + .sum(); + } + + public int getDiscountPrice(){ + int sum = benefitItems.stream() + .mapToInt(BenefitItem::getDiscountPrice) + .sum(); + + if(isGiftBenefit()) + sum -= GIFT_PRICE; + + return sum; + } + + public String getGiftBenefit() { + if(isGiftBenefit()) { + return "์ƒดํŽ˜์ธ 1๊ฐœ"; + } + return "์—†์Œ"; + } + + private boolean isGiftBenefit() { + return benefitItems.stream() + .anyMatch(benefitItem -> benefitItem.getBenefitCategory() == BenefitCategory.์ฆ์ •์ด๋ฒคํŠธ); + } + + public Badges getBadges() { + return Badges.getBadge(getBenefitPrice()); + } +}
Java
์ฆ์ • ์ด๋ฒคํŠธ์˜ ํ• ์ธ ๊ธˆ์•ก์€ ์‚ฌ์šฉ์ž์—๊ฒŒ ๋ณด์—ฌ์ฃผ๊ธฐ๋งŒ ํ•˜๊ณ  ์˜ˆ์ƒ ๊ฒฐ์ œ ๊ธˆ์•ก์—๋Š” ์ ์šฉ๋˜์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์— ์—ฌ๊ธฐ์„œ ์ฒ˜๋ฆฌํ•ด ์ฃผ๋Š”๊ฒŒ ์ข‹์€ ๋ฐฉ๋ฒ• ๊ฐ™์•„์š”!
@@ -0,0 +1,21 @@ +package christmas.domain.benefit.benefitItems; + +import christmas.domain.Calender; +import christmas.domain.Order; +import christmas.domain.benefit.BenefitCategory; + +public class ChristmasBenefit extends BenefitItem { + + public ChristmasBenefit(BenefitCategory benefitCategory, int discountPrice) { + super(benefitCategory, discountPrice); + } + + public static ChristmasBenefit of(BenefitCategory benefitCategory, Calender calender, Order order) { + return new ChristmasBenefit(benefitCategory, calculateDiscountPrice(benefitCategory, calender, order)); + } + + private static int calculateDiscountPrice(BenefitCategory benefitCategory, Calender calender, Order order) { + + return 1000 + (calender.getDate().getDayOfMonth() - 1) * benefitCategory.getPrice(); + } +}
Java
1000์€ ๋งค์ง ๋„˜๋ฒ„๋กœ ์‚ฌ์šฉํ•ด์ค˜๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,65 @@ +package christmas.io; + +import christmas.domain.Calender; +import christmas.domain.Order; +import christmas.error.ErrorCode; +import java.util.function.Supplier; + +public class InputView implements AutoCloseable { + + private final Reader DEFAULT_READER = new ConsoleReader(); + private final Reader reader; + + public InputView(Reader reader) { + this.reader = reader; + } + + public InputView() { + this.reader = DEFAULT_READER; + } + + private String readLine() { + String input = reader.readLine(); + validate(input); + return input; + } + + private static void printReInput(IllegalArgumentException ex) { + System.out.flush(); + System.out.println(ex.getMessage()); + } + + private static void validate(String input) { + if (input.isBlank()) { + throw new IllegalArgumentException(ErrorCode.BLANK_INPUT_MESSAGE.getMessage()); + } + } + + public Calender inputDate() { + return retryInput("12์›” ์ค‘ ์‹๋‹น ์˜ˆ์ƒ ๋ฐฉ๋ฌธ ๋‚ ์งœ๋Š” ์–ธ์ œ์ธ๊ฐ€์š”? (์ˆซ์ž๋งŒ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”!)", + () -> new Calender(readLine())); + } + + public Order inputMenu() { + return retryInput("์ฃผ๋ฌธํ•˜์‹ค ๋ฉ”๋‰ด์™€ ๊ฐœ์ˆ˜๋ฅผ ์•Œ๋ ค ์ฃผ์„ธ์š”. (e.g. ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€-2,๋ ˆ๋“œ์™€์ธ-1,์ดˆ์ฝ”์ผ€์ดํฌ-1)", + () -> new Order(readLine())); + } + + + private static <T> T retryInput(String prompt, Supplier<T> inputSupplier) { + System.out.println(prompt); + while (true) { + try { + T result = inputSupplier.get(); + return result; + } catch (IllegalArgumentException ex) { + printReInput(ex); + } + } + } + + @Override + public void close() { + reader.close(); + } +}
Java
๋‹ค์‹œ ์ž…๋ ฅ ๋ฐ›๋Š” ๋ฉ”์„œ๋“œ๋ฅผ ์ œ๋„ค๋ฆญ๊ณผ ์„œํ”Œ๋ผ์ด์–ด๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๊ตฌํ˜„ํ•˜๋Š” ๋ฐฉ์‹์ด ์ข‹์•„๋ณด์—ฌ์š”!
@@ -0,0 +1,80 @@ +package christmas.io; + +import christmas.domain.benefit.Benefits; +import christmas.domain.Calender; +import christmas.domain.Order; +import christmas.domain.OrderItem; +import java.text.DecimalFormat; +import java.time.LocalDate; +import java.util.List; + +public class OutputView { + + public static void printWelcomeMessage() { + System.out.println("์•ˆ๋…•ํ•˜์„ธ์š”! ์šฐํ…Œ์ฝ” ์‹๋‹น 12์›” ์ด๋ฒคํŠธ ํ”Œ๋ž˜๋„ˆ์ž…๋‹ˆ๋‹ค."); + } + + public static void printEventMessage(Calender calender) { + LocalDate date = calender.getDate(); + System.out.println(date.getMonth().getValue() + "์›” " + date.getDayOfMonth() + "์ผ์— ์šฐํ…Œ์ฝ” ์‹๋‹น์—์„œ ๋ฐ›์„ ์ด๋ฒคํŠธ ํ˜œํƒ ๋ฏธ๋ฆฌ ๋ณด๊ธฐ! \n"); + } + + public static void printOrderMenu(Order order) { + System.out.println("<์ฃผ๋ฌธ ๋ฉ”๋‰ด>"); + List<OrderItem> orderItems = order.getOrderItems(); + orderItems.forEach( + orderItem -> System.out.println(orderItem.getName() + " " + orderItem.getOrderCount() + "๊ฐœ") + ); + System.out.println(); + } + + public static void printTotalPrice(Order order) { + int totalPrice = order.calculateTotalPrice(); + DecimalFormat df = new DecimalFormat("###,###"); + System.out.println("<ํ• ์ธ ์ „ ์ด์ฃผ๋ฌธ ๊ธˆ์•ก>"); + System.out.println(df.format(totalPrice) + "์›\n"); + } + + public static void printBenefit(Order order, Benefits benefits){ + printGiftBenefit(benefits); + printBenefits(benefits); + printTotalDiscountPrice(benefits); + printAfterDiscountPrice(order, benefits); + printBadge(benefits); + } + + public static void printGiftBenefit(Benefits benefits) { + System.out.println("<์ฆ์ • ๋ฉ”๋‰ด>"); + System.out.println(benefits.getGiftBenefit() + "\n"); + } + + public static void printBenefits(Benefits benefits) { + System.out.println("<ํ˜œํƒ ๋‚ด์—ญ>"); + benefits.getBenefitItems().forEach( + benefitItem -> { + DecimalFormat df = new DecimalFormat("###,###"); + System.out.println(benefitItem.getName() + ": -" + df.format(benefitItem.getDiscountPrice()) + "์›"); + } + ); + System.out.println(); + } + + public static void printTotalDiscountPrice(Benefits benefits) { + System.out.println("<์ดํ˜œํƒ ๊ธˆ์•ก>"); + int totalDiscountPrice = benefits.getBenefitPrice(); + DecimalFormat df = new DecimalFormat("###,###"); + System.out.println("-" + df.format(totalDiscountPrice) + "์›\n"); + } + + public static void printAfterDiscountPrice(Order order, Benefits benefits) { + int afterDiscountPrice = order.calculateTotalPrice() - benefits.getDiscountPrice(); + DecimalFormat df = new DecimalFormat("###,###"); + System.out.println("<ํ• ์ธ ํ›„ ์˜ˆ์ƒ ๊ฒฐ์ œ ๊ธˆ์•ก>"); + System.out.println(df.format(afterDiscountPrice) + "์›\n"); + } + + public static void printBadge(Benefits benefits) { + System.out.println("<12์›” ์ด๋ฒคํŠธ ๋ฐฐ์ง€>"); + System.out.println(benefits.getBadges().getName()); + } +}
Java
DecimalFormat ์ด๋ผ๋Š” ๊ฒƒ๋„ ์žˆ๊ตฐ์š”... ๋” ์ฐพ์•„๋ด์•ผ๊ฒ ์–ด์š”
@@ -0,0 +1,80 @@ +package christmas.io; + +import christmas.domain.benefit.Benefits; +import christmas.domain.Calender; +import christmas.domain.Order; +import christmas.domain.OrderItem; +import java.text.DecimalFormat; +import java.time.LocalDate; +import java.util.List; + +public class OutputView { + + public static void printWelcomeMessage() { + System.out.println("์•ˆ๋…•ํ•˜์„ธ์š”! ์šฐํ…Œ์ฝ” ์‹๋‹น 12์›” ์ด๋ฒคํŠธ ํ”Œ๋ž˜๋„ˆ์ž…๋‹ˆ๋‹ค."); + } + + public static void printEventMessage(Calender calender) { + LocalDate date = calender.getDate(); + System.out.println(date.getMonth().getValue() + "์›” " + date.getDayOfMonth() + "์ผ์— ์šฐํ…Œ์ฝ” ์‹๋‹น์—์„œ ๋ฐ›์„ ์ด๋ฒคํŠธ ํ˜œํƒ ๋ฏธ๋ฆฌ ๋ณด๊ธฐ! \n"); + } + + public static void printOrderMenu(Order order) { + System.out.println("<์ฃผ๋ฌธ ๋ฉ”๋‰ด>"); + List<OrderItem> orderItems = order.getOrderItems(); + orderItems.forEach( + orderItem -> System.out.println(orderItem.getName() + " " + orderItem.getOrderCount() + "๊ฐœ") + ); + System.out.println(); + } + + public static void printTotalPrice(Order order) { + int totalPrice = order.calculateTotalPrice(); + DecimalFormat df = new DecimalFormat("###,###"); + System.out.println("<ํ• ์ธ ์ „ ์ด์ฃผ๋ฌธ ๊ธˆ์•ก>"); + System.out.println(df.format(totalPrice) + "์›\n"); + } + + public static void printBenefit(Order order, Benefits benefits){ + printGiftBenefit(benefits); + printBenefits(benefits); + printTotalDiscountPrice(benefits); + printAfterDiscountPrice(order, benefits); + printBadge(benefits); + } + + public static void printGiftBenefit(Benefits benefits) { + System.out.println("<์ฆ์ • ๋ฉ”๋‰ด>"); + System.out.println(benefits.getGiftBenefit() + "\n"); + } + + public static void printBenefits(Benefits benefits) { + System.out.println("<ํ˜œํƒ ๋‚ด์—ญ>"); + benefits.getBenefitItems().forEach( + benefitItem -> { + DecimalFormat df = new DecimalFormat("###,###"); + System.out.println(benefitItem.getName() + ": -" + df.format(benefitItem.getDiscountPrice()) + "์›"); + } + ); + System.out.println(); + } + + public static void printTotalDiscountPrice(Benefits benefits) { + System.out.println("<์ดํ˜œํƒ ๊ธˆ์•ก>"); + int totalDiscountPrice = benefits.getBenefitPrice(); + DecimalFormat df = new DecimalFormat("###,###"); + System.out.println("-" + df.format(totalDiscountPrice) + "์›\n"); + } + + public static void printAfterDiscountPrice(Order order, Benefits benefits) { + int afterDiscountPrice = order.calculateTotalPrice() - benefits.getDiscountPrice(); + DecimalFormat df = new DecimalFormat("###,###"); + System.out.println("<ํ• ์ธ ํ›„ ์˜ˆ์ƒ ๊ฒฐ์ œ ๊ธˆ์•ก>"); + System.out.println(df.format(afterDiscountPrice) + "์›\n"); + } + + public static void printBadge(Benefits benefits) { + System.out.println("<12์›” ์ด๋ฒคํŠธ ๋ฐฐ์ง€>"); + System.out.println(benefits.getBadges().getName()); + } +}
Java
์ดํ˜œํƒ ๊ธˆ์•ก์ด 0์ผ ๊ฒฝ์šฐ -0์œผ๋กœ ์ถœ๋ ฅ๋  ์ˆ˜๋„ ์žˆ์ง€ ์•Š์„๊นŒ์š”?
@@ -0,0 +1,44 @@ +package christmas.domain; + +import christmas.error.ErrorCode; +import java.util.Arrays; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +public class Order { + + private final String DELIMITER = ","; + private final List<OrderItem> orderItems; + + public Order(String orderInputs) { + this.orderItems = createOrderItems(orderInputs); + } + + public List<OrderItem> getOrderItems() { + return orderItems; + } + + public int calculateTotalPrice() { + return orderItems.stream() + .mapToInt(OrderItem::getPrice) + .sum(); + } + + private List<OrderItem> createOrderItems(String orderInputs) { + List<OrderItem> orderItems = Arrays.stream(orderInputs.split(DELIMITER)) + .map(OrderItem::new) + .toList(); + validateDuplication(orderItems); + return orderItems; + } + + private static void validateDuplication(List<OrderItem> orderItems) { + Set<String> duplicateChecker = orderItems.stream() + .map(OrderItem::getName) + .collect(Collectors.toSet()); + if (duplicateChecker.size() != orderItems.size()) { + throw new IllegalArgumentException(ErrorCode.INVALID_MENU_FORMAT.getMessage()); + } + } +}
Java
๋ฉ”๋‰ด๋Š” ํ•œ ๋ฒˆ ์ตœ๋Œ€ 20๊ฐœ๊นŒ์ง€๋งŒ ์ฃผ๋ฌธํ•  ์ˆ˜ ์žˆ๋Š”๋ฐ ์ด ๋ถ€๋ถ„์€ ๊ฒ€์ฆํ•˜๋Š” ๊ณณ์ด ์žˆ์„๊นŒ์š”? ์ด์ฃผ๋ฌธ ๊ธˆ์•ก 10000์› ์ด์ƒ๋ถ€ํ„ฐ ์ด๋ฒคํŠธ๊ฐ€ ์ ์šฉ๋˜๋Š” ๋ถ€๋ถ„, ์Œ๋ฃŒ๋งŒ ์ฃผ๋ฌธ ์‹œ ์ฃผ๋ฌธ์ด ๋ถˆ๊ฐ€๋Šฅํ•œ ๊ฒƒ์„ ์ฒดํฌํ•ด์ฃผ๋Š” ๋ถ€๋ถ„์ด ์žˆ๋‚˜์š”?
@@ -0,0 +1,43 @@ +package com.ll.backend.domain.admin.controller; + +import com.ll.backend.domain.admin.dto.AdminRequestDto; +import com.ll.backend.domain.admin.entity.Admin; +import com.ll.backend.domain.admin.service.AdminService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/admin") +public class AdminController { + private final AdminService adminService; + + //ํšŒ์›๊ฐ€์ž… + @PostMapping("/register") + public ResponseEntity<String> registerAdmin(@RequestBody AdminRequestDto request) { + try { + adminService.registerAdmin(request.getUsername(), request.getPassword()); + return ResponseEntity.ok("Admin registered successfully."); + } catch (Exception e) { + return ResponseEntity.badRequest().body("Error: " + e.getMessage()); + } + } + + //๋กœ๊ทธ์ธ + @PostMapping("/login") + public ResponseEntity<String> loginAdmin(@RequestBody AdminRequestDto request) { + try { + Admin admin = adminService.validateAdmin(request.getUsername(), request.getPassword()); + return ResponseEntity.ok("Welcome, " + admin.getUsername()); + } catch (IllegalArgumentException e) { + return ResponseEntity.badRequest().body("Error: " + e.getMessage()); + } + } + + + +} + + +
Java
์™ธ๋ถ€์—๋Š” ์—๋Ÿฌ๊ฐ€ ์ตœ๋Œ€ํ•˜๊ฒŒ ๋…ธ์ถœ๋˜์ง€ ์•Š๋„๋ก ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. (ํŠนํžˆ๋‚˜, ์—๋Ÿฌ๊ฐ€ ๊ตฌ์ฒดํ™”๊ฐ€ ๋˜๋ฉด ์•ˆ ๋ฉ๋‹ˆ๋‹ค.) -> ์™ธ๋ถ€ ๊ณต๊ฒฉ์ž ์ž…์žฅ์—์„œ, ์ด ์„œ๋ฒ„์˜ ์ทจ์•ฝ์ ์ด ๋ฌด์—‡์ธ์ง€ ํŒ๋‹จํ•˜๊ธฐ ์‰ฌ์›Œ์ ธ์š”.
@@ -0,0 +1,43 @@ +package com.ll.backend.domain.admin.controller; + +import com.ll.backend.domain.admin.dto.AdminRequestDto; +import com.ll.backend.domain.admin.entity.Admin; +import com.ll.backend.domain.admin.service.AdminService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/admin") +public class AdminController { + private final AdminService adminService; + + //ํšŒ์›๊ฐ€์ž… + @PostMapping("/register") + public ResponseEntity<String> registerAdmin(@RequestBody AdminRequestDto request) { + try { + adminService.registerAdmin(request.getUsername(), request.getPassword()); + return ResponseEntity.ok("Admin registered successfully."); + } catch (Exception e) { + return ResponseEntity.badRequest().body("Error: " + e.getMessage()); + } + } + + //๋กœ๊ทธ์ธ + @PostMapping("/login") + public ResponseEntity<String> loginAdmin(@RequestBody AdminRequestDto request) { + try { + Admin admin = adminService.validateAdmin(request.getUsername(), request.getPassword()); + return ResponseEntity.ok("Welcome, " + admin.getUsername()); + } catch (IllegalArgumentException e) { + return ResponseEntity.badRequest().body("Error: " + e.getMessage()); + } + } + + + +} + + +
Java
๋งŒ์•ฝ์— ์ด๊ฒŒ ์„œ๋ฒ„ ์—๋Ÿฌ๊ฐ€ ์•„๋‹ˆ๋ผ, ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฐ’์„ ํ•„ํ„ฐ๋งํ•˜๊ธฐ ์œ„ํ•œ ์˜ˆ์™ธ๋ผ๋ฉด, `catch (Exception e)` ๊ฐ€ ์•„๋‹ˆ๋ผ `catch (ServiceException e)` ์™€ ๊ฐ™์ด, ์—ฌ๋Ÿฌ๋ถ„๋“ค์ด ๋งŒ๋“  ์˜ˆ์™ธ๋งŒ catch ํ•˜๋„๋ก ๋งŒ๋“ค์–ด์ค˜์•ผ ํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,11 @@ +package com.ll.backend.domain.admin.dto; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class AdminRequestDto { + private String username; + private String password; +}
Java
record๋กœ ์ˆ˜์ •ํ•ด ์ฃผ์„ธ์š”.
@@ -0,0 +1,27 @@ +package com.ll.backend.domain.admin.service; + +import com.ll.backend.domain.order.entity.Order; +import com.ll.backend.domain.order.repository.OrderRepository; +import com.ll.backend.domain.orderdetail.repository.OrderDetailRepository; +import com.ll.backend.domain.product.repository.ProductRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class AdminNotificationService { + private final OrderRepository orderRepository; + private final ProductRepository productRepository; + private final OrderDetailRepository orderDetailRepository; + + // ๊ฒฐ์ œ ์™„๋ฃŒ ์‹œ ๊ด€๋ฆฌ์ž์—๊ฒŒ ๋ฐฐ์†ก ์š”์ฒญ ๋กœ์ง + public void notifyAdminForShipping(int orderId) { + // ์ฃผ๋ฌธ ์กฐํšŒ + Order order = orderRepository.findById(orderId) + .orElseThrow(() -> new IllegalArgumentException("Order not found for ID: " + orderId)); + + // ๊ด€๋ฆฌ์ž์—๊ฒŒ ์•Œ๋ฆผ + System.out.println("Admin notified for shipping. Order ID: " + orderId); + } + +}
Java
๊ฐ€๋Šฅํ•˜๋ฉด, ์ด๋Ÿฐ ์‹์˜ "์„œ๋น„์Šค ์ ์ธ ์˜ˆ์™ธ"๋Š” ์ž๋ฐ”์—์„œ ์ •์˜ํ•œ ๊ธฐ๋ณธ ์˜ˆ์™ธ๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ๊ฒƒ์„ ๊ถŒ์žฅ๋“œ๋ ค์š”.
@@ -0,0 +1,27 @@ +package com.ll.backend.domain.admin.service; + +import com.ll.backend.domain.order.entity.Order; +import com.ll.backend.domain.order.repository.OrderRepository; +import com.ll.backend.domain.orderdetail.repository.OrderDetailRepository; +import com.ll.backend.domain.product.repository.ProductRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class AdminNotificationService { + private final OrderRepository orderRepository; + private final ProductRepository productRepository; + private final OrderDetailRepository orderDetailRepository; + + // ๊ฒฐ์ œ ์™„๋ฃŒ ์‹œ ๊ด€๋ฆฌ์ž์—๊ฒŒ ๋ฐฐ์†ก ์š”์ฒญ ๋กœ์ง + public void notifyAdminForShipping(int orderId) { + // ์ฃผ๋ฌธ ์กฐํšŒ + Order order = orderRepository.findById(orderId) + .orElseThrow(() -> new IllegalArgumentException("Order not found for ID: " + orderId)); + + // ๊ด€๋ฆฌ์ž์—๊ฒŒ ์•Œ๋ฆผ + System.out.println("Admin notified for shipping. Order ID: " + orderId); + } + +}
Java
log๋กœ ๋Œ€์ฒดํ•ด ์ฃผ์„ธ์š”.
@@ -0,0 +1,56 @@ +package com.ll.backend.domain.admin.service; + +import com.ll.backend.domain.admin.entity.Admin; +import com.ll.backend.domain.admin.repository.AdminRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; + +import java.util.Optional; + +@Service +@RequiredArgsConstructor +public class AdminService { + private final AdminRepository adminRepository; + private final PasswordEncoder passwordEncoder; + + //๊ด€๋ฆฌ์ž ํšŒ์›๊ฐ€์ž… + public Admin registerAdmin(String username, String password){ + if (adminRepository.findByUsername(username).isPresent()) { + throw new IllegalArgumentException("์ด๋ฏธ ์กด์žฌํ•˜๋Š” ์‚ฌ์šฉ์ž ์ด๋ฆ„์ž…๋‹ˆ๋‹ค."); + } + + Admin admin = new Admin(); + admin.setUsername(username); + admin.setPassword(passwordEncoder.encode(password)); + return adminRepository.save(admin); + } + + //๊ด€๋ฆฌ์ž ๋กœ๊ทธ์ธ ๊ฒ€์ฆ + public Admin validateAdmin(String username, String password){ + Optional<Admin> oa=adminRepository.findByUsername(username); + if(oa.isEmpty()){ + throw new IllegalArgumentException("์‚ฌ์šฉ์ž๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + + Admin admin=oa.get(); + if(!passwordEncoder.matches(password,admin.getPassword())){ + throw new IllegalArgumentException("๋น„๋ฐ€๋ฒˆํ˜ธ๊ฐ€ ์ผ์น˜ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค."); + } + + return admin; + } + + //๊ด€๋ฆฌ์ž ์กฐํšŒ + public Optional<Admin> getAdmin(String username){ + return adminRepository.findByUsername(username); + } + + public Optional<Admin> findByUsername(String user1) { + return adminRepository.findByUsername(user1); + } + + public long count() { + return adminRepository.count(); + } +}
Java
๊ฐ€๋Šฅํ•˜๋ฉด, ์ตœ๋Œ€ํ•œ ๋งŽ์€ ๊ฐ์ฒด๋“ค์—์„œ setter ์ง์ ‘ ํ˜ธ์ถœ์„ ๋ฐฐ์ œํ•ด ์ฃผ์„ธ์š”.
@@ -0,0 +1,56 @@ +package com.ll.backend.domain.admin.service; + +import com.ll.backend.domain.admin.entity.Admin; +import com.ll.backend.domain.admin.repository.AdminRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; + +import java.util.Optional; + +@Service +@RequiredArgsConstructor +public class AdminService { + private final AdminRepository adminRepository; + private final PasswordEncoder passwordEncoder; + + //๊ด€๋ฆฌ์ž ํšŒ์›๊ฐ€์ž… + public Admin registerAdmin(String username, String password){ + if (adminRepository.findByUsername(username).isPresent()) { + throw new IllegalArgumentException("์ด๋ฏธ ์กด์žฌํ•˜๋Š” ์‚ฌ์šฉ์ž ์ด๋ฆ„์ž…๋‹ˆ๋‹ค."); + } + + Admin admin = new Admin(); + admin.setUsername(username); + admin.setPassword(passwordEncoder.encode(password)); + return adminRepository.save(admin); + } + + //๊ด€๋ฆฌ์ž ๋กœ๊ทธ์ธ ๊ฒ€์ฆ + public Admin validateAdmin(String username, String password){ + Optional<Admin> oa=adminRepository.findByUsername(username); + if(oa.isEmpty()){ + throw new IllegalArgumentException("์‚ฌ์šฉ์ž๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + + Admin admin=oa.get(); + if(!passwordEncoder.matches(password,admin.getPassword())){ + throw new IllegalArgumentException("๋น„๋ฐ€๋ฒˆํ˜ธ๊ฐ€ ์ผ์น˜ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค."); + } + + return admin; + } + + //๊ด€๋ฆฌ์ž ์กฐํšŒ + public Optional<Admin> getAdmin(String username){ + return adminRepository.findByUsername(username); + } + + public Optional<Admin> findByUsername(String user1) { + return adminRepository.findByUsername(user1); + } + + public long count() { + return adminRepository.count(); + } +}
Java
```java Admin admin = adminRepository.findByUsername(username) .orElseThrow(() -> new IllegalArgumentException("์‚ฌ์šฉ์ž๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")); ```
@@ -0,0 +1,42 @@ +package com.ll.backend.domain.order.controller; + +import com.ll.backend.domain.order.dto.OrderRequestDto; +import com.ll.backend.domain.order.entity.Order; +import com.ll.backend.domain.order.service.OrderService; +import com.ll.backend.domain.orderdetail.service.OrderDetailService; +import com.ll.backend.domain.order.dto.OrderResponseDto; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequiredArgsConstructor +public class OrderController { + private final OrderService orderService; + private final OrderDetailService orderDetailService; + + record OrderCreated(Integer id,String message) {} + + //์ฃผ๋ฌธ์ƒ์„ฑ + @PostMapping("/api/main/order") + public ResponseEntity<OrderCreated> createOrder(@RequestBody OrderRequestDto orderRequestDto){ + Order order = orderService.createOrder(orderRequestDto); + orderDetailService.createOrderDetails(order, orderRequestDto.getProducts()); + return ResponseEntity.ok(new OrderCreated(order.getId(),"Order successfully created.")); + } + + @GetMapping("/admin/orderList") + public ResponseEntity<List<OrderResponseDto>> getOrderList() { + List<OrderResponseDto> orderList = orderService.getOrderList(); + if (orderList.isEmpty()) { + return ResponseEntity.noContent().build(); + } + return ResponseEntity.ok(orderList); + } + +}
Java
์š”๊ฑฐ๋Š” ๊ฐ’์ด ์—†๋‹ค๊ณ  ํ•ด์„œ status๋ฅผ ๋‹ค๋ฅด๊ฒŒ ์ฃผ๋Š” ๊ฑด ์•„๋‹Œ ๊ฒƒ ๊ฐ™์•„์š”. (204 -> no content ๊ฐ€ ๋งž๊ธด ํ•œ๋ฐ, ์ €๊ฑด ์‘๋‹ต์ด ํ•„์š” ์—†๋Š” ์š”์ฒญ์— ๋Œ€ํ•œ ์‘๋‹ต ์ฝ”๋“œ์—์š”.)
@@ -0,0 +1,15 @@ +package com.ll.backend.domain.order.dto; + +import com.ll.backend.domain.orderdetail.dto.OrderDetailRequestDto; +import lombok.Getter; + +import java.util.List; + +@Getter +public class OrderRequestDto { + private String email; + private String address; + private String postalCode; + private Integer totalPrice; + private List<OrderDetailRequestDto> products; +}
Java
Jakarta Validation ์ ์šฉ
@@ -0,0 +1,81 @@ +package com.ll.backend.domain.order.service; + +import com.ll.backend.domain.order.OrderStatus; +import com.ll.backend.domain.order.dto.OrderRequestDto; +import com.ll.backend.domain.order.dto.OrderResponseDto; +import com.ll.backend.domain.order.entity.Order; +import com.ll.backend.domain.order.repository.OrderRepository; +import com.ll.backend.domain.orderdetail.service.OrderDetailService; +import com.ll.backend.domain.product.repository.ProductRepository; +import jakarta.transaction.Transactional; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.List; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +public class OrderService { + private final OrderRepository orderRepository; + private final ProductRepository productRepository; + private final OrderDetailService orderDetailService; + + + // ์ฃผ๋ฌธ ์ƒ์„ฑ + @Transactional + public Order createOrder(OrderRequestDto orderRequestDto) { + + // ์ฃผ๋ฌธ ์ •๋ณด ์ƒ์„ฑ + Order order = new Order( + orderRequestDto.getEmail(), + orderRequestDto.getAddress(), + orderRequestDto.getPostalCode(), + setOrderStateBasedOnTime(), + orderRequestDto.getTotalPrice() + ); + + // ์ฃผ๋ฌธ ์ €์žฅ + return orderRepository.save(order); + } + + private OrderStatus setOrderStateBasedOnTime() { + LocalDateTime now = LocalDateTime.now(); + LocalTime cutoffTime = LocalTime.of(14, 0); // ์˜คํ›„ 2์‹œ ๊ธฐ์ค€ + + if (now.toLocalTime().isBefore(cutoffTime)) { + return OrderStatus.SHIPPED; + } else { + return OrderStatus.PENDING; + } + } + + public long count() { + return orderRepository.count(); + } + + public Order initDataOrder(Order order) { + return orderRepository.save(order); + } + + @Transactional() + public List<OrderResponseDto> getOrderList() { + List<Order> orders = orderRepository.findAll(); + + return orders.stream() + .map(order -> new OrderResponseDto( + order.getId(), + order.getEmail(), + order.getAddress(), + order.getPostalCode(), + order.getState().toString(), + order.getTotalPrice(), + order.getOrderDate() + )) + .collect(Collectors.toList()); + } +} + +
Java
๊ฐ์ฒด ์„ธํŒ…์€ ๊ฐ€๋Šฅํ•˜๋ฉด Service ์ด์™ธ์˜ ๊ณณ์œผ๋กœ ์œ ๋ฐฐ ๋ณด๋‚ด์‹œ์ฃ . ```java return orderRepository.findAll().stream() .map(OrderConverter::toOrderResponse) .toList(); ```
@@ -0,0 +1,81 @@ +package com.ll.backend.domain.order.service; + +import com.ll.backend.domain.order.OrderStatus; +import com.ll.backend.domain.order.dto.OrderRequestDto; +import com.ll.backend.domain.order.dto.OrderResponseDto; +import com.ll.backend.domain.order.entity.Order; +import com.ll.backend.domain.order.repository.OrderRepository; +import com.ll.backend.domain.orderdetail.service.OrderDetailService; +import com.ll.backend.domain.product.repository.ProductRepository; +import jakarta.transaction.Transactional; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.List; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +public class OrderService { + private final OrderRepository orderRepository; + private final ProductRepository productRepository; + private final OrderDetailService orderDetailService; + + + // ์ฃผ๋ฌธ ์ƒ์„ฑ + @Transactional + public Order createOrder(OrderRequestDto orderRequestDto) { + + // ์ฃผ๋ฌธ ์ •๋ณด ์ƒ์„ฑ + Order order = new Order( + orderRequestDto.getEmail(), + orderRequestDto.getAddress(), + orderRequestDto.getPostalCode(), + setOrderStateBasedOnTime(), + orderRequestDto.getTotalPrice() + ); + + // ์ฃผ๋ฌธ ์ €์žฅ + return orderRepository.save(order); + } + + private OrderStatus setOrderStateBasedOnTime() { + LocalDateTime now = LocalDateTime.now(); + LocalTime cutoffTime = LocalTime.of(14, 0); // ์˜คํ›„ 2์‹œ ๊ธฐ์ค€ + + if (now.toLocalTime().isBefore(cutoffTime)) { + return OrderStatus.SHIPPED; + } else { + return OrderStatus.PENDING; + } + } + + public long count() { + return orderRepository.count(); + } + + public Order initDataOrder(Order order) { + return orderRepository.save(order); + } + + @Transactional() + public List<OrderResponseDto> getOrderList() { + List<Order> orders = orderRepository.findAll(); + + return orders.stream() + .map(order -> new OrderResponseDto( + order.getId(), + order.getEmail(), + order.getAddress(), + order.getPostalCode(), + order.getState().toString(), + order.getTotalPrice(), + order.getOrderDate() + )) + .collect(Collectors.toList()); + } +} + +
Java
```java //๋ฐฐ์†ก ์ƒํƒœ ๋ณ€๊ฒฝ @Transactional public void updateDeliveryStatus(OrderDeliveryRequestDto orderDeliveryRequestDto) { List<Integer> orderIds = orderDeliveryRequestDto.getId(); if (CollectionUtils.isEmpty(orderIds)) { throw new IllegalArgumentException("ID list cannot be null or empty."); } for (Integer orderId : orderIds) { Order order = orderRepository.findById(orderId) .orElseThrow(() -> new IllegalArgumentException("Order not found for ID: " + orderId)); // ๋ฐฐ์†ก ์ƒํƒœ๋ฅผ SHIPPED๋กœ ๋ณ€๊ฒฝ order.updateToShipped(); } } ```
@@ -0,0 +1,29 @@ +package com.ll.backend.domain.orderdetail.controller; + +import com.ll.backend.domain.orderdetail.dto.OrderDetailResponseDto; +import com.ll.backend.domain.orderdetail.service.OrderDetailService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequiredArgsConstructor +public class OrderDetailController { + + private final OrderDetailService orderDetailService; + + @GetMapping("/admin/order/{id}") + public ResponseEntity<List<OrderDetailResponseDto>> getOrderDetail(@PathVariable String id){ + List<OrderDetailResponseDto> orderDetail = orderDetailService.getOrderDetail(Integer.parseInt(id)); + if(orderDetail.isEmpty()){ + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + return new ResponseEntity<>(orderDetail, HttpStatus.OK); + } + +}
Java
Integer๋กœ ๋ฐ›์์‹œ๋‹ค.
@@ -0,0 +1,29 @@ +package com.ll.backend.domain.orderdetail.controller; + +import com.ll.backend.domain.orderdetail.dto.OrderDetailResponseDto; +import com.ll.backend.domain.orderdetail.service.OrderDetailService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequiredArgsConstructor +public class OrderDetailController { + + private final OrderDetailService orderDetailService; + + @GetMapping("/admin/order/{id}") + public ResponseEntity<List<OrderDetailResponseDto>> getOrderDetail(@PathVariable String id){ + List<OrderDetailResponseDto> orderDetail = orderDetailService.getOrderDetail(Integer.parseInt(id)); + if(orderDetail.isEmpty()){ + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + return new ResponseEntity<>(orderDetail, HttpStatus.OK); + } + +}
Java
(๋‚˜์ค‘์— ์‹œ๊ฐ„ ๋‚˜๋ฉด ํ™•์ธํ•ด ๋ณด์„ธ์š”~~~~~) - `@ControllerAdvice`, `@ExceptionHandler` ๋ฅผ ๊ฐ™์ด ์‚ฌ์šฉํ•˜๋ฉด, ์ €ํฌ๊ฐ€ ๊ตณ์ด ์ €๋ ‡๊ฒŒ ์‘๋‹ต ์ฝ”๋“œ๋ฅผ ๋ถ„๊ธฐํ•˜์ง€ ์•Š์•„๋„ ์˜ˆ์™ธ์˜ ์ข…๋ฅ˜๋งŒ ๋ณด๊ณ  HttpStatusCode๋ฅผ ์ง€์ •ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,15 @@ +package com.ll.backend.domain.orderdetail.repository; + +import com.ll.backend.domain.order.entity.Order; +import com.ll.backend.domain.orderdetail.entity.OrderDetail; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; + +public interface OrderDetailRepository extends JpaRepository<OrderDetail,Long> { + List<OrderDetail> findByOrder(Order order); + + Long id(Integer id); + + List<OrderDetail> findByOrder_Id(Integer orderId); +}
Java
Google Java Convention/Naver Java Convention ๋ชจ๋‘์—์„œ, ๋ฉ”์„œ๋“œ ์ด๋ฆ„์— ์–ธ๋”์Šค์ฝ”์–ด๋ฅผ ์“ฐ์ง€ ๋ง๋ผ๊ณ  ์ ํ˜€์žˆ์„๊ฑฐ์—์š”. (์ผ๋ฐ˜์ ์œผ๋กœ ํ…Œ์ŠคํŠธ๊ฐ€ ์•„๋‹ˆ๋ผ๋ฉด ๋ฉ”์„œ๋“œ ์ด๋ฆ„์— ์–ธ๋”์Šค์ฝ”์–ด๋ฅผ ์“ฐ์ง€ ์•Š์Šต๋‹ˆ๋‹ค.)
@@ -25,6 +25,7 @@ public class Board { @Column(updatable = false) private LocalDateTime createdAt = LocalDateTime.now(); + @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "userId") private User user;
Java
N+1 ๋ฌธ์ œ๋ฅผ ๊ณ ๋ คํ•ด์•ผํ•ด์„œ ์ˆ˜์ •ํ•ด์•ผํ•จ
@@ -22,18 +22,19 @@ public class BoardService { private final BoardRepository boardRepository; private final UserRepository userRepository; - LocalDateTime now = LocalDateTime.now(); - @Transactional + + @Transactional(readOnly = true) public Page<Board> getBoards(int page, int size) { Pageable pageable = PageRequest.of(page, size); return boardRepository.findAll(pageable); } @Transactional - public void create(BoardDto boardDto) { - final User user = userRepository.findByUsername(boardDto.getUsername()) + public void create(BoardDto boardDto, String identity) { + LocalDateTime now = LocalDateTime.now(); + final User user = userRepository.findByIdentity(identity) .orElseThrow(() -> new RuntimeException("์ผ์น˜ํ•˜๋Š” ์‚ฌ์šฉ์ž๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.")); Board board = Board.builder() @@ -49,12 +50,14 @@ public void create(BoardDto boardDto) { @Transactional public void update(BoardUpdateDto dto) { - final User user = userRepository.findByUsername(dto.getUsername()) - .orElseThrow(() -> new RuntimeException("์ผ์น˜ํ•˜๋Š” ์‚ฌ์šฉ์ž๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.")); - final Board board = boardRepository.findById(dto.getId()) .orElseThrow(() -> new RuntimeException("์ผ์น˜ํ•˜๋Š” ๊ฒŒ์‹œ๋ฌผ์ด ์—†์Šต๋‹ˆ๋‹ค.")); + final String username = board.getUser().getUsername(); + + final User user = userRepository.findByUsername(username) + .orElseThrow(() -> new RuntimeException("์ผ์น˜ํ•˜๋Š” ์‚ฌ์šฉ์ž๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.")); + if(user.getUsername().equals(dto.getUsername())) { board.update(dto.getTitle(), dto.getContent()); boardRepository.save(board); @@ -66,12 +69,16 @@ public void update(BoardUpdateDto dto) { @Transactional public void delete(BoardDeleteDto dto) { - final User user = userRepository.findByUsername(dto.getUsername()) - .orElseThrow(() -> new RuntimeException("์ผ์น˜ํ•˜๋Š” ์‚ฌ์šฉ์ž๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.")); - final Board board = boardRepository.findById(dto.getId()) .orElseThrow(() -> new RuntimeException("์ผ์น˜ํ•˜๋Š” ๊ฒŒ์‹œ๋ฌผ์ด ์—†์Šต๋‹ˆ๋‹ค.")); + final String username = board.getUser().getUsername(); + +// final String userid = board.getUser().getIdentity(); + + final User user = userRepository.findByUsername(username) + .orElseThrow(() -> new RuntimeException("์ผ์น˜ํ•˜๋Š” ์‚ฌ์šฉ์ž๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.")); + if(user.getUsername().equals(dto.getUsername())) { boardRepository.delete(board); }else {
Java
์•„๋ž˜์ฒ˜๋Ÿผ ๋กœ์ง์ด ๋ฐ”๋€Œ์–ด์•ผํ•จ ```java @Transactional public void delete(BoardDeleteDto dto) { // ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง์˜ ๋ฌธ์ œ -> ์ด๋Ÿฐ๊ฑฐ๋ฅผ ๊ณ ๋ฏผํ•˜๋Š”๊ฒŒ ๋ฐฑ์—”๋“œ ๊ฐœ๋ฐœ์ž์˜ ์—ญํ•  // ๊ฒŒ์‹œํŒ์„ ์ฐพ๋Š”๋‹ค. final Board board = boardRepository.findById(dto.getId()) .orElseThrow(() -> new RuntimeException("์ผ์น˜ํ•˜๋Š” ๊ฒŒ์‹œ๋ฌผ์ด ์—†์Šต๋‹ˆ๋‹ค.")); // ๊ฒŒ์‹œํŒ์˜ ์ž‘์„ฑ์ž๋ฅผ ์ฐพ๋Š”๋‹ค. final String username = board.getUser().getUsername(); // ๊ฒŒ์‹œํŒ์˜ ์ž‘์„ฑ์ž์˜ DB ์กฐํšŒ final User user = userRepository.findByUsername(username) .orElseThrow(() -> new RuntimeException("์ผ์น˜ํ•˜๋Š” ์‚ฌ์šฉ์ž๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.")); // ๊ฒŒ์‹œํŒ ์ž‘์„ฑ์ž์˜ DB ์™€ ํ˜„์žฌ ์š”์ฒญํ•œ ์‚ฌ๋žŒ์˜ username ์ด ๊ฐ™์€์ง€ ๋น„๊ต if (user.getUsername().equals(dto.getUsername())) { boardRepository.delete(board); } else { throw new IllegalArgumentException("์ž‘์„ฑ์ž๋งŒ ์ˆ˜์ •ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค."); } } ```
@@ -1,5 +1,22 @@ +import MovieListContainer from './components/MovieListContainer'; +import Header from './components/Header'; +import QueryErrorBoundary from './components/common/QueryResetErrorboundary'; + function App() { - return <div>hi</div>; + return ( + <div style={AppStyle}> + <QueryErrorBoundary> + <Header /> + <main> + <MovieListContainer /> + </main> + </QueryErrorBoundary> + </div> + ); } +const AppStyle = { + paddingBottom: '48px', +}; + export default App;
Unknown
์™€์šฐ ์—๋Ÿฌ๋ฐ”์šด๋”๋ฆฌ๊นŒ์ง€...!๐Ÿ‘๐Ÿป
@@ -0,0 +1,56 @@ +import * as S from './styles'; +import Portal from '../common/Portal'; +import ModalBackground from '../common/ModalBackground'; +import useGetMovieDetail from '../../hooks/useGetMovieDetail'; +import {IMAGE_BASE_URL} from '../../constants/movie'; +import {toOneDecimalPlace} from '../../utils/number'; +import filledStar from '../../assets/star_filled.png'; +import MyRating from '../MyRating'; + +interface DetailModalProps { + selectedMovieId: number; + closeModal: () => void; +} + +const DetailModal = ({selectedMovieId, closeModal}: DetailModalProps) => { + const {data} = useGetMovieDetail(selectedMovieId); + + const {poster_path, vote_average, title, overview, genres} = data; + + return ( + <Portal> + <ModalBackground closeModal={closeModal}> + <S.ModalContainer> + <S.Header> + <h2>{title}</h2> + <button type="button" onClick={closeModal}> + ๋‹ซ๊ธฐ + </button> + </S.Header> + + <S.Content> + <S.Poster src={`${IMAGE_BASE_URL}${poster_path}`} alt={`${title} ํฌ์Šคํ„ฐ`} /> + + <S.RightContent> + <S.ShortInfo> + <S.Genres>{genres.map(genre => genre.name).join(', ')}</S.Genres> + <S.Rate> + <span>{toOneDecimalPlace(vote_average)}</span> + <img src={filledStar} alt="" /> + </S.Rate> + </S.ShortInfo> + + <S.Overview>{overview}</S.Overview> + + <S.MyRatingWrapper> + <MyRating movieId={selectedMovieId} /> + </S.MyRatingWrapper> + </S.RightContent> + </S.Content> + </S.ModalContainer> + </ModalBackground> + </Portal> + ); +}; + +export default DetailModal;
Unknown
๋ชจ๋‹ฌ ๋ฐ์ดํ„ฐ๋ฅผ ๋ถˆ๋Ÿฌ์˜ค๊ณ  ์žˆ๋Š” ์ค‘์—๋Š” ๋ชจ๋‹ฌ์ด ์•ˆ๋„์›Œ์ง€๋”๋ผ๊ตฌ์š”. ๊ทธ๋ž˜์„œ Movie๋ฅผ ํด๋ฆญํ–ˆ์„ ๋•Œ ์•ฝ๊ฐ„์˜ ์ง€์—ฐ์‹œ๊ฐ„ ํ›„์— ๋ชจ๋‹ฌ์ด ๋„์›Œ์ง€๊ณ  ์žˆ๊ตฌ์š”! ์ด ๋ถ€๋ถ„์—์„œ ์‚ฌ์šฉ์„ฑ์„ ์œ„ํ•ด ์Šค์ผˆ๋ ˆํ†ค์ด๋‚˜ Suspense๊ฐ™์€ UI๋ฅผ ๋„ฃ๋Š” ๊ฒƒ์€ ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,81 @@ +import {BASE_URL, POPULAR_MOVIE_URL, SEARCH_URL} from '../constants/movie'; +import {MovieDetail, MovieList} from '../types/movie'; +import {createApiErrorMessage} from '../utils/error'; + +export const getMovieList = async ({pageParam = 1}: {pageParam?: number}) => { + const params = { + api_key: import.meta.env.VITE_TMDB_TOKEN, + language: 'ko-KR', + page: String(pageParam), + }; + const endpoint = `${POPULAR_MOVIE_URL}?${new URLSearchParams(params).toString()}`; + + const response = await fetch(endpoint, { + method: 'GET', + headers: { + Authorization: `Bearer ${import.meta.env.VITE_TMDB_TOKEN}`, + accept: 'application/json', + }, + }); + + if (!response.ok) { + throw new Error(createApiErrorMessage(response.status)); + } + + const data = await response.json(); + return data as MovieList; +}; + +interface GetSearchedMovieListParam { + pageParam?: number; + title: string; +} + +export const getSearchedMovieList = async ({pageParam = 1, title}: GetSearchedMovieListParam) => { + const params = { + api_key: import.meta.env.VITE_TMDB_TOKEN, + query: title, // ๊ฒ€์ƒ‰์–ด + language: 'ko-KR', + page: String(pageParam), + }; + + const endpoint = `${SEARCH_URL}?${new URLSearchParams(params).toString()}`; + + const response = await fetch(endpoint, { + method: 'GET', + headers: { + Authorization: `Bearer ${import.meta.env.VITE_TMDB_TOKEN}`, + accept: 'application/json', + }, + }); + + if (!response.ok) { + throw new Error(createApiErrorMessage(response.status)); + } + + const data = await response.json(); + return data as MovieList; +}; + +export const getMovieDetail = async (movieId: number) => { + const params = { + api_key: import.meta.env.VITE_TMDB_TOKEN, + language: 'ko-KR', + }; + const endpoint = `${BASE_URL}/movie/${movieId}?${new URLSearchParams(params).toString()}`; + + const response = await fetch(endpoint, { + method: 'GET', + headers: { + Authorization: `Bearer ${import.meta.env.VITE_TMDB_TOKEN}`, + accept: 'application/json', + }, + }); + + if (!response.ok) { + throw new Error(createApiErrorMessage(response.status)); + } + + const data = await response.json(); + return data as MovieDetail; +};
TypeScript
์—ฌ๊ธฐ์„œ๋Š” as๋กœ ๋ฆฌํ„ดํ•˜๊ณ  ์žˆ๊ตฐ์š”! ํ˜น์‹œ ํƒ€์ž… ๋‹จ์–ธ์„ ํ•˜๋Š” ๊ฒฝ์šฐ๋„ `getMovieDetail` ํ•จ์ˆ˜์˜ ๋ฆฌํ„ด๊ฐ’ ํƒ€์ž… ์ถ”๋ก ์ด ๋˜๋‚˜์š”??(์ž˜ ๋ชฐ๋ผ์„œ...) ์‚ฌ์‹ค ์„œ๋ฒ„๋กœ๋ถ€ํ„ฐ ์˜ค๋Š” ๋ฐ์ดํ„ฐ ํƒ€์ž…์„ Typescript๊ฐ€ ์ถ”๋ก ํ•  ์ˆ˜๋Š” ์—†์–ด์„œ `as`๋„ ์ƒ๊ด€์—†์„ ๊ฒƒ ๊ฐ™์ง€๋งŒ ๊ถŒ์žฅ๋˜๋Š” ํ˜•์‹์€ ๋ช…์‹œ์ ์ธ ๋ฐ˜ํ™˜ ํƒ€์ž… ์„ ์–ธ์„ ํ•˜๋Š” ๋ฐฉ๋ฒ• ๊ฐ™์•„์„œ์š”! ์˜ฌ๋ฆฌ๋Š” as์™€ ๋ฐ˜ํ™˜ ํƒ€์ž… ์„ ์–ธ ์ค‘ ์–ด๋–ค ๋ฐฉ๋ฒ•์ด ๋” ๋‚ซ๋‹ค๊ณ  ์ƒ๊ฐํ•˜๋Š”์ง€ ๊ถ๊ธˆํ•ด์š”!
@@ -0,0 +1,56 @@ +import * as S from './styles'; +import Portal from '../common/Portal'; +import ModalBackground from '../common/ModalBackground'; +import useGetMovieDetail from '../../hooks/useGetMovieDetail'; +import {IMAGE_BASE_URL} from '../../constants/movie'; +import {toOneDecimalPlace} from '../../utils/number'; +import filledStar from '../../assets/star_filled.png'; +import MyRating from '../MyRating'; + +interface DetailModalProps { + selectedMovieId: number; + closeModal: () => void; +} + +const DetailModal = ({selectedMovieId, closeModal}: DetailModalProps) => { + const {data} = useGetMovieDetail(selectedMovieId); + + const {poster_path, vote_average, title, overview, genres} = data; + + return ( + <Portal> + <ModalBackground closeModal={closeModal}> + <S.ModalContainer> + <S.Header> + <h2>{title}</h2> + <button type="button" onClick={closeModal}> + ๋‹ซ๊ธฐ + </button> + </S.Header> + + <S.Content> + <S.Poster src={`${IMAGE_BASE_URL}${poster_path}`} alt={`${title} ํฌ์Šคํ„ฐ`} /> + + <S.RightContent> + <S.ShortInfo> + <S.Genres>{genres.map(genre => genre.name).join(', ')}</S.Genres> + <S.Rate> + <span>{toOneDecimalPlace(vote_average)}</span> + <img src={filledStar} alt="" /> + </S.Rate> + </S.ShortInfo> + + <S.Overview>{overview}</S.Overview> + + <S.MyRatingWrapper> + <MyRating movieId={selectedMovieId} /> + </S.MyRatingWrapper> + </S.RightContent> + </S.Content> + </S.ModalContainer> + </ModalBackground> + </Portal> + ); +}; + +export default DetailModal;
Unknown
selectedMovieId๋„ props๊ฐ€ ๊ฝค ๊นŠ์ด ์žˆ์–ด์„œ ์ „์—ญ์œผ๋กœ ๊ด€๋ฆฌํ•ด๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์€๋ฐ ์–ด๋–จ๊นŒ์š”??
@@ -0,0 +1,66 @@ +import {useAtomValue} from 'jotai'; +import useGetList from '../../hooks/useGetList'; +import useInfiniteScroll from '../../hooks/useInfiniteScroll'; +import * as S from './styles'; +import MovieItem from '../MovieItem'; +import SkeletonMovieList from '../skeleton/MovieList'; +import {searchTextAtom} from '../../jotai/atoms'; + +interface MovieListProps { + openModal: (movieId: number) => void; +} + +const MovieList = ({openModal}: MovieListProps) => { + const {movies, hasNextPage, fetchNextPage, isLoading, isFetchingNextPage} = useGetList(); + const searchText = useAtomValue(searchTextAtom); + + const lastElementRef = useInfiniteScroll({ + fetchNextPage, + isLoading, + isLastPage: !hasNextPage, + }); + + const handleItemClick = (event: React.MouseEvent<HTMLUListElement>) => { + event.preventDefault(); + + const listItem = (event.target as HTMLElement).closest('li'); + if (!listItem) return; + + const id = Number(listItem.id); + const selectedItem = movies.find(item => item.id === id); + + if (selectedItem) openModal(id); + }; + + return ( + <S.MovieList onClick={handleItemClick}> + {isLoading ? ( + <SkeletonMovieList /> + ) : ( + movies.map((movie, index) => { + const isLastMovie = index === movies.length - 1; + + return ( + <div + key={movie.id} + ref={isLastMovie ? lastElementRef : null} // ๋งˆ์ง€๋ง‰ ์š”์†Œ์— ref ์—ฐ๊ฒฐ + > + <MovieItem + key={movie.id} + id={movie.id} + title={movie.title} + poster_path={movie.poster_path} + vote_average={movie.vote_average} + /> + </div> + ); + }) + )} + {isFetchingNextPage && <SkeletonMovieList />} + + {searchText && movies.length === 0 && <S.Message>๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.</S.Message>} + </S.MovieList> + ); +}; + +export default MovieList;
Unknown
๋ฐ์ดํ„ฐ ํ˜•์‹ ์ฒ˜๋ฆฌ๋ฅผ MovieList์—์„œ ํ•˜๊ณ  ์žˆ๊ตฐ์š”! ์ œ ์ƒ๊ฐ์—๋Š” ์—ญํ• ์— ๋”ฐ๋ผ useGetList์—์„œ ๋‹ด๋‹นํ•  ์ˆ˜๋„ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,66 @@ +import {useAtomValue} from 'jotai'; +import useGetList from '../../hooks/useGetList'; +import useInfiniteScroll from '../../hooks/useInfiniteScroll'; +import * as S from './styles'; +import MovieItem from '../MovieItem'; +import SkeletonMovieList from '../skeleton/MovieList'; +import {searchTextAtom} from '../../jotai/atoms'; + +interface MovieListProps { + openModal: (movieId: number) => void; +} + +const MovieList = ({openModal}: MovieListProps) => { + const {movies, hasNextPage, fetchNextPage, isLoading, isFetchingNextPage} = useGetList(); + const searchText = useAtomValue(searchTextAtom); + + const lastElementRef = useInfiniteScroll({ + fetchNextPage, + isLoading, + isLastPage: !hasNextPage, + }); + + const handleItemClick = (event: React.MouseEvent<HTMLUListElement>) => { + event.preventDefault(); + + const listItem = (event.target as HTMLElement).closest('li'); + if (!listItem) return; + + const id = Number(listItem.id); + const selectedItem = movies.find(item => item.id === id); + + if (selectedItem) openModal(id); + }; + + return ( + <S.MovieList onClick={handleItemClick}> + {isLoading ? ( + <SkeletonMovieList /> + ) : ( + movies.map((movie, index) => { + const isLastMovie = index === movies.length - 1; + + return ( + <div + key={movie.id} + ref={isLastMovie ? lastElementRef : null} // ๋งˆ์ง€๋ง‰ ์š”์†Œ์— ref ์—ฐ๊ฒฐ + > + <MovieItem + key={movie.id} + id={movie.id} + title={movie.title} + poster_path={movie.poster_path} + vote_average={movie.vote_average} + /> + </div> + ); + }) + )} + {isFetchingNextPage && <SkeletonMovieList />} + + {searchText && movies.length === 0 && <S.Message>๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.</S.Message>} + </S.MovieList> + ); +}; + +export default MovieList;
Unknown
์˜ค ์ด๋ ‡๊ฒŒ ๋ฌดํ•œ ์Šคํฌ๋กค ๋กœ์ง์„ ๋ถ„๋ฆฌํ•˜๋‹ˆ ์ •๋ง ๊น”๋”ํ•˜๋„ค์š”๐Ÿ‘๐Ÿป
@@ -0,0 +1,66 @@ +import {useAtomValue} from 'jotai'; +import useGetList from '../../hooks/useGetList'; +import useInfiniteScroll from '../../hooks/useInfiniteScroll'; +import * as S from './styles'; +import MovieItem from '../MovieItem'; +import SkeletonMovieList from '../skeleton/MovieList'; +import {searchTextAtom} from '../../jotai/atoms'; + +interface MovieListProps { + openModal: (movieId: number) => void; +} + +const MovieList = ({openModal}: MovieListProps) => { + const {movies, hasNextPage, fetchNextPage, isLoading, isFetchingNextPage} = useGetList(); + const searchText = useAtomValue(searchTextAtom); + + const lastElementRef = useInfiniteScroll({ + fetchNextPage, + isLoading, + isLastPage: !hasNextPage, + }); + + const handleItemClick = (event: React.MouseEvent<HTMLUListElement>) => { + event.preventDefault(); + + const listItem = (event.target as HTMLElement).closest('li'); + if (!listItem) return; + + const id = Number(listItem.id); + const selectedItem = movies.find(item => item.id === id); + + if (selectedItem) openModal(id); + }; + + return ( + <S.MovieList onClick={handleItemClick}> + {isLoading ? ( + <SkeletonMovieList /> + ) : ( + movies.map((movie, index) => { + const isLastMovie = index === movies.length - 1; + + return ( + <div + key={movie.id} + ref={isLastMovie ? lastElementRef : null} // ๋งˆ์ง€๋ง‰ ์š”์†Œ์— ref ์—ฐ๊ฒฐ + > + <MovieItem + key={movie.id} + id={movie.id} + title={movie.title} + poster_path={movie.poster_path} + vote_average={movie.vote_average} + /> + </div> + ); + }) + )} + {isFetchingNextPage && <SkeletonMovieList />} + + {searchText && movies.length === 0 && <S.Message>๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.</S.Message>} + </S.MovieList> + ); +}; + +export default MovieList;
Unknown
closest๋ฅผ ์‚ฌ์šฉํ•œ ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?!
@@ -0,0 +1,66 @@ +import {useAtomValue} from 'jotai'; +import useGetList from '../../hooks/useGetList'; +import useInfiniteScroll from '../../hooks/useInfiniteScroll'; +import * as S from './styles'; +import MovieItem from '../MovieItem'; +import SkeletonMovieList from '../skeleton/MovieList'; +import {searchTextAtom} from '../../jotai/atoms'; + +interface MovieListProps { + openModal: (movieId: number) => void; +} + +const MovieList = ({openModal}: MovieListProps) => { + const {movies, hasNextPage, fetchNextPage, isLoading, isFetchingNextPage} = useGetList(); + const searchText = useAtomValue(searchTextAtom); + + const lastElementRef = useInfiniteScroll({ + fetchNextPage, + isLoading, + isLastPage: !hasNextPage, + }); + + const handleItemClick = (event: React.MouseEvent<HTMLUListElement>) => { + event.preventDefault(); + + const listItem = (event.target as HTMLElement).closest('li'); + if (!listItem) return; + + const id = Number(listItem.id); + const selectedItem = movies.find(item => item.id === id); + + if (selectedItem) openModal(id); + }; + + return ( + <S.MovieList onClick={handleItemClick}> + {isLoading ? ( + <SkeletonMovieList /> + ) : ( + movies.map((movie, index) => { + const isLastMovie = index === movies.length - 1; + + return ( + <div + key={movie.id} + ref={isLastMovie ? lastElementRef : null} // ๋งˆ์ง€๋ง‰ ์š”์†Œ์— ref ์—ฐ๊ฒฐ + > + <MovieItem + key={movie.id} + id={movie.id} + title={movie.title} + poster_path={movie.poster_path} + vote_average={movie.vote_average} + /> + </div> + ); + }) + )} + {isFetchingNextPage && <SkeletonMovieList />} + + {searchText && movies.length === 0 && <S.Message>๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.</S.Message>} + </S.MovieList> + ); +}; + +export default MovieList;
Unknown
์˜คํ˜ธ ์ด๋ ‡๊ฒŒ ๋งˆ์ง€๋ง‰ ์š”์†Œ์— ref๋ฅผ ๋„ฃ๋Š” ๋ฐฉ๋ฒ•๋„ ์žˆ๊ตฐ์š”..! ์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ํ™•์‹คํžˆ ๋งˆ์ง€๋ง‰ ์š”์†Œ๊นŒ์ง€ ๋„๋‹ฌํ–ˆ์„ ๋•Œ ์ƒˆ๋กœ์šด API๋ฅผ ํ˜ธ์ถœํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”
@@ -0,0 +1,66 @@ +import {useAtomValue} from 'jotai'; +import useGetList from '../../hooks/useGetList'; +import useInfiniteScroll from '../../hooks/useInfiniteScroll'; +import * as S from './styles'; +import MovieItem from '../MovieItem'; +import SkeletonMovieList from '../skeleton/MovieList'; +import {searchTextAtom} from '../../jotai/atoms'; + +interface MovieListProps { + openModal: (movieId: number) => void; +} + +const MovieList = ({openModal}: MovieListProps) => { + const {movies, hasNextPage, fetchNextPage, isLoading, isFetchingNextPage} = useGetList(); + const searchText = useAtomValue(searchTextAtom); + + const lastElementRef = useInfiniteScroll({ + fetchNextPage, + isLoading, + isLastPage: !hasNextPage, + }); + + const handleItemClick = (event: React.MouseEvent<HTMLUListElement>) => { + event.preventDefault(); + + const listItem = (event.target as HTMLElement).closest('li'); + if (!listItem) return; + + const id = Number(listItem.id); + const selectedItem = movies.find(item => item.id === id); + + if (selectedItem) openModal(id); + }; + + return ( + <S.MovieList onClick={handleItemClick}> + {isLoading ? ( + <SkeletonMovieList /> + ) : ( + movies.map((movie, index) => { + const isLastMovie = index === movies.length - 1; + + return ( + <div + key={movie.id} + ref={isLastMovie ? lastElementRef : null} // ๋งˆ์ง€๋ง‰ ์š”์†Œ์— ref ์—ฐ๊ฒฐ + > + <MovieItem + key={movie.id} + id={movie.id} + title={movie.title} + poster_path={movie.poster_path} + vote_average={movie.vote_average} + /> + </div> + ); + }) + )} + {isFetchingNextPage && <SkeletonMovieList />} + + {searchText && movies.length === 0 && <S.Message>๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.</S.Message>} + </S.MovieList> + ); +}; + +export default MovieList;
Unknown
์ด ๋ถ€๋ถ„์„ ์ƒˆ๋กœ์šด ์ปดํฌ๋„ŒํŠธ๋กœ ๋ถ„๋ฆฌํ•ด๋ณด๋Š” ๊ฑด ์–ด๋–จ๊นŒ์š”? ref๋ฅผ MovieItem์— ์ง์ ‘ ๋„˜๊ฒจ์ฃผ๋Š” ๋ฐฉ๋ฒ•์œผ๋กœ๋„ ํ•ด๋ณผ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”
@@ -0,0 +1,24 @@ +import {IMAGE_BASE_URL} from '../../constants/movie'; +import filledStar from '../../assets/star_filled.png'; +import {Movie} from '../../types/movie'; +import * as S from './styles'; +import {toOneDecimalPlace} from '../../utils/number'; + +export type MovieItemProps = Pick<Movie, 'id' | 'title' | 'poster_path' | 'vote_average'>; + +const MovieItem = ({id, title, poster_path, vote_average}: MovieItemProps) => ( + <S.MovieItem id={String(id)}> + <a href="#"> + <S.MovieContent> + <S.Thumbnail src={`${IMAGE_BASE_URL}${poster_path}`} loading="lazy" alt={`${title}-ํฌ์Šคํ„ฐ`} /> + <S.Title>{title}</S.Title> + <S.ScoreContainer> + <S.Score>{toOneDecimalPlace(vote_average)}</S.Score> + <S.StarImg src={filledStar} alt="" /> + </S.ScoreContainer> + </S.MovieContent> + </a> + </S.MovieItem> +); + +export default MovieItem;
Unknown
์˜ค Pick์„ ์‚ฌ์šฉํ–ˆ๊ตฐ์š”! ์˜ฌ๋ฆฌ๋Š” Pick๊ณผ Omit์˜ ์‚ฌ์šฉ ๊ธฐ์ค€์ด ์žˆ์„๊นŒ์š”? ์ €๋Š” Omit์„ ์ฃผ๋กœ ์‚ฌ์šฉํ•˜๋Š” ํŽธ์ด๋ผ์„œ์š”! ๊ทธ๋ฆฌ๊ณ  MovieItemProps๋Š” ๋‹ค๋ฅธ ๊ณณ์—์„œ ์‚ฌ์šฉ๋˜์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์— export๊ฐ€ ์—†์–ด๋„ ๋  ๊ฒƒ ๊ฐ™์Šด๋‹ค!
@@ -0,0 +1,24 @@ +import {IMAGE_BASE_URL} from '../../constants/movie'; +import filledStar from '../../assets/star_filled.png'; +import {Movie} from '../../types/movie'; +import * as S from './styles'; +import {toOneDecimalPlace} from '../../utils/number'; + +export type MovieItemProps = Pick<Movie, 'id' | 'title' | 'poster_path' | 'vote_average'>; + +const MovieItem = ({id, title, poster_path, vote_average}: MovieItemProps) => ( + <S.MovieItem id={String(id)}> + <a href="#"> + <S.MovieContent> + <S.Thumbnail src={`${IMAGE_BASE_URL}${poster_path}`} loading="lazy" alt={`${title}-ํฌ์Šคํ„ฐ`} /> + <S.Title>{title}</S.Title> + <S.ScoreContainer> + <S.Score>{toOneDecimalPlace(vote_average)}</S.Score> + <S.StarImg src={filledStar} alt="" /> + </S.ScoreContainer> + </S.MovieContent> + </a> + </S.MovieItem> +); + +export default MovieItem;
Unknown
id๋Š” liํƒœ๊ทธ์˜ id์ธ ๊ฑธ๊นŒ์š”? idํƒœ๊ทธ๋ฅผ ๋„ฃ์–ด์ค€ ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ด์š”!
@@ -0,0 +1,66 @@ +import {useAtomValue} from 'jotai'; +import useGetList from '../../hooks/useGetList'; +import useInfiniteScroll from '../../hooks/useInfiniteScroll'; +import * as S from './styles'; +import MovieItem from '../MovieItem'; +import SkeletonMovieList from '../skeleton/MovieList'; +import {searchTextAtom} from '../../jotai/atoms'; + +interface MovieListProps { + openModal: (movieId: number) => void; +} + +const MovieList = ({openModal}: MovieListProps) => { + const {movies, hasNextPage, fetchNextPage, isLoading, isFetchingNextPage} = useGetList(); + const searchText = useAtomValue(searchTextAtom); + + const lastElementRef = useInfiniteScroll({ + fetchNextPage, + isLoading, + isLastPage: !hasNextPage, + }); + + const handleItemClick = (event: React.MouseEvent<HTMLUListElement>) => { + event.preventDefault(); + + const listItem = (event.target as HTMLElement).closest('li'); + if (!listItem) return; + + const id = Number(listItem.id); + const selectedItem = movies.find(item => item.id === id); + + if (selectedItem) openModal(id); + }; + + return ( + <S.MovieList onClick={handleItemClick}> + {isLoading ? ( + <SkeletonMovieList /> + ) : ( + movies.map((movie, index) => { + const isLastMovie = index === movies.length - 1; + + return ( + <div + key={movie.id} + ref={isLastMovie ? lastElementRef : null} // ๋งˆ์ง€๋ง‰ ์š”์†Œ์— ref ์—ฐ๊ฒฐ + > + <MovieItem + key={movie.id} + id={movie.id} + title={movie.title} + poster_path={movie.poster_path} + vote_average={movie.vote_average} + /> + </div> + ); + }) + )} + {isFetchingNextPage && <SkeletonMovieList />} + + {searchText && movies.length === 0 && <S.Message>๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.</S.Message>} + </S.MovieList> + ); +}; + +export default MovieList;
Unknown
infiniteQuery์—์„œ ์ƒˆ๋กœ์šด ๋ฐฐ์—ด์„ ๊ธฐ์กด ๋ฐฐ์—ด์— ๋„ฃ์–ด์ฃผ๊ณ  ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ์ด ๋ถ€๋ถ„์€ ์—†์–ด๋„ ๋  ๊ฒƒ ๊ฐ™์•„์š”~!
@@ -0,0 +1,30 @@ +import styled from '@emotion/styled'; +import searchImg from '../../assets/search_button.png'; + +export const Search = styled.section` + display: flex; + height: 3rem; + + background: #fff; + padding: 8px; + border-radius: 4px; + + button { + width: 14px; + border: 0; + text-indent: -1000rem; + background: url(${searchImg}) no-repeat center center; + background-size: contain; + } +`; + +export const SearchInput = styled.input` + font-size: 13px; + + border: 0; + + &:focus { + outline: none; + border: none; + } +`;
TypeScript
form์œผ๋กœ๋„ ์ฒ˜๋ฆฌํ•ด๋ณผ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์€๋ฐ ์˜ฌ๋ฆฌ๋Š” ์–ด๋–ค ๋ฐฉ๋ฒ•์ด ๋” ํŽธํ• ๊นŒ์š”?
@@ -0,0 +1,17 @@ +import React, {useRef} from 'react'; + +import * as S from './styles.ts'; +import useModalClose from '../../../hooks/useModalClose.ts'; + +interface ModalBackgroundProps { + closeModal: (() => void) | null; + children?: React.ReactNode; +} + +const ModalBackground = ({children, closeModal}: ModalBackgroundProps) => { + const modalBackgroundRef = useRef<HTMLDivElement>(null); + useModalClose({closeModal, modalBackgroundRef}); + + return <S.ModalBackground ref={modalBackgroundRef}>{children}</S.ModalBackground>; +}; +export default ModalBackground;
Unknown
React.FC๋ฅผ ์‚ฌ์šฉํ•œ ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?!
@@ -0,0 +1,81 @@ +import {BASE_URL, POPULAR_MOVIE_URL, SEARCH_URL} from '../constants/movie'; +import {MovieDetail, MovieList} from '../types/movie'; +import {createApiErrorMessage} from '../utils/error'; + +export const getMovieList = async ({pageParam = 1}: {pageParam?: number}) => { + const params = { + api_key: import.meta.env.VITE_TMDB_TOKEN, + language: 'ko-KR', + page: String(pageParam), + }; + const endpoint = `${POPULAR_MOVIE_URL}?${new URLSearchParams(params).toString()}`; + + const response = await fetch(endpoint, { + method: 'GET', + headers: { + Authorization: `Bearer ${import.meta.env.VITE_TMDB_TOKEN}`, + accept: 'application/json', + }, + }); + + if (!response.ok) { + throw new Error(createApiErrorMessage(response.status)); + } + + const data = await response.json(); + return data as MovieList; +}; + +interface GetSearchedMovieListParam { + pageParam?: number; + title: string; +} + +export const getSearchedMovieList = async ({pageParam = 1, title}: GetSearchedMovieListParam) => { + const params = { + api_key: import.meta.env.VITE_TMDB_TOKEN, + query: title, // ๊ฒ€์ƒ‰์–ด + language: 'ko-KR', + page: String(pageParam), + }; + + const endpoint = `${SEARCH_URL}?${new URLSearchParams(params).toString()}`; + + const response = await fetch(endpoint, { + method: 'GET', + headers: { + Authorization: `Bearer ${import.meta.env.VITE_TMDB_TOKEN}`, + accept: 'application/json', + }, + }); + + if (!response.ok) { + throw new Error(createApiErrorMessage(response.status)); + } + + const data = await response.json(); + return data as MovieList; +}; + +export const getMovieDetail = async (movieId: number) => { + const params = { + api_key: import.meta.env.VITE_TMDB_TOKEN, + language: 'ko-KR', + }; + const endpoint = `${BASE_URL}/movie/${movieId}?${new URLSearchParams(params).toString()}`; + + const response = await fetch(endpoint, { + method: 'GET', + headers: { + Authorization: `Bearer ${import.meta.env.VITE_TMDB_TOKEN}`, + accept: 'application/json', + }, + }); + + if (!response.ok) { + throw new Error(createApiErrorMessage(response.status)); + } + + const data = await response.json(); + return data as MovieDetail; +};
TypeScript
์„œ๋ฒ„์—์„œ ๋ฐ์ดํ„ฐ๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ์ง€์—ฐ ์‹œ๊ฐ„์ด ์žˆ๊ธฐ ๋•Œ๋ฌธ์— delay๋ฅผ ๊ฑธ์ง€ ์•Š์•„๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”! ์ €๋Š” ๊ตฌํ˜„ํ•  ๋•Œ ๋„คํŠธ์›Œํฌ ์†๋„๋‚˜ performance์—์„œ CPU๋ฅผ ์ œ์–ดํ•˜๋ฉด์„œ ํ…Œ์ŠคํŠธํ–ˆ๋‹ต๋‹ˆ๋‹ค๐Ÿ˜Š
@@ -0,0 +1,59 @@ +import React, {Component, ReactNode} from 'react'; + +import {TOAST_ERROR} from '../../../constants/error'; + +export interface FallbackProps { + error: Error; + resetErrorBoundary: () => void; +} + +interface ErrorBoundaryProps { + fallback: React.ComponentType<FallbackProps>; + children: ReactNode; + resetQueryError?: () => void; +} + +interface ErrorBoundaryState { + hasError: boolean; + error: Error | null; +} + +class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> { + constructor(props: ErrorBoundaryProps) { + super(props); + this.state = {hasError: false, error: null}; + } + + static getDerivedStateFromError(error: Error): ErrorBoundaryState { + // ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•˜๋ฉด ์ƒํƒœ๋ฅผ ์—…๋ฐ์ดํŠธํ•˜์—ฌ fallback์„ ํ‘œ์‹œ + return {hasError: true, error}; + } + + componentDidCatch(error: Error, errorInfo: React.ErrorInfo) { + // ์—๋Ÿฌ๋ฅผ ๋กœ๊น… + console.error('ErrorBoundary caught an error', error, errorInfo); + } + + resetErrorBoundary = () => { + const {resetQueryError} = this.props; + if (resetQueryError) resetQueryError(); + this.setState({hasError: false, error: null}); + }; + + render() { + const {hasError, error} = this.state; + const {children, fallback: FallbackComponent} = this.props; + + // ์—๋Ÿฌ ๋ฉ”์„ธ์ง€์— TOAST_ERROR ํฌํ•จํ•˜๋ฉด fallback ๋Œ€์ƒ์—์„œ ์ œ์™ธ + const isHandleError = !error?.message.includes(TOAST_ERROR); + + // ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ์„ ๋•Œ fallback ์ปดํฌ๋„ŒํŠธ๋กœ ๋Œ€์ฒด + if (hasError && error && isHandleError) { + return <FallbackComponent error={error} resetErrorBoundary={this.resetErrorBoundary} />; + } + + return children; + } +} + +export default ErrorBoundary;
Unknown
์˜คํ™ ํ† ์ŠคํŠธ ๊ตฌํ˜„๋„ ๊ถ๊ธˆํ•ด์ง€๋„ค์š”๐Ÿคฉ ๊ธฐ๋Œ€ํ•ด๋ด๋„....์ข‹์„๊นŒ์š”....?ใ…‹ใ…‹ใ…‹ใ…‹ใ…‹ใ…‹
@@ -0,0 +1,66 @@ +import {useAtomValue} from 'jotai'; +import useGetList from '../../hooks/useGetList'; +import useInfiniteScroll from '../../hooks/useInfiniteScroll'; +import * as S from './styles'; +import MovieItem from '../MovieItem'; +import SkeletonMovieList from '../skeleton/MovieList'; +import {searchTextAtom} from '../../jotai/atoms'; + +interface MovieListProps { + openModal: (movieId: number) => void; +} + +const MovieList = ({openModal}: MovieListProps) => { + const {movies, hasNextPage, fetchNextPage, isLoading, isFetchingNextPage} = useGetList(); + const searchText = useAtomValue(searchTextAtom); + + const lastElementRef = useInfiniteScroll({ + fetchNextPage, + isLoading, + isLastPage: !hasNextPage, + }); + + const handleItemClick = (event: React.MouseEvent<HTMLUListElement>) => { + event.preventDefault(); + + const listItem = (event.target as HTMLElement).closest('li'); + if (!listItem) return; + + const id = Number(listItem.id); + const selectedItem = movies.find(item => item.id === id); + + if (selectedItem) openModal(id); + }; + + return ( + <S.MovieList onClick={handleItemClick}> + {isLoading ? ( + <SkeletonMovieList /> + ) : ( + movies.map((movie, index) => { + const isLastMovie = index === movies.length - 1; + + return ( + <div + key={movie.id} + ref={isLastMovie ? lastElementRef : null} // ๋งˆ์ง€๋ง‰ ์š”์†Œ์— ref ์—ฐ๊ฒฐ + > + <MovieItem + key={movie.id} + id={movie.id} + title={movie.title} + poster_path={movie.poster_path} + vote_average={movie.vote_average} + /> + </div> + ); + }) + )} + {isFetchingNextPage && <SkeletonMovieList />} + + {searchText && movies.length === 0 && <S.Message>๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.</S.Message>} + </S.MovieList> + ); +}; + +export default MovieList;
Unknown
์•— ์ด ๋ถ€๋ถ„๋•Œ๋ฌธ์— ์˜ํ™”๊ฐ€ 2๋ฒˆ ๋ณด์˜€๋˜ ๊ฑฐ๋„ค์š”๐Ÿ˜‚ ๋•๋ถ„์— ์•Œ์•„์ฐจ๋ ธ์–ด์š”!
@@ -1,5 +1,22 @@ +import MovieListContainer from './components/MovieListContainer'; +import Header from './components/Header'; +import QueryErrorBoundary from './components/common/QueryResetErrorboundary'; + function App() { - return <div>hi</div>; + return ( + <div style={AppStyle}> + <QueryErrorBoundary> + <Header /> + <main> + <MovieListContainer /> + </main> + </QueryErrorBoundary> + </div> + ); } +const AppStyle = { + paddingBottom: '48px', +}; + export default App;
Unknown
์‚ฌ์‹ค ์žˆ๋Š” ์ฝ”๋“œ๋ฅผ ๊ฐ€์ ธ์™”์Šต๋‹ˆ๋‹คใ…‹ใ…‹ใ…‹ใ…‹
@@ -0,0 +1,56 @@ +import * as S from './styles'; +import Portal from '../common/Portal'; +import ModalBackground from '../common/ModalBackground'; +import useGetMovieDetail from '../../hooks/useGetMovieDetail'; +import {IMAGE_BASE_URL} from '../../constants/movie'; +import {toOneDecimalPlace} from '../../utils/number'; +import filledStar from '../../assets/star_filled.png'; +import MyRating from '../MyRating'; + +interface DetailModalProps { + selectedMovieId: number; + closeModal: () => void; +} + +const DetailModal = ({selectedMovieId, closeModal}: DetailModalProps) => { + const {data} = useGetMovieDetail(selectedMovieId); + + const {poster_path, vote_average, title, overview, genres} = data; + + return ( + <Portal> + <ModalBackground closeModal={closeModal}> + <S.ModalContainer> + <S.Header> + <h2>{title}</h2> + <button type="button" onClick={closeModal}> + ๋‹ซ๊ธฐ + </button> + </S.Header> + + <S.Content> + <S.Poster src={`${IMAGE_BASE_URL}${poster_path}`} alt={`${title} ํฌ์Šคํ„ฐ`} /> + + <S.RightContent> + <S.ShortInfo> + <S.Genres>{genres.map(genre => genre.name).join(', ')}</S.Genres> + <S.Rate> + <span>{toOneDecimalPlace(vote_average)}</span> + <img src={filledStar} alt="" /> + </S.Rate> + </S.ShortInfo> + + <S.Overview>{overview}</S.Overview> + + <S.MyRatingWrapper> + <MyRating movieId={selectedMovieId} /> + </S.MyRatingWrapper> + </S.RightContent> + </S.Content> + </S.ModalContainer> + </ModalBackground> + </Portal> + ); +}; + +export default DetailModal;
Unknown
์‚ฌ์‹ค ์ €๋Š” 1์ดˆ ์–ธ์ €๋ฆฌ์˜ ์งง์€ ๋กœ๋”ฉ ์‹œ๊ฐ„์ด๋ผ๋ฉด ์Šค์ผˆ๋ ˆํ†ค์„ ๊ฑฐ๋Š” ๊ฒŒ ์˜คํžˆ๋ ค ์ •์‹ ์—†๋‹ค๊ณ  ์ƒ๊ฐํ•ด์„œ ์„ ํ˜ธํ•˜์ง€ ์•Š๋Š” ํŽธ์ธ๋ฐ, ๋ชจ๋‹ฌ์€ 1์ดˆ๋Œ€์˜ ๋กœ๋”ฉ์ด์ง€๋งŒ ํ™”๋ฉด ์ „ํ™˜์ด ๋ฐ”๋กœ ์ผ์–ด๋‚  ๊ฒƒ์„ ๊ธฐ๋Œ€ํ•˜๊ณ  ํด๋ฆญํ•˜๋Š” ๊ฑฐ๋‹ˆ๊นŒ ๋ชจ๋‹ฌ์€ ๋ฐ”๋กœ ๋„์šฐ๋˜ ๋กœ๋”ฉ UI๋ฅผ ๋ณด์—ฌ์ฃผ๋Š” ๊ฒŒ ํ›จ์”ฌ ์ž์—ฐ์Šค๋Ÿฌ์šธ ๊ฒƒ ๊ฐ™๋„ค์š”! ๊ฐœ๋ฐœํ•˜๋ฉด์„œ ๋ˆŒ๋ €๋˜ ๊ฒƒ๋งŒ ๊ณ„์† ๋ˆŒ๋Ÿฌ์„œ ๋А๋ฆฐ ์ค„๋„ ๋ชจ๋ฅด๊ณ  ์žˆ์—ˆ๋„ค์š”...ใ…‹ใ…‹ใ…‹ใ…‹ใ…‹
@@ -0,0 +1,81 @@ +import {BASE_URL, POPULAR_MOVIE_URL, SEARCH_URL} from '../constants/movie'; +import {MovieDetail, MovieList} from '../types/movie'; +import {createApiErrorMessage} from '../utils/error'; + +export const getMovieList = async ({pageParam = 1}: {pageParam?: number}) => { + const params = { + api_key: import.meta.env.VITE_TMDB_TOKEN, + language: 'ko-KR', + page: String(pageParam), + }; + const endpoint = `${POPULAR_MOVIE_URL}?${new URLSearchParams(params).toString()}`; + + const response = await fetch(endpoint, { + method: 'GET', + headers: { + Authorization: `Bearer ${import.meta.env.VITE_TMDB_TOKEN}`, + accept: 'application/json', + }, + }); + + if (!response.ok) { + throw new Error(createApiErrorMessage(response.status)); + } + + const data = await response.json(); + return data as MovieList; +}; + +interface GetSearchedMovieListParam { + pageParam?: number; + title: string; +} + +export const getSearchedMovieList = async ({pageParam = 1, title}: GetSearchedMovieListParam) => { + const params = { + api_key: import.meta.env.VITE_TMDB_TOKEN, + query: title, // ๊ฒ€์ƒ‰์–ด + language: 'ko-KR', + page: String(pageParam), + }; + + const endpoint = `${SEARCH_URL}?${new URLSearchParams(params).toString()}`; + + const response = await fetch(endpoint, { + method: 'GET', + headers: { + Authorization: `Bearer ${import.meta.env.VITE_TMDB_TOKEN}`, + accept: 'application/json', + }, + }); + + if (!response.ok) { + throw new Error(createApiErrorMessage(response.status)); + } + + const data = await response.json(); + return data as MovieList; +}; + +export const getMovieDetail = async (movieId: number) => { + const params = { + api_key: import.meta.env.VITE_TMDB_TOKEN, + language: 'ko-KR', + }; + const endpoint = `${BASE_URL}/movie/${movieId}?${new URLSearchParams(params).toString()}`; + + const response = await fetch(endpoint, { + method: 'GET', + headers: { + Authorization: `Bearer ${import.meta.env.VITE_TMDB_TOKEN}`, + accept: 'application/json', + }, + }); + + if (!response.ok) { + throw new Error(createApiErrorMessage(response.status)); + } + + const data = await response.json(); + return data as MovieDetail; +};
TypeScript
์ด ๋ถ€๋ถ„์€ ํ”„๋กœ์ ํŠธ ํ•  ๋•Œ ๊ณ„์† ์จ์™€์„œ ๊ทธ๋Ÿฐ๊ฐ€ ๋ณ„ ์ƒ๊ฐ ์—†์ด ์ผ์–ด์š”...ใ…Ž (ํฐ ๋ฌธ์ œ๊ฐ€ ์žˆ์—ˆ๋‹ค๋ฉด ๋ˆ„๊ตฐ๊ฐ€ ์ง€์ ํ•ด์คฌ๊ฒ ์ง€ ํ•˜๋Š” ์•ˆ์ผํ•จ) ๋‹น์žฅ ๋“œ๋Š” ์ƒ๊ฐ์€ ์ผ๋ฐ˜์ ์ธ ๊ฒฝ์šฐ์—๋Š” ๋‹จ์–ธ์„ ํ•ด๋„ ๋ฌธ์ œ๋Š” ์—†์„ ๊ฒƒ ๊ฐ™๋‹ค๋Š” ์ƒ๊ฐ์ž…๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ ์„œ๋ฒ„๊ฐ€ ๊นจ์ ธ์„œ ์ด์ƒํ•œ ๊ฐ’์„ ๋ณด๋‚ด์ฃผ๋Š” ๊ฒฝ์šฐ์—๋Š” ๋””๋ฒ„๊น…ํ•˜๊ธฐ ์–ด๋ ค์šธ ์ˆ˜๋„ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”. ํƒ€์ž… ์ถ”๋ก ์€ as๊ฐ€ ์• ์ดˆ์— ์ด๊ฑธ๋กœ ์ถ”๋ก ํ•ด๋ผ! ๋ผ๊ณ  ๋ช…๋ นํ•˜๋Š” ๊ฑฐ๋‹ˆ๊นŒ ๋ฌธ์ œ์—†์ด ๋˜๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์‹ค์ œ๋กœ ๋ฆฌ์•กํŠธ ์ฟผ๋ฆฌ ์ฝ”๋“œ๋ฅผ ์“ธ ๋•Œ ์ œ๋„ค๋ฆญ์œผ๋กœ ๋ฆฌํ„ด ํƒ€์ž…์„ ๋ช…์‹œํ•ด์ฃผ์ง€ ์•Š์•„๋„ ์•Œ์•„์„œ data ํƒ€์ž…์„ ์ถ”๋ก ํ•ด์ฃผ๋”๋ผ๊ณ ์š”. ๋งŒ์•ฝ ๊ณ ์ณ๋ณธ๋‹ค๋ฉด Promise์— ์ œ๋„ค๋ฆญ์œผ๋กœ ํƒ€์ž…์„ ๊ฑธ์–ด์ค„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค~!
@@ -0,0 +1,51 @@ +package nextstep.app.config; + +import nextstep.security.*; +import nextstep.security.domain.MemberDetailService; +import nextstep.security.filter.*; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.filter.DelegatingFilterProxy; + +import java.util.List; + +@Configuration +public class SecurityConfig { + + private final MemberDetailService memberDetailService; + + public SecurityConfig(MemberDetailService memberDetailService) { + this.memberDetailService = memberDetailService; + } + + @Bean + public DelegatingFilterProxy delegatingFilterProxy() { + return new DelegatingFilterProxy(filterChainProxy(List.of(securityFilterChain()))); + } + + @Bean + public FilterChainProxy filterChainProxy(List<SecurityFilterChain> securityFilterChains) { + return new FilterChainProxy(securityFilterChains); + } + + @Bean + public SecurityFilterChain securityFilterChain() { + return new DefaultSecurityFilterChain( + List.of(new ExceptionHandlerFilter(), + new BasicAuthenticationFilter(authenticationManager()), + new LoginAuthenticationFilter(authenticationManager()), + new SecurityContextHolderFilter(new HttpSessionSecurityContextRepository())) + ); + } + + @Bean + public AuthenticationManager authenticationManager() { + List<AuthenticationProvider> providers = List.of(daoAuthenticationProvider()); + return new ProviderManager(providers); + } + + @Bean + public DaoAuthenticationProvider daoAuthenticationProvider() { + return new DaoAuthenticationProvider(memberDetailService); + } +}
Java
ํ•„ํ„ฐ์˜ ์ˆœ์„œ๋Š” ์ค‘์š”ํ•ฉ๋‹ˆ๋‹ค! SecurityContextHolderFilter๋Š” BasicAuthenticationFilter, LoginAuthenticationFilter๋ณด๋‹ค ๋จผ์ € ์„ค์ •๋˜์–ด์•ผ ํ•  ๊ฒƒ ๊ฐ™์•„์š”~
@@ -0,0 +1,35 @@ +package nextstep.security; + +import nextstep.security.domain.MemberDetail; +import nextstep.security.domain.MemberDetailService; +import nextstep.security.exception.AuthenticationException; + +public class DaoAuthenticationProvider implements AuthenticationProvider { + + private final MemberDetailService memberDetailService; + + public DaoAuthenticationProvider(MemberDetailService memberDetailService) { + this.memberDetailService = memberDetailService; + } + + @Override + public Authentication authenticate(Authentication authentication) { + if (authentication.isAuthenticated()) { + return authentication; + } + + MemberDetail member = memberDetailService.findByUsername((String) authentication.getPrincipal()); + if (!member.isCorrectPassword((String) authentication.getCredentials())) { + throw new AuthenticationException(); + } + + UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(member, null); + authenticationToken.setAuthenticated(true); + return authenticationToken; + } + + @Override + public boolean supports(Class<?> authentication) { + return authentication.isAssignableFrom(UsernamePasswordAuthenticationToken.class); + } +}
Java
Pssword๋ฅผ ํ™•์ธํ•˜๋Š” ์—ญํ• ์„ Member์—๊ฒŒ ์ฃผ์…จ๋Š”๋ฐ, Password๋ฅผ ๊ฒ€์ฆํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜์€ ํ™•์žฅ ๊ฐ€๋Šฅํ•œ ์„ค๊ณ„๊ฐ€ ํ•„์š”ํ•  ๊ฒƒ ๊ฐ™์•„์š”. (e.g. ๋‹จ์ˆœ ํŒจ์Šค์›Œ๋“œ ํ™•์ธ, BCrypt ์•”ํ˜ธํ™”๋œ ์ •๋ณด๋ฅผ ํ™•์ธ, ...) ๋”ฐ๋ผ์„œ Member ์—ญํ• ์ด ์•„๋‹Œ ๋ณ„๋„์˜ ํ™•์žฅ ํฌ์ธํŠธ๋กœ ์„ค๊ณ„ํ•ด ๋ณด๋ฉด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,35 @@ +package nextstep.security; + +import nextstep.security.domain.MemberDetail; +import nextstep.security.domain.MemberDetailService; +import nextstep.security.exception.AuthenticationException; + +public class DaoAuthenticationProvider implements AuthenticationProvider { + + private final MemberDetailService memberDetailService; + + public DaoAuthenticationProvider(MemberDetailService memberDetailService) { + this.memberDetailService = memberDetailService; + } + + @Override + public Authentication authenticate(Authentication authentication) { + if (authentication.isAuthenticated()) { + return authentication; + } + + MemberDetail member = memberDetailService.findByUsername((String) authentication.getPrincipal()); + if (!member.isCorrectPassword((String) authentication.getCredentials())) { + throw new AuthenticationException(); + } + + UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(member, null); + authenticationToken.setAuthenticated(true); + return authenticationToken; + } + + @Override + public boolean supports(Class<?> authentication) { + return authentication.isAssignableFrom(UsernamePasswordAuthenticationToken.class); + } +}
Java
setAuthenticated๋Š” ์—ฌ๊ธฐ์„œ๋งŒ true๋กœ ์ง€์ •ํ•˜๊ณ  ์žˆ๋Š”๋ฐ, ์ด๋Ÿฌํ•œ ์„ค๊ณ„๋ฅผ ํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,70 @@ +package nextstep.security.filter; + +import jakarta.servlet.*; +import jakarta.servlet.http.HttpServletRequest; +import nextstep.security.*; +import nextstep.security.exception.AuthenticationException; +import nextstep.security.util.Base64Convertor; +import org.springframework.web.filter.GenericFilterBean; + +import java.io.IOException; + +import static nextstep.security.filter.LoginAuthenticationFilter.SPRING_SECURITY_CONTEXT_KEY; + +public class BasicAuthenticationFilter extends GenericFilterBean { + + private final AuthenticationManager authenticationManager; + + public BasicAuthenticationFilter(AuthenticationManager authenticationManager) { + this.authenticationManager = authenticationManager; + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + HttpServletRequest httpRequest = (HttpServletRequest) request; + if (notTarget(httpRequest)) { + chain.doFilter(request, response); + return; + } + + Authentication resultAuthentication = authenticationManager.authenticate(getAuthenticationFrom(httpRequest)); + SecurityContextHolder.getContext().setAuthentication(resultAuthentication); + chain.doFilter(request, response); + } + + private static boolean notTarget(HttpServletRequest httpRequest) { + return !httpRequest.getRequestURI().startsWith("/members"); + } + + private static Authentication getAuthenticationFrom(HttpServletRequest httpRequest) { + if (httpRequest.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY) != null) { + SecurityContext attribute = (SecurityContext) httpRequest.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY); + return attribute.getAuthentication(); + } + + String basicToken = extractToken(httpRequest); + String[] usernameAndPassword = splitToken(basicToken); + + String username = usernameAndPassword[0]; + String password = usernameAndPassword[1]; + return new UsernamePasswordAuthenticationToken(username, password); + } + + private static String extractToken(HttpServletRequest httpRequest) { + String authorization = httpRequest.getHeader("Authorization"); + return authorization.split(" ")[1]; + } + + private static String[] splitToken(String basicToken) { + String decodedString = Base64Convertor.decode(basicToken); + String[] usernameAndPassword = decodedString.split(":"); + validateToken(usernameAndPassword); + return usernameAndPassword; + } + + private static void validateToken(String[] usernameAndPassword) { + if (usernameAndPassword.length != 2) { + throw new AuthenticationException(); + } + } +}
Java
๊ฐ ํ•„ํ„ฐ์—์„œ SecurityContext๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ๋Š” SecurityContextHolder๋ฅผ ํ†ตํ•ด ์‚ฌ์šฉํ•˜๋ฉด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,47 @@ +package nextstep.security.filter; + +import jakarta.servlet.*; +import org.springframework.web.filter.GenericFilterBean; + +import java.io.IOException; +import java.util.List; + +public class FilterChainProxy extends GenericFilterBean { + + private final List<SecurityFilterChain> filterChains; + + public FilterChainProxy(List<SecurityFilterChain> filterChains) { + this.filterChains = filterChains; + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { + for (SecurityFilterChain filterChain : filterChains) { + List<Filter> filters = filterChain.filters(); + VirtualFilterChain virtualFilterChain = new VirtualFilterChain(filters, chain); + virtualFilterChain.doFilter(servletRequest, servletResponse); + } + } + + public static class VirtualFilterChain implements FilterChain { + + private final List<Filter> filters; + private final FilterChain originalChain; + private int currentPosition = 0; + + public VirtualFilterChain(List<Filter> filters, FilterChain originalChain) { + this.filters = filters; + this.originalChain = originalChain; + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { + if (currentPosition >= filters.size()) { + originalChain.doFilter(request, response); + } else { + Filter filter = filters.get(currentPosition++); + filter.doFilter(request, response, this); + } + } + } +}
Java
์ง€๊ธˆ์€ ๋ชจ๋“  ์ฒด์ธ์˜ ํ•„ํ„ฐ๋ฅผ ์‹คํ–‰ํ•˜๊ณ  ์žˆ๋Š”๋ฐ์š”. ์ง€๊ธˆ ํ”„๋กœ์ ํŠธ์—์„  ํ•˜๋‚˜์˜ ํ•„ํ„ฐ ์ฒด์ธ๋งŒ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ์ง€๋งŒ, ์—ฌ๋Ÿฌ ํ•„ํ„ฐ ์ฒด์ธ์„ ์‚ฌ์šฉํ•  ์ˆ˜ ๊ฒฝ์šฐ ๋ฌธ์ œ๊ฐ€ ์ƒ๊ธธ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์€๋ฐ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”?
@@ -0,0 +1,25 @@ +package nextstep.security.filter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import nextstep.security.SecurityContextHolder; +import nextstep.security.exception.AuthenticationException; +import org.springframework.http.HttpStatus; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +public class ExceptionHandlerFilter extends OncePerRequestFilter { + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { + try { + chain.doFilter(request, response); + } catch (AuthenticationException e) { + SecurityContextHolder.clearContext(); + response.setStatus(HttpStatus.UNAUTHORIZED.value()); + } + } +}
Java
> ์˜ˆ์™ธ ๋ฐœ์ƒ ์‹œ clearContext๋Š” ExceptionHandlerFilter์—์„œ ์ˆ˜ํ–‰ํ•˜๋„๋ก ๊ตฌํ˜„ํ–ˆ๊ณ , ์š”์ฒญ ์™„๋ฃŒ ํ›„ clearContext๋Š” SecurityContextHolderFilter์—์„œ ์ˆ˜ํ–‰ํ•˜๋„๋ก ๊ตฌํ˜„ํ–ˆ์Šต๋‹ˆ๋‹ค. ์ด๊ฒŒ ๋งž๋Š” ๋ฐฉ์‹์ธ์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค. Filter์˜ ์—ญํ• ์„ ์ž˜ ๋‚˜๋ˆ ์ฃผ์…จ์–ด์š” ๐Ÿ‘ ์กฐ๊ธˆ ๋” ์ฝ”๋“œ๋ฅผ ๋ฐœ์ „์‹œ์ผœ ๋ณธ๋‹ค๋ฉด ์˜ˆ์™ธ ์ƒํ™ฉ์— ๋”ฐ๋ฅธ ์˜ˆ์™ธ ์ฒ˜๋ฆฌ๊ฐ€ ์ถ”๊ฐ€๋˜๊ณ , SecurityContextHolder์™€ ๊ด€๋ จ๋œ ๋ชจ๋“  ์—ญํ• ์€ SecurityContextHolderFilter์—์„œ ๋‹ด๋‹นํ•˜๋„๋ก ํ•ด๋ณด๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,9 @@ +package nextstep.security; + +public interface Authentication { + Object getPrincipal(); + + Object getCredentials(); + + boolean isAuthenticated(); +}
Java
> security ํŒจํ‚ค์ง€ ํ•˜์œ„์˜ ํŒจํ‚ค์ง€๋ฅผ ์–ด๋–ป๊ฒŒ ์„ค์ • (๋„ค์ด๋ฐ) ํ•ด์•ผ ํ• ์ง€ ๊ณ ๋ฏผ์ด ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. filter๋ฅผ ํŒจํ‚ค์ง€๋กœ ๋งŒ๋“ค์–ด์ฃผ์‹  ๊ฒƒ์ฒ˜๋Ÿผ, ๋™์ผํ•œ ๋งฅ๋ฝ์„ ๊ฐ€์ง„ ๊ตฌ์„ฑ ์š”์†Œ๋“ค์„ ํŒจํ‚ค์ง€๋กœ ๋ฌถ๊ณ  ๊ณตํ†ต๋œ ํŠน์ง•์„ ๊ธฐ์ค€์œผ๋กœ ๋„ค์ด๋ฐ ํ•ด๋ณด๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”. context์™€ authentication์— ๋Œ€ํ•œ ๋ถ€๋ถ„๋งŒ ๋ชจ์•„๋ณด๋ฉด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,35 @@ +package nextstep.security; + +import nextstep.security.domain.MemberDetail; +import nextstep.security.domain.MemberDetailService; +import nextstep.security.exception.AuthenticationException; + +public class DaoAuthenticationProvider implements AuthenticationProvider { + + private final MemberDetailService memberDetailService; + + public DaoAuthenticationProvider(MemberDetailService memberDetailService) { + this.memberDetailService = memberDetailService; + } + + @Override + public Authentication authenticate(Authentication authentication) { + if (authentication.isAuthenticated()) { + return authentication; + } + + MemberDetail member = memberDetailService.findByUsername((String) authentication.getPrincipal()); + if (!member.isCorrectPassword((String) authentication.getCredentials())) { + throw new AuthenticationException(); + } + + UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(member, null); + authenticationToken.setAuthenticated(true); + return authenticationToken; + } + + @Override + public boolean supports(Class<?> authentication) { + return authentication.isAssignableFrom(UsernamePasswordAuthenticationToken.class); + } +}
Java
> ์ธ์ฆ ๋กœ์ง์„ AuthenticationProvider์—์„œ ์ˆ˜ํ–‰ํ•˜๋„๋ก ๊ตฌํ˜„ํ–ˆ๋Š”๋ฐ, username, password๋ฅผ ํŒŒ์‹ฑํ•˜๋Š” ๋กœ์ง๋„ ์ธ์ฆ ๋กœ์ง์— ํฌํ•จ์ด ๋˜์–ด์•ผ ํ•˜๋Š”์ง€ ๊ณ ๋ฏผ์ด ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. (Provider์—์„œ ํŒŒ์‹ฑ์„ ์ˆ˜ํ–‰ํ•œ๋‹ค๋ฉด Provider ๊ตฌํ˜„์ฒด๋ฅผ 2๊ฐœ ๋งŒ๋“ค์–ด์•ผ ํ•œ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ์Šต๋‹ˆ๋‹ค. ์ผ๋‹จ ํŒŒ์‹ฑ์€ Filter์—์„œ ์ˆ˜ํ–‰ํ•˜๋„๋ก ๊ตฌํ˜„ํ–ˆ์Šต๋‹ˆ๋‹ค.) ์ข‹์€ ๊ณ ๋ฏผ์„ ํ•˜์…จ๋„ค์š” ๐Ÿ‘ ์ผ๋ฐ˜์ ์œผ๋กœ ๊ตฌํ˜„ํ•ด์ฃผ์‹  ๊ฒƒ์ฒ˜๋Ÿผ ํŒŒ์‹ฑ์˜ ์—ญํ• ์€ Filter์—์„œ ํ•˜๋Š” ๊ฒƒ์ด ์ผ๋ฐ˜์ ์ธ ์„ค๊ณ„์ž…๋‹ˆ๋‹ค. Filter๋Š” HTTP ์š”์ฒญ์„ ์ฒ˜๋ฆฌํ•˜๋Š” ์—ญํ• ์„ ๊ฐ€์ง€๊ณ  ์žˆ๊ณ , AuthenticationProvider๋Š” ์ธ์ฆ์„ ๋‹ด๋‹นํ•œ๋‹ค๊ณ  ๋ดค์„ ๋•Œ ๊ตฌํ˜„์„ ์ž˜ ํ•ด์ฃผ์…จ๋„ค์š” ใ…Žใ…Ž
@@ -0,0 +1,51 @@ +package nextstep.security.filter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import nextstep.security.Authentication; +import nextstep.security.AuthenticationManager; +import nextstep.security.SecurityContextHolder; +import nextstep.security.UsernamePasswordAuthenticationToken; +import org.springframework.web.filter.GenericFilterBean; + +import java.io.IOException; +import java.util.Map; + +public class LoginAuthenticationFilter extends GenericFilterBean { + + public static final String SPRING_SECURITY_CONTEXT_KEY = "SPRING_SECURITY_CONTEXT"; + private final AuthenticationManager authenticationManager; + + public LoginAuthenticationFilter(AuthenticationManager authenticationManager) { + this.authenticationManager = authenticationManager; + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + HttpServletRequest httpRequest = (HttpServletRequest) request; + if (notTarget(httpRequest)) { + chain.doFilter(request, response); + return; + } + + Authentication authentication = authenticationManager.authenticate(getAuthentication(httpRequest)); + SecurityContextHolder.getContext().setAuthentication(authentication); + httpRequest.getSession().setAttribute(SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext()); + + chain.doFilter(request, response); + } + + private static boolean notTarget(HttpServletRequest httpRequest) { + return !httpRequest.getRequestURI().startsWith("/login"); + } + + private static UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest httpRequest) { + Map<String, String[]> parameterMap = httpRequest.getParameterMap(); + String username = parameterMap.get("username")[0]; + String password = parameterMap.get("password")[0]; + return new UsernamePasswordAuthenticationToken(username, password); + } +}
Java
SPRING_SECURITY_CONTEXT_KEY๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ์ฒ˜๋ฆฌํ•˜๋Š” ์—ญํ• ์€ SecurityContextRepository์—๊ฒŒ ๋„˜๊ฒจ์ฃผ๋ฉด ์ข‹๊ฒ ๋„ค์š”!
@@ -0,0 +1,40 @@ +package nextstep.security.filter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import nextstep.security.SecurityContext; +import nextstep.security.SecurityContextHolder; +import nextstep.security.SecurityContextRepository; +import org.springframework.web.filter.GenericFilterBean; + +import java.io.IOException; + +public class SecurityContextHolderFilter extends GenericFilterBean { + + private final SecurityContextRepository securityContextRepository; + + public SecurityContextHolderFilter(SecurityContextRepository securityContextRepository) { + this.securityContextRepository = securityContextRepository; + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + HttpServletRequest httpRequest = (HttpServletRequest) request; + HttpServletResponse httpResponse = (HttpServletResponse) response; + + SecurityContext securityContext = securityContextRepository.loadContext(httpRequest); + SecurityContextHolder.setContext(securityContext); + + try { + chain.doFilter(httpRequest, response); + } finally { + SecurityContext context = SecurityContextHolder.getContext(); + securityContextRepository.saveContext(context, httpRequest, httpResponse); +// SecurityContextHolder.clearContext(); + } + } +}
Java
> 4๋‹จ๊ณ„ SecurityContextHolderFilter ๊ตฌํ˜„ ์ค‘ clearContext๋ฅผ SecurityContextHolderFilter์—์„œ ์ˆ˜ํ–‰ํ•˜๋Š” ๊ฒŒ ๋งž๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ๋Š”๋ฐ, clearContext๋ฅผ ์ˆ˜ํ–‰ํ•˜๋ฉด ํ…Œ์ŠคํŠธ๊ฐ€ ์‹คํŒจํ•ฉ๋‹ˆ๋‹ค. ์ผ๋‹จ ์ œ์ถœ์„ ์œ„ํ•ด ์ฃผ์„์ฒ˜๋ฆฌํ–ˆ๋Š”๋ฐ, ํ…Œ์ŠคํŠธ๊ฐ€ ์‹คํŒจํ•˜๋Š” ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค. ```suggestion securityContextRepository.saveContext(securityContext, httpRequest, httpResponse); SecurityContextHolder.clearContext(); ``` ์œ„์™€ ๊ฐ™์ด ์ˆ˜์ •ํ•˜๋ฉด ์ž˜ ๋™์ž‘ํ•  ๊ฒƒ ๊ฐ™์€๋ฐ ์™œ ๊ทธ๋Ÿด์ง€ ๊ณ ๋ฏผํ•ด๋ณด์•„์š” :)
@@ -1 +1,60 @@ # spring-security-authentication + +## 1๋‹จ๊ณ„ - SecurityFilterChain ์ ์šฉ + +์ธํ„ฐ์…‰ํ„ฐ๋กœ ๊ตฌํ˜„ํ•œ ์ธ์ฆ ๋กœ์ง์„ ํ•„ํ„ฐ ํ˜•ํƒœ๋กœ ๋ณ€ํ˜•ํ•œ๋‹ค. +์ธ์ฆ ๋กœ์ง์ด ๋‹ด๊ธด ํ•„ํ„ฐ๋ฅผ ๋ฐ”๋กœ ์„œ๋ธ”๋ฆฟ ํ•„ํ„ฐ๋กœ ๋“ฑ๋กํ•˜์ง€ ์•Š๊ณ  ์•„๋ž˜ ์ด๋ฏธ์ง€๋ฅผ ์ฐธ๊ณ ํ•˜์—ฌ ๋ณ„๋„์˜ ํ•„ํ„ฐ ์ฒด์ธ์„ ๊ตฌ์ถ•ํ•˜์—ฌ ๊ตฌํ˜„ํ•œ๋‹ค. +์ฃผ์š” ํด๋ž˜์Šค: DelegatingFilterProxy, FilterChainProxy, SecurityFilterChain, DefaultSecurityFilterChain, VirtualFilterChain(FilterChainProxy์˜ ๋‚ด๋ถ€ ํด๋ž˜์Šค) + +![SecurityFilterChain.png](docs-img/SecurityFilterChain.png) + +### ์š”๊ตฌ ์‚ฌํ•ญ +- [X] ๊ธฐ์กด Interceptor ์ธ์ฆ ๋กœ์ง ๋ณ€ํ™˜ + - ์ œ๊ณต๋œ Interceptor ๊ธฐ๋ฐ˜ ์ธ์ฆ ๋กœ์ง์„ Filter๋กœ ๋ณ€ํ™˜ + - ๋ณ€ํ™˜๋œ Filter๋Š” HttpServletRequest์™€ HttpServletResponse๋ฅผ ์ฒ˜๋ฆฌํ•˜๋ฉฐ, ์ธ์ฆ ์—ฌ๋ถ€๋ฅผ ๊ฒฐ์ • + - ์š”์ฒญ์ด ์ธ์ฆ๋˜์ง€ ์•Š์€ ๊ฒฝ์šฐ, ์ ์ ˆํ•œ HTTP ์ƒํƒœ ์ฝ”๋“œ(์˜ˆ: 401 Unauthorized) ๋ฐ˜ํ™˜ + - ์ธ์ฆ๋œ ์‚ฌ์šฉ์ž ์ •๋ณด๋Š” ์š”์ฒญ ๊ฐ์ฒด์— ์ถ”๊ฐ€ํ•˜์—ฌ ์ดํ›„ ํ•„ํ„ฐ์—์„œ ์ ‘๊ทผ ๊ฐ€๋Šฅํ•˜๋„๋ก ์„ค์ • +- [X] DelegatingFilterProxy ์„ค์ • + - Spring Bean์œผ๋กœ DelegatingFilterProxy๋ฅผ ๋“ฑ๋กํ•˜๊ณ  ์ด๋ฅผ ํ†ตํ•ด FilterChainProxy๋ฅผ ํ˜ธ์ถœํ•˜๋„๋ก ์„ค์ • + - DelegatingFilterProxy๋Š” Servlet ์ปจํ…Œ์ด๋„ˆ์˜ Filter์™€ Spring ์ปจํ…์ŠคํŠธ๋ฅผ ์—ฐ๊ฒฐ +- [X] FilterChainProxy ๊ตฌํ˜„ + - FilterChainProxy๋Š” ์š”์ฒญ URI์— ๋”ฐ๋ผ ์ ์ ˆํ•œ SecurityFilterChain์„ ์„ ํƒํ•˜์—ฌ ์‹คํ–‰ + - SecurityFilterChain์€ Filter ๋ฆฌ์ŠคํŠธ๋ฅผ ํฌํ•จํ•˜๋ฉฐ ์š”์ฒญ์„ ์ฒ˜๋ฆฌ +- [X] SecurityFilterChain ๋ฆฌํŒฉํ„ฐ๋ง + - ๊ฐ SecurityFilterChain์€ ์—ญํ• ์— ๋”ฐ๋ผ ๋‹ค๋ฅธ ํ•„ํ„ฐ ์„ธํŠธ๋ฅผ ๊ด€๋ฆฌ + - ์ธ์ฆ(Authentication) ํ•„ํ„ฐ์™€ ๊ถŒํ•œ(Authorization) ํ•„ํ„ฐ๋ฅผ ํฌํ•จํ•˜๋„๋ก ๊ตฌ์„ฑ + +## 2๋‹จ๊ณ„ - AuthenticationManager ์ ์šฉ + +๋‹ค์–‘ํ•œ ์ธ์ฆ ๋ฐฉ์‹์„ ์ฒ˜๋ฆฌํ•˜๊ธฐ ์œ„ํ•ด AuthenticationManager๋ฅผ ํ™œ์šฉํ•˜์—ฌ ์ธ์ฆ ๊ณผ์ •์„ ์ถ”์ƒํ™”ํ•œ๋‹ค. +๊ธฐ์กด์˜ ์ธ์ฆ ๋กœ์ง์„ ๋ถ„๋ฆฌํ•˜๊ณ , ์ธ์ฆ ๋ฐฉ์‹์„ ์œ ์—ฐํ•˜๊ฒŒ ํ™•์žฅ ๊ฐ€๋Šฅํ•˜๋„๋ก ๊ตฌ์กฐํ™”ํ•œ๋‹ค. +์ฃผ์š” ํด๋ž˜์Šค: AuthenticationManager, ProviderManager, AuthenticationProvider, DaoAuthenticationProvider + +![AuthenticationManager.png](docs-img/AuthenticationManager.png) + +### ์š”๊ตฌ ์‚ฌํ•ญ + +- [X] Authentication์™€ UsernamePasswordAuthenticationToken ๊ตฌํ˜„ +- [X] ์ œ๊ณต๋œ AuthenticationManager๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ProviderManager ๊ตฌํ˜„ +- [X] ์ œ๊ณต๋œ AuthenticationProvider๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ DaoAuthenticationProvider ๊ตฌํ˜„ +- [X] ๊ธฐ์กด ์ธ์ฆ ํ•„ํ„ฐ์—์„œ ์ธ์ฆ ๋กœ์ง ๋ถ„๋ฆฌ ๋ฐ AuthenticationManager๋กœ ํ†ตํ•ฉ + +## 3๋‹จ๊ณ„ - SecurityContextHolder ์ ์šฉ +- ์ธ์ฆ ์„ฑ๊ณต ํ›„ ์ƒ์„ฑ๋œ Authentication ๊ฐ์ฒด๋ฅผ ๊ธฐ์กด์˜ ์„ธ์…˜ ๋ฐฉ์‹ ๋Œ€์‹  ์Šค๋ ˆ๋“œ ๋กœ์ปฌ(Thread Local)์— ๋ณด๊ด€ํ•˜๋„๋ก ๋ณ€๊ฒฝํ•œ๋‹ค. +- ๊ฐ ํ•„ํ„ฐ์—์„œ ์Šค๋ ˆ๋“œ ๋กœ์ปฌ์— ๋ณด๊ด€๋œ ์ธ์ฆ ์ •๋ณด๋ฅผ ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋„๋ก SecurityContextHolder์™€ SecurityContext ๊ตฌ์กฐ๋ฅผ ๊ตฌํ˜„ํ•œ๋‹ค. + +![SecurityContextHolder.png](docs-img/SecurityContextHolder.png) + +### ์š”๊ตฌ์‚ฌํ•ญ +-[X] SecurityContext ๋ฐ SecurityContextHolder ์ž‘์„ฑ +-[X] BasicAuthenticationFilter์—์„œ SecurityContextHolder ํ™œ์šฉ +-[X] ๊ธฐ์กด ์„ธ์…˜ ๋ฐฉ์‹์—์„œ ์Šค๋ ˆ๋“œ ๋กœ์ปฌ ๋ฐฉ์‹์œผ๋กœ ์ธ์ฆ ์ •๋ณด ๊ด€๋ฆฌ ๋ณ€๊ฒฝ + +## 4๋‹จ๊ณ„ - SecurityContextHolderFilter ๊ตฌํ˜„ +* ์„ธ์…˜์— ๋ณด๊ด€๋œ ์ธ์ฆ ์ •๋ณด๋ฅผ SecurityContextHolder๋กœ ์˜ฎ๊ธฐ๊ธฐ ์œ„ํ•œ SecurityContextHolderFilter๋ฅผ ๊ตฌํ˜„ํ•œ๋‹ค. + +### ์š”๊ตฌ ์‚ฌํ•ญ +- [X] SecurityContextRepository ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ HttpSessionSecurityContextRepository ๊ตฌํ˜„ +- [X] SecurityContextHolderFilter ์ž‘์„ฑ ๋ฐ ํ•„ํ„ฐ ์ฒด์ธ์— ๋“ฑ๋ก +- [X] login_after_members ํ…Œ์ŠคํŠธ๋กœ ๋™์ž‘ ๊ฒ€์ฆ +
Unknown
์š”๊ตฌ์‚ฌํ•ญ์„ ์•„์ฃผ ๊ผผ๊ผผํ•˜๊ฒŒ ์ž‘์„ฑํ•ด ์ฃผ์…จ๋„ค์š”! ๐Ÿ‘
@@ -0,0 +1,34 @@ +package nextstep.security.filter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import nextstep.security.context.SecurityContext; +import nextstep.security.context.SecurityContextHolder; +import nextstep.security.context.SecurityContextRepository; +import org.springframework.web.filter.GenericFilterBean; + +import java.io.IOException; + +public class SecurityContextHolderFilter extends GenericFilterBean { + private final SecurityContextRepository securityContextRepository; + + public SecurityContextHolderFilter(SecurityContextRepository securityContextRepository) { + this.securityContextRepository = securityContextRepository; + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + SecurityContext securityContext = securityContextRepository.loadContext((HttpServletRequest) request); + SecurityContextHolder.setContext(securityContext); + + chain.doFilter(request,response); + + SecurityContext context = SecurityContextHolder.getContext(); + securityContextRepository.saveContext(context, (HttpServletRequest) request, (HttpServletResponse) response); + SecurityContextHolder.clearContext(); + } +}
Java
ํ˜„์žฌ SecurityContextHolderFilter์—์„œ securityContextRepository.saveContext(context, request, response);๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ๋ฐฉ์‹์€ Spring Security์˜ ์ผ๋ฐ˜์ ์ธ ํ๋ฆ„๊ณผ ๋งž์ง€ ์•Š์„ ๊ฒƒ ๊ฐ™์•„์š” ๐Ÿ˜ข ์ธ์ฆ์ด ์ด๋ฃจ์–ด์ง€์ง€ ์•Š์•˜์Œ์—๋„ ๋ถˆ๊ตฌํ•˜๊ณ  SecurityContext๋ฅผ ์ €์žฅํ•  ๊ฐ€๋Šฅ์„ฑ์ด ์žˆ์„ ๊ฒƒ ๊ฐ™์€๋ฐ ๊ฐœ์„ ํ•ด๋ณด๋ฉด ์–ด๋–จ๊นŒ์š”? ๐Ÿ˜„
@@ -0,0 +1,46 @@ +package nextstep.security.authentication; + +import nextstep.security.UserDetails; +import nextstep.security.UserDetailsService; + +import java.util.Objects; + +public class DaoAuthenticationProvider implements AuthenticationProvider { + private final UserDetailsService userDetailsService; + + public DaoAuthenticationProvider(UserDetailsService userDetailsService) { + this.userDetailsService = userDetailsService; + } + + @Override + public Authentication authenticate(Authentication authentication) throws AuthenticationException { + check(authentication); + + final String username = authentication.getPrincipal().toString(); + final String password = authentication.getCredentials().toString(); + final UserDetails userDetails = userDetailsService.loadUserByUsername(username); + + if (Objects.equals(password, userDetails.getPassword())) { + return UsernamePasswordAuthenticationToken.ofAuthenticated(username, password); + } + + throw new AuthenticationException(); + } + + private static void check(Authentication authentication) { + if (authentication == null) { + throw new AuthenticationException(); + } + if (authentication.getPrincipal() == null) { + throw new AuthenticationException(); + } + if (authentication.getCredentials() == null) { + throw new AuthenticationException(); + } + } + + @Override + public boolean supports(Class<?> authentication) { + return authentication == UsernamePasswordAuthenticationToken.class; + } +}
Java
ํ•ด๋‹น ๋ฉ”์„œ๋“œ์— static์„ ์‚ฌ์šฉํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ๋‚˜์š”?
@@ -0,0 +1,46 @@ +package nextstep.security.authentication; + +import nextstep.security.UserDetails; +import nextstep.security.UserDetailsService; + +import java.util.Objects; + +public class DaoAuthenticationProvider implements AuthenticationProvider { + private final UserDetailsService userDetailsService; + + public DaoAuthenticationProvider(UserDetailsService userDetailsService) { + this.userDetailsService = userDetailsService; + } + + @Override + public Authentication authenticate(Authentication authentication) throws AuthenticationException { + check(authentication); + + final String username = authentication.getPrincipal().toString(); + final String password = authentication.getCredentials().toString(); + final UserDetails userDetails = userDetailsService.loadUserByUsername(username); + + if (Objects.equals(password, userDetails.getPassword())) { + return UsernamePasswordAuthenticationToken.ofAuthenticated(username, password); + } + + throw new AuthenticationException(); + } + + private static void check(Authentication authentication) { + if (authentication == null) { + throw new AuthenticationException(); + } + if (authentication.getPrincipal() == null) { + throw new AuthenticationException(); + } + if (authentication.getCredentials() == null) { + throw new AuthenticationException(); + } + } + + @Override + public boolean supports(Class<?> authentication) { + return authentication == UsernamePasswordAuthenticationToken.class; + } +}
Java
== ์—ฐ์‚ฐ์ž๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ UsernamePasswordAuthenticationToken๊ณผ ์ง์ ‘ ๋น„๊ตํ•˜๊ณ  ์žˆ๋Š”๋ฐ์š”, isAssignableFrom() ๋กœ ๋น„๊ตํ•˜๋Š” ๊ฒƒ๊ณผ ์–ด๋– ํ•œ ์ฐจ์ด๊ฐ€ ์žˆ์„๊นŒ์š”? ๐Ÿ˜„
@@ -0,0 +1,21 @@ +package nextstep.security.context; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; + +public class HttpSessionSecurityContextRepository implements SecurityContextRepository { + private static final String SPRING_SECURITY_CONTEXT_KEY = "SPRING_SECURITY_CONTEXT"; + + @Override + public SecurityContext loadContext(HttpServletRequest request) { + HttpSession session = request.getSession(); + return (SecurityContext) session.getAttribute(SPRING_SECURITY_CONTEXT_KEY); + } + + @Override + public void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response) { + HttpSession session = request.getSession(); + session.setAttribute(SPRING_SECURITY_CONTEXT_KEY, context); + } +}
Java
ํ˜„์žฌ request.getSession()์„ ํ˜ธ์ถœํ•˜๋ฉด ์„ธ์…˜์ด ์กด์žฌํ•˜์ง€ ์•Š์„ ๊ฒฝ์šฐ ์ž๋™์œผ๋กœ ์ƒˆ ์„ธ์…˜์„ ์ƒ์„ฑํ•˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค. ์„ธ์…˜์ด ํ•„์š”ํ•˜์ง€ ์•Š์€ ์š”์ฒญ์—๋„ ๋ถˆํ•„์š”ํ•œ ์„ธ์…˜์ด ์ƒ์„ฑ๋  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์€๋ฐ, getSession(false)๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์–ด๋–ค ์ฐจ์ด๊ฐ€ ์žˆ์„๊นŒ์š”? ๐Ÿค” ๊ธฐ์กด ์„ธ์…˜์ด ์žˆ๋Š” ๊ฒฝ์šฐ์—๋งŒ SecurityContext๋ฅผ ๋กœ๋“œํ•˜๋„๋ก ๊ฐœ์„ ํ•ด๋ณด๋ฉด ์–ด๋–จ๊นŒ์š”? ๐Ÿ˜„
@@ -0,0 +1,60 @@ +package nextstep.security.filter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.AuthenticationManager; +import nextstep.security.authentication.UsernamePasswordAuthenticationToken; +import nextstep.security.context.SecurityContextHolder; +import nextstep.security.util.Base64Convertor; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +public class BasicAuthenticationFilter extends OncePerRequestFilter { + private static final String BASIC_PREFIX = "basic "; + + private final AuthenticationManager authenticationManager; + + public BasicAuthenticationFilter(AuthenticationManager authenticationManager) { + this.authenticationManager = authenticationManager; + } + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { + final String authorization = request.getHeader(HttpHeaders.AUTHORIZATION); + if (!isNotBasicAuth(authorization)) { + filterChain.doFilter(request, response); + return; + } + try { + String[] usernameAndPassword = extractUsernameAndPassword(authorization); + UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(usernameAndPassword[0], usernameAndPassword[1]); + Authentication authenticate = authenticationManager.authenticate(authenticationToken); + + SecurityContextHolder.getContext().setAuthentication(authenticate); + + filterChain.doFilter(request, response); + } catch (Exception e) { + SecurityContextHolder.clearContext(); + response.setStatus(HttpStatus.UNAUTHORIZED.value()); + } + } + + private String[] extractUsernameAndPassword(String authorization) { + String base64Credentials = authorization.substring(BASIC_PREFIX.length()); + String decodedString = Base64Convertor.decode(base64Credentials); + return decodedString.split(":"); + } + + private boolean isNotBasicAuth(String authorization) { + if (authorization == null) { + return false; + } + return authorization.toLowerCase().startsWith(BASIC_PREFIX); + } +}
Java
isNotBasicAuth() ๋ฉ”์„œ๋“œ์˜ ๋„ค์ด๋ฐ์„ ๋ณด๋ฉด Basic ์ธ์ฆ์ด ์•„๋‹ ๊ฒฝ์šฐ true๋ฅผ ๋ฐ˜ํ™˜ํ•ด์•ผ ํ•  ๊ฒƒ ๊ฐ™์ง€๋งŒ, ํ˜„์žฌ ๊ตฌํ˜„์—์„œ๋Š” Basic ์ธ์ฆ์ผ ๋•Œ true๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ณ  ์žˆ๋„ค์š” ๐Ÿ˜„
@@ -0,0 +1,19 @@ +package nextstep.security.authentication; + +import nextstep.security.role.GrantedAuthority; + +import java.util.List; + +public interface Authentication { + String getPrincipal(); + + String getCredentials(); + + boolean isAuthenticated(); + + List<GrantedAuthority> getAuthorities(); + + void addAuthority(GrantedAuthority grantedAuthority); + + public boolean isNoPermission(); +}
Java
app ํŒจํ‚ค์ง€๋Š” ์ผ๋ฐ˜์ ์œผ๋กœ ๊ตฌํ˜„ํ•˜๋Š” ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์ด๊ณ , security ํŒจํ‚ค์ง€๋Š” ํ”„๋ ˆ์ž„์›Œํฌ์˜ ์„ค๊ณ„๋ฅผ ๊ฐ€์ง€๊ฒŒ ๋˜๋Š”๋ฐ์š”. ๊ทธ๋Ÿฐ ๊ด€์ ์—์„œ ์ง€๊ธˆ์˜ Role์€ NORMAL, ADMIN๋งŒ ์ง€์›ํ•˜๊ณ  ์žˆ๋Š”๋ฐ, ํ”„๋ ˆ์ž„์›Œํฌ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ์ž…์žฅ์—์„œ๋Š” ๋‘ ํƒ€์ž… ์ด์™ธ์— ๋งŽ์€ ์ผ€์ด์Šค๊ฐ€ ์กด์žฌํ•  ๊ฒƒ ๊ฐ™์•„์š”. ํ”„๋ ˆ์ž„์›Œํฌ๋ผ๋Š” ๊ด€์ ์—์„œ ์–ด๋–ป๊ฒŒ ํ™•์žฅ ํฌ์ธํŠธ๋ฅผ ๊ฐ€์ ธ๊ฐˆ ์ˆ˜ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,86 @@ +package nextstep.app; + +import nextstep.app.domain.CustomUserDetailsService; +import nextstep.app.domain.MemberRepository; +import nextstep.security.role.Role; +import nextstep.security.core.context.HttpSessionSecurityContextRepository; +import nextstep.security.core.context.SecurityContextRepository; +import nextstep.security.filter.AuthorizationFilter; +import nextstep.security.filter.GlobalExceptionFilter; +import nextstep.security.filter.SecurityContextHolderFilter; +import nextstep.security.filter.config.DefaultSecurityFilterChain; +import nextstep.security.filter.config.DelegatingFilterProxy; +import nextstep.security.filter.config.FilterChainProxy; +import nextstep.security.filter.config.SecurityFilterChain; +import nextstep.security.core.uesrdetails.UserDetailsService; +import nextstep.security.authentication.AuthenticationManager; +import nextstep.security.authentication.AuthenticationProvider; +import nextstep.security.authentication.DaoAuthenticationProvider; +import nextstep.security.authentication.ProviderManager; +import nextstep.security.filter.BasicAuthFilter; +import nextstep.security.filter.FormAuthFilter; +import nextstep.security.util.PasswordMatcher; +import nextstep.security.util.PlainTextPasswordMatcher; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.List; +import java.util.Map; + +@Configuration +public class SecurityConfig { + private final MemberRepository memberRepository; + + public SecurityConfig(final MemberRepository memberRepository) { + this.memberRepository = memberRepository; + } + + @Bean + public DelegatingFilterProxy delegatingFilterProxy() { + return new DelegatingFilterProxy(filterChainProxy(List.of(securityFilterChain()))); + } + + @Bean + public FilterChainProxy filterChainProxy(List<SecurityFilterChain> securityFilterChains) { + return new FilterChainProxy(securityFilterChains); + } + + @Bean + public SecurityFilterChain securityFilterChain() { + return new DefaultSecurityFilterChain( + new GlobalExceptionFilter(), + new SecurityContextHolderFilter(securityContextRepository()), + new FormAuthFilter(authenticationManager()), + new BasicAuthFilter(authenticationManager()), + new AuthorizationFilter(Map.of("/members", List.of(new Role("NORMAL"))) + ) + ); + } + + @Bean + public SecurityContextRepository securityContextRepository() { + return new HttpSessionSecurityContextRepository(); + } + + @Bean + public AuthenticationManager authenticationManager() { + List<AuthenticationProvider> providers = List.of(daoAuthenticationProvider()); + return new ProviderManager(providers); + } + + @Bean + public DaoAuthenticationProvider daoAuthenticationProvider() { + DaoAuthenticationProvider provider = new DaoAuthenticationProvider(passwordMatcher(), userDetailsService()); + return provider; + } + + @Bean + public PasswordMatcher passwordMatcher() { + return new PlainTextPasswordMatcher(); + } + + @Bean + public UserDetailsService userDetailsService() { + return new CustomUserDetailsService(memberRepository); + } +}
Java
> DefaultSecurityFilterChain์˜ match ๊ธฐ์ค€์ด ๋ญ˜๊นŒ์š”? ์—ฌ๋Ÿฌ ํ•„ํ„ฐ ์ฒด์ธ์ด ์กด์žฌํ•  ์ˆ˜ ์žˆ๊ณ , ํ•„ํ„ฐ ์ฒด์ธ๋งˆ๋‹ค ์กฐ๊ฑด์„ ์„ค์ •ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด AuthorizationFilter์˜ "/members"๊ฐ€ ์ผ์น˜ํ•˜๋Š”์ง€์˜ ์กฐ๊ฑด๋„ DefaultSecurityFilterChain์˜ match๋กœ ์˜ฎ๊ธฐ๋Š” ๊ฒƒ๋„ ํ•˜๋‚˜์˜ ์˜ˆ์‹œ๊ฐ€ ๋  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์€๋ฐ์š”. ์ด๋ฒˆ ๋ฏธ์…˜์—์„œ ์ค‘์š”ํ•œ ํฌ์ธํŠธ๋Š” ์•„๋‹ˆ๊ธฐ๋„ ํ•˜๊ณ  ์ง€๊ธˆ ๊ตฌํ˜„ํ•˜๋Š” ๊ทœ๋ชจ์—์„  Filter์—์„œ ๊ฒ€์ฆํ•˜๋Š” ๊ฒƒ๊ณผ ์ฐจ์ด๋ฅผ ๋А๋ผ์ง€ ํž˜๋“ค ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์„œ 4์ฃผ ์ฐจ ๋ฆฌํŒฉํ„ฐ๋ง ๋•Œ ์ž์„ธํžˆ ๊ตฌํ˜„ํ•ด๋ณด๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค ใ…Žใ…Ž ์ถ”๊ฐ€๋กœ ์‚ฌ์†Œํ•œ ํŒ์ธ๋ฐ ๋ฉ”์„œ๋“œ ๋งค๊ฐœ๋ณ€์ˆ˜๊ฐ€ ํ•˜๋‚˜๊ณ  List๋ฅผ ๋ฐ›์„ ๋•Œ ๊ฐ€๋ณ€์ธ์ž๋กœ ๋งŒ๋“ค๋ฉด ์ƒ๊ฐ๋ณด๋‹ค ํŽธํ•ด์„œ ์ข‹์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,30 @@ +package nextstep.app.domain; + +import nextstep.security.core.uesrdetails.UserDetails; +import nextstep.security.core.uesrdetails.UserDetailsService; +import nextstep.security.exception.AuthenticationException; +import nextstep.security.role.Role; + +public class CustomUserDetailsService implements UserDetailsService { + private final MemberRepository memberRepository; + + public CustomUserDetailsService(final MemberRepository memberRepository) { + this.memberRepository = memberRepository; + } + + @Override + public UserDetails loadUserByUsername(final String username) { + final CustomMember customMember = fetchUser(username); + + return customMember; + } + + private CustomMember fetchUser(final String username) { + final CustomMember customMember = memberRepository.findByEmail(username) + .map(CustomMember::new) + .orElseThrow(() -> new AuthenticationException()); + + customMember.addAuthority(new Role("NORMAL")); + return customMember; + } +}
Java
```suggestion return memberRepository.findByEmail(username) .map(CustomMember::new) .orElseThrow(() -> new IllegalArgumentException("ํ•ด๋‹นํ•˜๋Š” ์‚ฌ์šฉ์ž๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")); ``` ์†Œ์†Œํ•œ ๊ฐ€๋…์„ฑ ์ƒ์Šน์„ ํ•ด๋ณผ ์ˆ˜ ์žˆ๊ฒ ๋„ค์š”~
@@ -0,0 +1,79 @@ +package nextstep.security.filter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.AuthenticationManager; +import nextstep.security.authentication.UsernamePasswordAuthenticationToken; +import nextstep.security.core.context.SecurityContext; +import nextstep.security.core.context.SecurityContextHolder; +import nextstep.security.exception.AuthenticationException; +import nextstep.security.util.Base64Convertor; + +import java.io.IOException; + +public class BasicAuthFilter extends AbstractAuthProcessingFilter { + public static final String BASIC_HEADER_COLON = ":"; + public static final String BASIC_HEADER_COMMA = " "; + public static final String BASIC_HEADER_PREFIX = "Basic "; + public static final String AUTHORIZATION = "Authorization"; + + public BasicAuthFilter(final AuthenticationManager authenticationManager) { + super(authenticationManager); + } + + @Override + boolean match(final HttpServletRequest request) { + return existAuthorizationHeader(request); + } + + private boolean existAuthorizationHeader(final HttpServletRequest request) { + return request.getHeader(AUTHORIZATION) != null; + } + + @Override + public Authentication makeAuthentication(final HttpServletRequest request) { + String authorizationHeader = request.getHeader(AUTHORIZATION); + + if (isValidBasicAuthHeader(authorizationHeader)) { + throw new AuthenticationException(); + } + + String credentials = extractCredentials(authorizationHeader); + String[] usernameAndPassword = parseCredentials(credentials); + + return UsernamePasswordAuthenticationToken.unauthenticated(usernameAndPassword[0], usernameAndPassword[1]); + } + + private boolean isValidBasicAuthHeader(final String authorizationHeader) { + return authorizationHeader == null || !authorizationHeader.startsWith(BASIC_HEADER_PREFIX); + } + + private String extractCredentials(String authorizationHeader) { + String[] parts = authorizationHeader.split(BASIC_HEADER_COMMA); + if (parts.length != 2) { + throw new AuthenticationException(); + } + + return Base64Convertor.decode(parts[1]); + } + + private String[] parseCredentials(String decodedString) { + String[] usernameAndPassword = decodedString.split(BASIC_HEADER_COLON); + if (usernameAndPassword.length != 2) { + throw new AuthenticationException(); + } + + return usernameAndPassword; + } + + @Override + protected void successAuthentication(final HttpServletRequest request, final HttpServletResponse response, + final FilterChain filterChain) throws ServletException, IOException { + final SecurityContext context = SecurityContextHolder.getContext(); + final Authentication authentication = context.getAuthentication(); + authentication.getAuthorities().clear(); + } +}
Java
SecurityContextRepository์˜ ๊ตฌํ˜„์ฒด๋ฅผ Filter์—์„œ ์ฃผ์ž…๋ฐ›์•„ ์ฒ˜๋ฆฌํ•˜๊ฒŒ ๊ตฌํ˜„ํ•ด์ฃผ์…จ๋„ค์š”! ์Šคํ”„๋ง์€ ๋‹ค๋ฅธ Filter์—์„œ SecurityContextRepository์˜ ๋‚ด๋ถ€ ๊ตฌํ˜„์„ ๋ชฐ๋ผ๋„ `SecurityContextHolder.getContext()`๋ฅผ ํ†ตํ•ด ์ธ์ฆ ์ •๋ณด๋ฅผ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ๋„๋ก ์„ค๊ณ„๋˜์–ด ์žˆ๋Š”๋ฐ์š”. ์ด๋ ‡๊ฒŒ ๊ตฌ์กฐ๋ฅผ ์„ค๊ณ„ํ•œ ์ด์œ ์— ๋Œ€ํ•ด ๊ณ ๋ฏผํ•ด๋ณด์‹œ๋ฉด ์ข‹๊ฒ ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,48 @@ +package nextstep.security.filter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import nextstep.security.authentication.Authentication; +import nextstep.security.core.context.SecurityContextHolder; +import nextstep.security.exception.ForbiddenException; +import nextstep.security.role.GrantedAuthority; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; +import java.util.List; +import java.util.Map; + +public class AuthorizationFilter extends OncePerRequestFilter { + private final Map<String, List<GrantedAuthority>> restrictedRoutes; + + public AuthorizationFilter(Map<String, List<GrantedAuthority>> restrictedRoutes) { + this.restrictedRoutes = restrictedRoutes; + } + + @Override + protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response, final FilterChain filterChain) throws ServletException, IOException { + final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + + if (isUnauthorized(request, authentication)) { + throw new ForbiddenException(); + } + + filterChain.doFilter(request, response); + } + + private boolean isUnauthorized(final HttpServletRequest request, final Authentication authentication) { + final String requestURI = request.getRequestURI(); + + return restrictedRoutes.containsKey(requestURI) && isBlockedRole(authentication, requestURI); + + } + + private boolean isBlockedRole(final Authentication authentication, final String requestUri) { + List<GrantedAuthority> blockedRoles = restrictedRoutes.getOrDefault(requestUri, List.of()); + + return authentication.getAuthorities().stream() + .anyMatch(blockedRoles::contains); + } +}
Java
์ผ๋ฐ˜์ ์œผ๋กœ ํ•œ ํด๋ž˜์Šค ๋‚ด์—์„œ ์—ฃ์ง€ ์ผ€์ด์Šค๋ฅผ ํŒ๋‹จํ•  ๋•Œ๋Š” try-catch๋กœ ์˜ˆ์™ธ๋ฅผ ์ฒ˜๋ฆฌํ•˜๊ธฐ๋ณด๋‹ค, boolean์„ ํ™œ์šฉํ•ด ์‚ฌ์ „์— ์ฒดํฌํ•˜๊ณ  ํ•ธ๋“ค๋งํ•˜๋Š” ๊ฒƒ์ด ๊ฐ€๋…์„ฑ๊ณผ ์„ฑ๋Šฅ ๋ฉด์—์„œ ๋” ์ข‹์€๋ฐ์š”. ์ง€๊ธˆ ์ผ€์ด์Šค๋„ ์œ„ ์ผ€์ด์Šค์— ํ•ด๋‹นํ•˜๋Š” ๊ฒƒ ๊ฐ™์€๋ฐ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”?
@@ -0,0 +1,79 @@ +package nextstep.security.filter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.AuthenticationManager; +import nextstep.security.authentication.UsernamePasswordAuthenticationToken; +import nextstep.security.core.context.SecurityContext; +import nextstep.security.core.context.SecurityContextHolder; +import nextstep.security.exception.AuthenticationException; +import nextstep.security.util.Base64Convertor; + +import java.io.IOException; + +public class BasicAuthFilter extends AbstractAuthProcessingFilter { + public static final String BASIC_HEADER_COLON = ":"; + public static final String BASIC_HEADER_COMMA = " "; + public static final String BASIC_HEADER_PREFIX = "Basic "; + public static final String AUTHORIZATION = "Authorization"; + + public BasicAuthFilter(final AuthenticationManager authenticationManager) { + super(authenticationManager); + } + + @Override + boolean match(final HttpServletRequest request) { + return existAuthorizationHeader(request); + } + + private boolean existAuthorizationHeader(final HttpServletRequest request) { + return request.getHeader(AUTHORIZATION) != null; + } + + @Override + public Authentication makeAuthentication(final HttpServletRequest request) { + String authorizationHeader = request.getHeader(AUTHORIZATION); + + if (isValidBasicAuthHeader(authorizationHeader)) { + throw new AuthenticationException(); + } + + String credentials = extractCredentials(authorizationHeader); + String[] usernameAndPassword = parseCredentials(credentials); + + return UsernamePasswordAuthenticationToken.unauthenticated(usernameAndPassword[0], usernameAndPassword[1]); + } + + private boolean isValidBasicAuthHeader(final String authorizationHeader) { + return authorizationHeader == null || !authorizationHeader.startsWith(BASIC_HEADER_PREFIX); + } + + private String extractCredentials(String authorizationHeader) { + String[] parts = authorizationHeader.split(BASIC_HEADER_COMMA); + if (parts.length != 2) { + throw new AuthenticationException(); + } + + return Base64Convertor.decode(parts[1]); + } + + private String[] parseCredentials(String decodedString) { + String[] usernameAndPassword = decodedString.split(BASIC_HEADER_COLON); + if (usernameAndPassword.length != 2) { + throw new AuthenticationException(); + } + + return usernameAndPassword; + } + + @Override + protected void successAuthentication(final HttpServletRequest request, final HttpServletResponse response, + final FilterChain filterChain) throws ServletException, IOException { + final SecurityContext context = SecurityContextHolder.getContext(); + final Authentication authentication = context.getAuthentication(); + authentication.getAuthorities().clear(); + } +}
Java
> ์ธ์ฆ ๋ฏธ์…˜์˜ 4๋‹จ๊ณ„์—์„œ user_login_after_members ์ด ํ…Œ์ŠคํŠธ ํ†ต๊ณผ๊ฐ€ ์•ˆ๋˜์„œ ๊ณ ๋ฏผํ•˜๋‹ค๊ฐ€ ์ž„์˜๋กœ authorizationFilter๋ฅผ๏ฟฝ ๊ตฌํ˜„ํ•˜์˜€์Šต๋‹ˆ๋‹ค. > (ํ˜„๋‹จ๊ณ„์—์„œ ์–ด๋–ป๊ฒŒ ํ†ต๊ณผํ•˜๊ฒŒ ํ•˜๋Š”๊ฑธ๊นŒ์š”??) ๋กœ๊ทธ์ธ ๋ฐฉ์‹์— ๋”ฐ๋ผ Role์„ ๋‹ค๋ฅด๊ฒŒ ์„ค์ •ํ•˜์‹  ์ด์œ ๋Š” ์œ„ ์ด์œ  ๋•Œ๋ฌธ์ด๊ฒ ์ฃ ..?ใ…‹ใ…‹ ์ธ๊ฐ€์— ๋Œ€ํ•œ ๋ถ€๋ถ„์€ 2์ฃผ ์ฐจ์—์„œ ๋‹ค๋ฃจ๋Š” ๊ฒƒ์œผ๋กœ ์•Œ๊ณ  ์žˆ์–ด์„œ, ์ผ๋‹จ ์ธ๊ฐ€์— ๋Œ€ํ•œ ๋ถ€๋ถ„์€ ์‹ ๊ฒฝ์“ฐ์ง€ ์•Š๊ณ  ์ธ์ฆ๋œ ์‚ฌ์šฉ์ž๋ฅผ ํ™•์ธํ•œ๋‹ค! ๋ผ๋Š” ๊ฐœ๋…์œผ๋กœ ํ™•์ธํ•ด์ฃผ์‹œ๋ฉด ๋  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค (๋งŒ์•ฝ ์•„๋‹ˆ๋ฉด DM ๋“œ๋ฆด๊ฒŒ์š”..! ์†๋‹ฅ์†๋‹ฅ..)
@@ -0,0 +1,79 @@ +package nextstep.security.filter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.AuthenticationManager; +import nextstep.security.core.context.SecurityContext; +import nextstep.security.core.context.SecurityContextHolder; +import nextstep.security.exception.AuthenticationException; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +public abstract class AbstractAuthProcessingFilter extends OncePerRequestFilter { + private final AuthenticationManager authenticationManager; + + protected AbstractAuthProcessingFilter(final AuthenticationManager authenticationManager) { + this.authenticationManager = authenticationManager; + } + + @Override + protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response, final FilterChain filterChain) throws ServletException, IOException { + if (!match(request)) { + filterChain.doFilter(request, response); + return; + } + + if (isAlreadyAuthenticated()) { + filterChain.doFilter(request, response); + return; + } + + Authentication authRequest = makeAuthentication(request); + + Authentication authentication = authenticate(authRequest); + + saveAuthentication(request, response, authentication); + + successAuthentication(request, response, filterChain); + + if (!shouldContinueFilterChain()) { + return; + } + + doFilter(request, response, filterChain); + } + + private static boolean isAlreadyAuthenticated() { + return SecurityContextHolder.getContext().getAuthentication() != null; + } + + private Authentication authenticate(final Authentication authRequest) { + Authentication authentication = this.authenticationManager.authenticate(authRequest); + if (!authentication.isAuthenticated()) { + throw new AuthenticationException(); + } + + return authentication; + } + + abstract boolean match(final HttpServletRequest request); + + private void saveAuthentication(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) { + SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); + securityContext.setAuthentication(authentication); + SecurityContextHolder.setContext(securityContext); + } + + abstract Authentication makeAuthentication(final HttpServletRequest request); + + protected abstract void successAuthentication(final HttpServletRequest request, final HttpServletResponse response, + final FilterChain filterChain) throws ServletException, IOException; + + protected boolean shouldContinueFilterChain() { + return true; + } +}
Java
ํ•„ํ„ฐ์—์„œ๋Š” ๋งˆ์ง€๋ง‰์— doFilter()๋ฅผ ํ˜ธ์ถœํ•ด์•ผ ์ •์ƒ์ ์ธ ์š”์ฒญ ํ๋ฆ„์„ ์œ ์ง€ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค~
@@ -0,0 +1,19 @@ +package nextstep.security.authentication; + +import nextstep.security.role.GrantedAuthority; + +import java.util.List; + +public interface Authentication { + String getPrincipal(); + + String getCredentials(); + + boolean isAuthenticated(); + + List<GrantedAuthority> getAuthorities(); + + void addAuthority(GrantedAuthority grantedAuthority); + + public boolean isNoPermission(); +}
Java
์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์—์„œ Role ์„ ์ฃผ์ž…์‹œ์ผœ์•ผ ํ• ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค :)
@@ -0,0 +1,86 @@ +package nextstep.app; + +import nextstep.app.domain.CustomUserDetailsService; +import nextstep.app.domain.MemberRepository; +import nextstep.security.role.Role; +import nextstep.security.core.context.HttpSessionSecurityContextRepository; +import nextstep.security.core.context.SecurityContextRepository; +import nextstep.security.filter.AuthorizationFilter; +import nextstep.security.filter.GlobalExceptionFilter; +import nextstep.security.filter.SecurityContextHolderFilter; +import nextstep.security.filter.config.DefaultSecurityFilterChain; +import nextstep.security.filter.config.DelegatingFilterProxy; +import nextstep.security.filter.config.FilterChainProxy; +import nextstep.security.filter.config.SecurityFilterChain; +import nextstep.security.core.uesrdetails.UserDetailsService; +import nextstep.security.authentication.AuthenticationManager; +import nextstep.security.authentication.AuthenticationProvider; +import nextstep.security.authentication.DaoAuthenticationProvider; +import nextstep.security.authentication.ProviderManager; +import nextstep.security.filter.BasicAuthFilter; +import nextstep.security.filter.FormAuthFilter; +import nextstep.security.util.PasswordMatcher; +import nextstep.security.util.PlainTextPasswordMatcher; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.List; +import java.util.Map; + +@Configuration +public class SecurityConfig { + private final MemberRepository memberRepository; + + public SecurityConfig(final MemberRepository memberRepository) { + this.memberRepository = memberRepository; + } + + @Bean + public DelegatingFilterProxy delegatingFilterProxy() { + return new DelegatingFilterProxy(filterChainProxy(List.of(securityFilterChain()))); + } + + @Bean + public FilterChainProxy filterChainProxy(List<SecurityFilterChain> securityFilterChains) { + return new FilterChainProxy(securityFilterChains); + } + + @Bean + public SecurityFilterChain securityFilterChain() { + return new DefaultSecurityFilterChain( + new GlobalExceptionFilter(), + new SecurityContextHolderFilter(securityContextRepository()), + new FormAuthFilter(authenticationManager()), + new BasicAuthFilter(authenticationManager()), + new AuthorizationFilter(Map.of("/members", List.of(new Role("NORMAL"))) + ) + ); + } + + @Bean + public SecurityContextRepository securityContextRepository() { + return new HttpSessionSecurityContextRepository(); + } + + @Bean + public AuthenticationManager authenticationManager() { + List<AuthenticationProvider> providers = List.of(daoAuthenticationProvider()); + return new ProviderManager(providers); + } + + @Bean + public DaoAuthenticationProvider daoAuthenticationProvider() { + DaoAuthenticationProvider provider = new DaoAuthenticationProvider(passwordMatcher(), userDetailsService()); + return provider; + } + + @Bean + public PasswordMatcher passwordMatcher() { + return new PlainTextPasswordMatcher(); + } + + @Bean + public UserDetailsService userDetailsService() { + return new CustomUserDetailsService(memberRepository); + } +}
Java
๋„ต:) ๊ฐ€๋ณ€์ธ์ž๋กœ ์„ค์ •ํ•˜๋Š”๊ฒŒ ์‚ฌ์šฉํ•˜๋Š” ์ž…์žฅ์—์„œ ํ›จ์”ฌ ํŽธ๋ฆฌํ•  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ๐Ÿ‘ --- ์žฌ์—ฐ๋‹˜ ๋ง์”€์ด๋ž‘ ์‹œํ๋ฆฌํ‹ฐ ์ฝ”๋“œ ๋ณด๋ฉด์„œ ๋œฏ์–ด๋ณด๋‹ˆ ์‹ค์ œ ์‹œํ๋ฆฌํ‹ฐ๋ฅผ ์‚ฌ์šฉํ• ๋•Œ ์‚ฌ์šฉํ•˜๋˜ securityMatcher(), authorizeHttpRequests() ๋“ฑ์œผ๋กœ filterChain์ด ์„ ํƒ๋˜๊ณ  ์ธ๊ฐ€๋ฅผ ๋ฐœ์ƒ์‹œํ‚ค๋Š”๊ตฐ์š”! ์–ด๋–ค ๋ง์”€ํ•˜์‹œ๋Š”๊ฑด์ง€ ์•ฝ๊ฐ„ ๊ฐ์ด ์žกํžˆ๋Š”๊ฑฐ ๊ฐ™์Šต๋‹ˆ๋‹ค! ๐Ÿ‘ (์•„๋‹์ˆ˜๋„)
@@ -0,0 +1,79 @@ +package nextstep.security.filter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.AuthenticationManager; +import nextstep.security.authentication.UsernamePasswordAuthenticationToken; +import nextstep.security.core.context.SecurityContext; +import nextstep.security.core.context.SecurityContextHolder; +import nextstep.security.exception.AuthenticationException; +import nextstep.security.util.Base64Convertor; + +import java.io.IOException; + +public class BasicAuthFilter extends AbstractAuthProcessingFilter { + public static final String BASIC_HEADER_COLON = ":"; + public static final String BASIC_HEADER_COMMA = " "; + public static final String BASIC_HEADER_PREFIX = "Basic "; + public static final String AUTHORIZATION = "Authorization"; + + public BasicAuthFilter(final AuthenticationManager authenticationManager) { + super(authenticationManager); + } + + @Override + boolean match(final HttpServletRequest request) { + return existAuthorizationHeader(request); + } + + private boolean existAuthorizationHeader(final HttpServletRequest request) { + return request.getHeader(AUTHORIZATION) != null; + } + + @Override + public Authentication makeAuthentication(final HttpServletRequest request) { + String authorizationHeader = request.getHeader(AUTHORIZATION); + + if (isValidBasicAuthHeader(authorizationHeader)) { + throw new AuthenticationException(); + } + + String credentials = extractCredentials(authorizationHeader); + String[] usernameAndPassword = parseCredentials(credentials); + + return UsernamePasswordAuthenticationToken.unauthenticated(usernameAndPassword[0], usernameAndPassword[1]); + } + + private boolean isValidBasicAuthHeader(final String authorizationHeader) { + return authorizationHeader == null || !authorizationHeader.startsWith(BASIC_HEADER_PREFIX); + } + + private String extractCredentials(String authorizationHeader) { + String[] parts = authorizationHeader.split(BASIC_HEADER_COMMA); + if (parts.length != 2) { + throw new AuthenticationException(); + } + + return Base64Convertor.decode(parts[1]); + } + + private String[] parseCredentials(String decodedString) { + String[] usernameAndPassword = decodedString.split(BASIC_HEADER_COLON); + if (usernameAndPassword.length != 2) { + throw new AuthenticationException(); + } + + return usernameAndPassword; + } + + @Override + protected void successAuthentication(final HttpServletRequest request, final HttpServletResponse response, + final FilterChain filterChain) throws ServletException, IOException { + final SecurityContext context = SecurityContextHolder.getContext(); + final Authentication authentication = context.getAuthentication(); + authentication.getAuthorities().clear(); + } +}
Java
~~repository์— context์ €์žฅ์„ ์ธ์ฆํ•„ํ„ฐ ์™„๋ฃŒ ์‹œ์ ์ด ์•„๋‹Œ SecurityHolderFilter ์ข…๋ฃŒ์‹œ์— ํ•˜๋ฉด ๋  ๊ฑฐ๊ฐ™์Šต๋‹ˆ๋‹ค! ๐Ÿ‘~~ ์ถ”๊ฐ€๋กœ ์ธ์ฆํ•„ํ„ฐ์—์„œ SecurityContextHolder๋‚ด๋ถ€์— context๊ฐ€ ์žˆ๋‹ค๋ฉด ์ธ์ฆํ•„ํ„ฐ๋ฅผ ํ†ต๊ณผํ•˜๊ฒŒ ์ถ”๊ฐ€ํ•˜์˜€์Šต๋‹ˆ๋‹ค !
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
63