Dataset Viewer
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์ ๋ด๋ถ ํด๋์ค)
+
+
+
+### ์๊ตฌ ์ฌํญ
+- [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
+
+
+
+### ์๊ตฌ ์ฌํญ
+
+- [X] Authentication์ UsernamePasswordAuthenticationToken ๊ตฌํ
+- [X] ์ ๊ณต๋ AuthenticationManager๋ฅผ ๊ธฐ๋ฐ์ผ๋ก ProviderManager ๊ตฌํ
+- [X] ์ ๊ณต๋ AuthenticationProvider๋ฅผ ๊ธฐ๋ฐ์ผ๋ก DaoAuthenticationProvider ๊ตฌํ
+- [X] ๊ธฐ์กด ์ธ์ฆ ํํฐ์์ ์ธ์ฆ ๋ก์ง ๋ถ๋ฆฌ ๋ฐ AuthenticationManager๋ก ํตํฉ
+
+## 3๋จ๊ณ - SecurityContextHolder ์ ์ฉ
+- ์ธ์ฆ ์ฑ๊ณต ํ ์์ฑ๋ Authentication ๊ฐ์ฒด๋ฅผ ๊ธฐ์กด์ ์ธ์
๋ฐฉ์ ๋์ ์ค๋ ๋ ๋ก์ปฌ(Thread Local)์ ๋ณด๊ดํ๋๋ก ๋ณ๊ฒฝํ๋ค.
+- ๊ฐ ํํฐ์์ ์ค๋ ๋ ๋ก์ปฌ์ ๋ณด๊ด๋ ์ธ์ฆ ์ ๋ณด๋ฅผ ์ ๊ทผํ ์ ์๋๋ก SecurityContextHolder์ SecurityContext ๊ตฌ์กฐ๋ฅผ ๊ตฌํํ๋ค.
+
+
+
+### ์๊ตฌ์ฌํญ
+-[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