code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -0,0 +1,101 @@ +@use '../../../../styles/mixin.scss' as mixin; +@use '../../../../styles/color.scss' as clr; + +.feeds { + position: relative; + top: 77px; + width: 60%; + margin-bottom: 80px; + background: #fff; + + .top_menu { + @include mixin.flex($justify: space-between, $align: center); + height: 82px; + + span { + @include mixin.flex($align: center); + margin-left: 20px; + font-weight: bold; + + &:last-child { + margin-right: 22px; + color: #2a2a2a; + font-size: 35px; + } + + img { + width: 42px; + height: 42px; + border-radius: 50%; + margin-right: 20px; + } + } + } + + article { + img { + width: 100%; + height: 818px; + } + + .bottom_menu { + @include mixin.flex($align: center); + position: relative; + height: 62px; + + span > svg { + margin: 0 10px; + font-size: 32px; + color: #414141; + } + + span:last-child > svg { + position: absolute; + top: 15px; + right: 0; + } + + span:first-child > svg > path { + color: #eb4b59; + } + } + } + + .comments { + display: flex; + flex-direction: column; + + span { + padding-left: 10px; + } + } + + .add_comments { + position: absolute; + @include mixin.flex($justify: space-between, $align: center); + bottom: -62px; + width: 100%; + height: 62px; + border-top: 1px solid clr.$clr-border; + font-size: 14px; + + input { + width: 90%; + height: 50%; + margin-left: 15px; + border: none; + } + + button { + margin-right: 15px; + border: none; + color: clr.$clr-primary; + opacity: 0.5; + background: #fff; + + &.activated { + opacity: 1; + } + } + } +}
Unknown
class๋ช…์€ ์–ด๋–ค ํ˜•ํƒœ๊ฐ€ ์ข‹์„๊นŒ์š”?! ํ•ด๋‹น class๋ช…์€ '๋™์ž‘'์„ ๋‚˜ํƒ€๋‚ด๊ธฐ์— ํด๋ž˜์Šค ๋„ค์ž„๋ณด๋‹ค๋Š” ํ•จ์ˆ˜๋ช…์ฒ˜๋Ÿผ ๋А๊ปด์ง‘๋‹ˆ๋‹ค!
@@ -1,5 +1,98 @@ import React from 'react'; +import { useState, useEffect } from 'react'; +import { useNavigate } from 'react-router-dom'; +import './Login.scss'; -export default function Login() { - return <div>Hello, Hyeonze!</div>; -} +const Login = () => { + const [idInput, setIdInput] = useState(''); + const [pwInput, setPwInput] = useState(''); + const [isValidatedUser, setIsValidatedUser] = useState(false); + + const navigate = useNavigate(); + const changeIdInput = e => { + const { value } = e.target; + setIdInput(value); + }; + + const changePwInput = e => { + const { value } = e.target; + setPwInput(value); + }; + + useEffect(() => { + setIsValidatedUser(idInput.indexOf('@') !== -1 && pwInput.length > 4); + }, [idInput, pwInput]); + + // ๋ฉ”์ธ์œผ๋กœ ์ด๋™ํ•  ๋•Œ ๋กœ์ง + const goToMain = () => { + navigate('/main-hyeonze'); + }; + + // ํšŒ์›๊ฐ€์ž…์‹œ ์‚ฌ์šฉํ•  ๋กœ์ง + // const signup = () => { + // fetch('http://10.58.4.22:8000/users/signup', { + // method: 'POST', + // body: JSON.stringify({ + // email: idInput, + // password: pwInput, + // }), + // }) + // .then(response => response.json()) + // .then(result => { + // //console.log('๊ฒฐ๊ณผ: ', result.message) + // if (result.message === 'EMAIL_ALREADY_EXISTS') { + // console.log('Error : Duplicated'); + // } + // }); + // }; + + // ๋กœ๊ทธ์ธ์‹œ ์‚ฌ์šฉํ•  ๋กœ์ง + // const login = () => { + // fetch('http://10.58.4.22:8000/users/login', { + // method: 'POST', + // body: JSON.stringify({ + // email: idInput, + // password: pwInput, + // }), + // }) + // .then(response => response.json()) + // .then(result => { + // //console.log('๊ฒฐ๊ณผ: ', result.message) + // if (result.message === 'SUCCESS') { + // console.log('login SUCCESS'); + // } + // }); + // }; + + return ( + <div className="login"> + <div id="wrapper"> + <h1>westagram</h1> + <form className="login_form"> + <input + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + className="username" + onChange={changeIdInput} + /> + <input + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + className="userpassword" + onChange={changePwInput} + /> + <input + className={isValidatedUser ? 'activated' : ''} + disabled={!isValidatedUser} + type="button" + value="๋กœ๊ทธ์ธ" + onClick={goToMain} + /> + </form> + <p>๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</p> + </div> + </div> + ); +}; + +export default Login;
Unknown
- ๋ถˆํ•„์š”ํ•œ ์ฃผ์„์ฒ˜๋ฆฌ๋Š” ์‚ญ์ œํ•ด์ฃผ์„ธ์š”! - ๋”๋ถˆ์–ด์„œ className ์ž์ฒด๋ฅผ '์ƒ‰'์œผ๋กœ ์ง€์ •ํ•˜๋Š” ๊ฒƒ์€ ์ข‹์€ ๋„ค์ด๋ฐ์€ ์•„๋‹Œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์–ด๋–ค ๋„ค์ด๋ฐ์ด ์ ํ•ฉํ• ์ง€ ๊ณ ๋ฏผํ•˜์…”์„œ , ํ•ด๋‹น ์š”์†Œ๊ฐ€ ๋ฌด์—‡์ธ์ง€๋ฅผ ์ž˜ ๋‚˜ํƒ€๋‚ด๋Š” ๋„ค์ด๋ฐ์œผ๋กœ ์ˆ˜์ •ํ•ด์ฃผ์„ธ์š”. - ํ”Œ๋Ÿฌ์Šค! ์—ฌ๊ธฐ์—๋„ ์‚ฌ์šฉํ•˜์ง€ ์•Š์•„๋„ ๋˜๋Š” ์‚ผํ•ญ์—ฐ์‚ฌ์ž๊ฐ€ ์ˆจ์–ด์žˆ๋„ค์š”! ํ™•์ธํ•ด์ฃผ์„ธ์š”
@@ -0,0 +1,101 @@ +@use '../../../../styles/mixin.scss' as mixin; +@use '../../../../styles/color.scss' as clr; + +.feeds { + position: relative; + top: 77px; + width: 60%; + margin-bottom: 80px; + background: #fff; + + .top_menu { + @include mixin.flex($justify: space-between, $align: center); + height: 82px; + + span { + @include mixin.flex($align: center); + margin-left: 20px; + font-weight: bold; + + &:last-child { + margin-right: 22px; + color: #2a2a2a; + font-size: 35px; + } + + img { + width: 42px; + height: 42px; + border-radius: 50%; + margin-right: 20px; + } + } + } + + article { + img { + width: 100%; + height: 818px; + } + + .bottom_menu { + @include mixin.flex($align: center); + position: relative; + height: 62px; + + span > svg { + margin: 0 10px; + font-size: 32px; + color: #414141; + } + + span:last-child > svg { + position: absolute; + top: 15px; + right: 0; + } + + span:first-child > svg > path { + color: #eb4b59; + } + } + } + + .comments { + display: flex; + flex-direction: column; + + span { + padding-left: 10px; + } + } + + .add_comments { + position: absolute; + @include mixin.flex($justify: space-between, $align: center); + bottom: -62px; + width: 100%; + height: 62px; + border-top: 1px solid clr.$clr-border; + font-size: 14px; + + input { + width: 90%; + height: 50%; + margin-left: 15px; + border: none; + } + + button { + margin-right: 15px; + border: none; + color: clr.$clr-primary; + opacity: 0.5; + background: #fff; + + &.activated { + opacity: 1; + } + } + } +}
Unknown
์ด๋ ‡๊ฒŒ ๊ฐ ์š”์†Œ์— background color๋ฅผ ๊ฐ๊ฐ ๋‹ค ๋„ฃ์–ด์ฃผ์‹  ์ด์œ ๊ฐ€ ์žˆ์œผ์‹ค๊นŒ์š”?
@@ -0,0 +1,92 @@ +{ + "stories": [ + { "imgUrl": "images/joonyoung/stories/story1.jpg", "username": "Enna" }, + { "imgUrl": "images/joonyoung/stories/story2.jpg", "username": "Jesy" }, + { "imgUrl": "images/joonyoung/stories/story3.jpg", "username": "Denial" }, + { "imgUrl": "images/joonyoung/stories/story4.jpg", "username": "Meow" }, + { + "imgUrl": "images/joonyoung/stories/story5.jpg", + "username": "Christina" + }, + { "imgUrl": "images/joonyoung/stories/story6.jpg", "username": "Mally" }, + { "imgUrl": "images/joonyoung/stories/story7.jpg", "username": "Karel" }, + { "imgUrl": "images/joonyoung/stories/story8.jpg", "username": "Bred" }, + { "imgUrl": "images/joonyoung/stories/story9.jpg", "username": "Andrew" }, + { "imgUrl": "images/joonyoung/stories/story10.jpg", "username": "Emily" } + ], + "otherProfileInfos": [ + { + "id": 1, + "username": "wecode28๊ธฐ", + "description": "wecode๋‹˜์™ธ 36๋ช…์ด follow" + }, + { + "id": 2, + "username": "Younha", + "description": "Enna Kim์™ธ 10๋ช…์ด follow" + }, + { + "id": 3, + "username": "wework", + "description": "wecode28๋‹˜์™ธ 236๋ช…์ด follow" + } + ], + "feed": [ + { + "id": 1, + "feedUpLoader": "Enna", + "uploaderProfileImg": "./images/joonyoung/stories/story1.jpg", + "uploaderInfo": "Enna's Feed icon", + "carouselImages": [ + "./images/joonyoung/feed/feed1/pexels-fauxels-3184291.jpg", + "./images/joonyoung/feed/feed1/pexels-fauxels-3184302.jpg", + "./images/joonyoung/feed/feed1/pexels-fauxels-3184433.jpg", + "./images/joonyoung/feed/feed1/pexels-min-an-853168.jpg", + "./images/joonyoung/feed/feed1/pexels-this-is-zun-1116302.jpg" + ], + "likes": 1129, + "comments": [ + { + "id": 1, + "user": "28๊ธฐ ์–‘๋Œ€์˜๋‹˜", + "comment": "์—ฌ๋Ÿฌ๋ถ„ ์น˜ํ‚จ๊ณ„ ์“ฐ์…”์•ผ ํ•ฉ๋‹ˆ๋‹ค..!!ย ๐Ÿ‘€ ๐Ÿ‘€" + }, + { + "id": 2, + "user": "28๊ธฐ ์ด์•„์˜๋‹˜", + "comment": "๋Œ€์˜๋‹˜๋„ ์•ˆ ์“ฐ์…จ์ž–์•„์š”?! ๐Ÿคญ" + }, + { + "id": 3, + "user": "28๊ธฐ ๋ฐ•์œค๊ตญ๋‹˜", + "comment": "๐ŸŽธ ๐ŸŽธ ๐ŸŽธ (์‹ ๊ณก ํ™๋ณด์ค‘)" + } + ] + }, + { + "id": 2, + "feedUpLoader": "James", + "uploaderProfileImg": "./images/joonyoung/stories/story2.jpg", + "uploaderInfo": "It's jesy!", + "carouselImages": [ + "./images/joonyoung/feed/feed2/handtohand.jpg", + "./images/joonyoung/feed/feed2/branch.jpg", + "./images/joonyoung/feed/feed2/pexels-te-lensfix-1371360.jpg", + "./images/joonyoung/feed/feed2/pexels-victor-freitas-803105.jpg" + ], + "likes": 1129, + "comments": [ + { + "id": 1, + "user": "๋ฉ˜ํ†  ๊น€INTP๋‹˜", + "comment": "(์•ˆ๊ฒฝ์„ ์น˜์ผœ ์˜ฌ๋ฆฌ๋ฉฐ) git branch merge" + }, + { + "id": 2, + "user": "28๊ธฐ ์ดESTJ๋‹˜", + "comment": "์•„๋‹ˆ ๊ณ„ํš์„ ์•ˆ์งœ๊ณ  ์—ฌํ–‰์„ ๊ฐ„๋‹ค๊ณ ?" + } + ] + } + ] +}
Unknown
mockData king ์ค€์˜๋‹˜๐Ÿ‘ ์ •๋ง ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ์„ธ๋ถ€ ๋‚ด์šฉ์€ ์ž„์˜๋กœ ๋ณ€๊ฒฝํ•œ ํ›„, ๋ฐ์ดํ„ฐ์˜ ํ˜•์‹์ข€ ๋นŒ๋ ค๋‹ค ์“ฐ๊ฒ ์Šต๋‹ˆ๋‹ค ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,14 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="UTF-8" /> + <link rel="icon" type="image/svg+xml" href="/vite.svg" /> + <meta name="viewport" content="width=device-width, initial-scale=1.0" /> + <title>react-shopping-products</title> + <script type="module" crossorigin src="/react-shopping-products/dist/assets/index-B5NHo3G9.js"></script> + <link rel="stylesheet" crossorigin href="/react-shopping-products/dist/assets/index-BlzNY9oW.css"> + </head> + <body> + <div id="root"></div> + </body> +</html>
Unknown
dist ํด๋”๊ฐ€ git ignore๋˜์ง€ ์•Š์•˜๊ตฐ์šฉ
@@ -0,0 +1,10 @@ +/** + * generateBasicToken - Basic auth๋ฅผ ์œ„ํ•œ ํ† ํฐ์„ ๋งŒ๋“œ๋Š” ํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค. + * @param {string} userId - USERNAME์ž…๋‹ˆ๋‹ค. + * @param {string} userPassword - PASSWORD์ž…๋‹ˆ๋‹ค. + * @returns {string} + */ +export function generateBasicToken(userId: string, userPassword: string): string { + const token = btoa(`${userId}:${userPassword}`); + return `Basic ${token}`; +}
TypeScript
์„ฌ์„ธํ•œ jsdocs ๐Ÿ‘๐Ÿ‘๐Ÿ‘๐Ÿ‘
@@ -0,0 +1,95 @@ +import { CartItemType, ProductType } from '../types'; +import { generateBasicToken } from './auth'; + +const API_URL = import.meta.env.VITE_API_URL; +const USER_ID = import.meta.env.VITE_USER_ID; +const USER_PASSWORD = import.meta.env.VITE_USER_PASSWORD; + +/** + * ๊ณตํ†ต ์š”์ฒญ์„ ์ฒ˜๋ฆฌํ•˜๋Š” ํ•จ์ˆ˜ + * @param {string} endpoint - API endpoint + * @param {RequestInit} options - fetch options + * @returns {Response} - fetch response + */ +async function makeRequest(endpoint: string, options: RequestInit): Promise<Response> { + const token = generateBasicToken(USER_ID, USER_PASSWORD); + + const response = await fetch(`${API_URL}${endpoint}`, { + ...options, + headers: { + ...options.headers, + Authorization: token, + 'Content-Type': 'application/json', + }, + }); + + if (!response.ok) { + throw new Error(`Failed to ${options.method?.toLowerCase()} ${endpoint}`); + } + + return response; +} + +interface FetchProductsParams { + category?: string; + page?: number; + size?: number; + sort?: string; +} + +/** + * fetchCartItems - API์—์„œ ์ƒํ’ˆ ๋ชฉ๋ก์„ fetchํ•ฉ๋‹ˆ๋‹ค. + * @returns {Promise<ProductType[]>} + */ +export async function fetchProducts(params: FetchProductsParams = {}): Promise<ProductType[]> { + const queryString = Object.entries(params) + .map(([key, value]) => { + if (key === 'category' && value === 'all') { + return; + } else { + return `${key}=${value}`; + } + }) + .join('&'); + const response = await makeRequest(`/products?${queryString}`, { + method: 'GET', + }); + const data = await response.json(); + + return data.content; +} + +/** + * addCartItem - ์„ ํƒํ•œ ์ƒํ’ˆ์„ ์žฅ๋ฐ”๊ตฌ๋‹ˆ์— ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค. + * @returns {Promise<void>} + */ +export async function addCartItem(productId: number): Promise<void> { + await makeRequest('/cart-items', { + method: 'POST', + body: JSON.stringify({ productId }), + }); +} + +/** + * fetchCartItem - API์—์„œ ์žฅ๋ฐ”๊ตฌ๋‹ˆ ๋ชฉ๋ก์„ fetchํ•ฉ๋‹ˆ๋‹ค. + * @returns {Promise<CartItemType[]>} + */ +export async function fetchCartItem(): Promise<CartItemType[]> { + const response = await makeRequest('/cart-items?page=0&size=100', { + method: 'GET', + }); + + const data = await response.json(); + + return data.content; +} + +/** + * deleteCartItem - ์„ ํƒํ•œ ์ƒํ’ˆ์„ ์žฅ๋ฐ”๊ตฌ๋‹ˆ์—์„œ ์‚ญ์ œํ•ฉ๋‹ˆ๋‹ค. + * @returns {Promise<void>} + */ +export async function deleteCartItem(cartItemId: number): Promise<void> { + await makeRequest(`/cart-items/${cartItemId}`, { + method: 'DELETE', + }); +}
TypeScript
๊ณตํ†ต ๋กœ์ง์„ ๋ฌถ์–ด์ฃผ๋Š” ๊ฒƒ ๋„ˆ๋ฌด ์ข‹์Šต๋‹ˆ๋‹ค~!
@@ -0,0 +1,95 @@ +import { CartItemType, ProductType } from '../types'; +import { generateBasicToken } from './auth'; + +const API_URL = import.meta.env.VITE_API_URL; +const USER_ID = import.meta.env.VITE_USER_ID; +const USER_PASSWORD = import.meta.env.VITE_USER_PASSWORD; + +/** + * ๊ณตํ†ต ์š”์ฒญ์„ ์ฒ˜๋ฆฌํ•˜๋Š” ํ•จ์ˆ˜ + * @param {string} endpoint - API endpoint + * @param {RequestInit} options - fetch options + * @returns {Response} - fetch response + */ +async function makeRequest(endpoint: string, options: RequestInit): Promise<Response> { + const token = generateBasicToken(USER_ID, USER_PASSWORD); + + const response = await fetch(`${API_URL}${endpoint}`, { + ...options, + headers: { + ...options.headers, + Authorization: token, + 'Content-Type': 'application/json', + }, + }); + + if (!response.ok) { + throw new Error(`Failed to ${options.method?.toLowerCase()} ${endpoint}`); + } + + return response; +} + +interface FetchProductsParams { + category?: string; + page?: number; + size?: number; + sort?: string; +} + +/** + * fetchCartItems - API์—์„œ ์ƒํ’ˆ ๋ชฉ๋ก์„ fetchํ•ฉ๋‹ˆ๋‹ค. + * @returns {Promise<ProductType[]>} + */ +export async function fetchProducts(params: FetchProductsParams = {}): Promise<ProductType[]> { + const queryString = Object.entries(params) + .map(([key, value]) => { + if (key === 'category' && value === 'all') { + return; + } else { + return `${key}=${value}`; + } + }) + .join('&'); + const response = await makeRequest(`/products?${queryString}`, { + method: 'GET', + }); + const data = await response.json(); + + return data.content; +} + +/** + * addCartItem - ์„ ํƒํ•œ ์ƒํ’ˆ์„ ์žฅ๋ฐ”๊ตฌ๋‹ˆ์— ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค. + * @returns {Promise<void>} + */ +export async function addCartItem(productId: number): Promise<void> { + await makeRequest('/cart-items', { + method: 'POST', + body: JSON.stringify({ productId }), + }); +} + +/** + * fetchCartItem - API์—์„œ ์žฅ๋ฐ”๊ตฌ๋‹ˆ ๋ชฉ๋ก์„ fetchํ•ฉ๋‹ˆ๋‹ค. + * @returns {Promise<CartItemType[]>} + */ +export async function fetchCartItem(): Promise<CartItemType[]> { + const response = await makeRequest('/cart-items?page=0&size=100', { + method: 'GET', + }); + + const data = await response.json(); + + return data.content; +} + +/** + * deleteCartItem - ์„ ํƒํ•œ ์ƒํ’ˆ์„ ์žฅ๋ฐ”๊ตฌ๋‹ˆ์—์„œ ์‚ญ์ œํ•ฉ๋‹ˆ๋‹ค. + * @returns {Promise<void>} + */ +export async function deleteCartItem(cartItemId: number): Promise<void> { + await makeRequest(`/cart-items/${cartItemId}`, { + method: 'DELETE', + }); +}
TypeScript
์žฅ๋ฐ”๊ตฌ๋‹ˆ์— 100๊ฐœ ๋„˜๊ฒŒ ๋‹ด์„ ์ˆ˜ ์žˆ๋Š” case๊ฐ€ ์กด์žฌํ•  ๊ฒƒ ๊ฐ™์•„์š”~!
@@ -0,0 +1,50 @@ +.loaderContainer { + height: 60px; + display: flex; + justify-content: center; + align-items: center; +} + +.loader { + width: 60px; + display: flex; + justify-content: space-evenly; +} + +.ball { + list-style: none; + width: 12px; + height: 12px; + border-radius: 50%; + background-color: black; +} + +.ball:nth-child(1) { + animation: bounce1 0.4s ease-in-out infinite; +} + +@keyframes bounce1 { + 50% { + transform: translateY(-18px); + } +} + +.ball:nth-child(2) { + animation: bounce2 0.4s ease-in-out 0.2s infinite; +} + +@keyframes bounce2 { + 50% { + transform: translateY(-18px); + } +} + +.ball:nth-child(3) { + animation: bounce3 0.4s ease-in-out 0.4s infinite; +} + +@keyframes bounce3 { + 50% { + transform: translateY(-18px); + } +}
Unknown
๊ท€์—ฌ์šด ์• ๋‹ˆ๋ฉ”์ด์…˜์„ ๋งŒ๋“ค์—ˆ๊ตฐ์šฉ ๐Ÿš€๐Ÿš€๐Ÿš€
@@ -0,0 +1,15 @@ +export const productCategories = { + all: '์ „์ฒด', + fashion: 'ํŒจ์…˜', + beverage: '์Œ๋ฃŒ', + electronics: '์ „์ž์ œํ’ˆ', + kitchen: '์ฃผ๋ฐฉ์šฉํ’ˆ', + fitness: 'ํ”ผํŠธ๋‹ˆ์Šค', + books: '๋„์„œ', +} as const; + +export const sortOptions = { priceAsc: '๋‚ฎ์€ ๊ฐ€๊ฒฉ์ˆœ', priceDesc: '๋†’์€ ๊ฐ€๊ฒฉ์ˆœ' } as const; + +export const FIRST_FETCH_PAGE = 0; +export const FIRST_FETCH_SIZE = 20; +export const AFTER_FETCH_SIZE = 4;
TypeScript
์ƒ์ˆ˜ํ™” ๐Ÿ‘๐Ÿ‘๐Ÿ‘
@@ -0,0 +1,32 @@ +import React, { createContext, useState, useCallback, ReactNode } from 'react'; +import ErrorToast from '../components/ErrorToast/ErrorToast'; + +export interface ToastContextType { + showToast: (message: string) => void; +} + +export const ToastContext = createContext<ToastContextType | undefined>(undefined); + +interface ToastProviderProps { + children: ReactNode; +} + +export const ToastProvider: React.FC<ToastProviderProps> = ({ children }) => { + const [isOpen, setIsOpen] = useState(false); + const [message, setMessage] = useState(''); + + const showToast = useCallback((message: string) => { + setMessage(message); + setIsOpen(true); + setTimeout(() => { + setIsOpen(false); + }, 3000); + }, []); + + return ( + <ToastContext.Provider value={{ showToast }}> + {children} + {isOpen && <ErrorToast message={message} />} + </ToastContext.Provider> + ); +};
Unknown
๋ณ„๋„์˜ Provider๋กœ ๋งŒ๋“ค์–ด ์ค€ ๊ฒƒ ๋„ˆ๋ฌด ์ข‹๋„ค์š”
@@ -0,0 +1,95 @@ +import { CartItemType, ProductType } from '../types'; +import { generateBasicToken } from './auth'; + +const API_URL = import.meta.env.VITE_API_URL; +const USER_ID = import.meta.env.VITE_USER_ID; +const USER_PASSWORD = import.meta.env.VITE_USER_PASSWORD; + +/** + * ๊ณตํ†ต ์š”์ฒญ์„ ์ฒ˜๋ฆฌํ•˜๋Š” ํ•จ์ˆ˜ + * @param {string} endpoint - API endpoint + * @param {RequestInit} options - fetch options + * @returns {Response} - fetch response + */ +async function makeRequest(endpoint: string, options: RequestInit): Promise<Response> { + const token = generateBasicToken(USER_ID, USER_PASSWORD); + + const response = await fetch(`${API_URL}${endpoint}`, { + ...options, + headers: { + ...options.headers, + Authorization: token, + 'Content-Type': 'application/json', + }, + }); + + if (!response.ok) { + throw new Error(`Failed to ${options.method?.toLowerCase()} ${endpoint}`); + } + + return response; +} + +interface FetchProductsParams { + category?: string; + page?: number; + size?: number; + sort?: string; +} + +/** + * fetchCartItems - API์—์„œ ์ƒํ’ˆ ๋ชฉ๋ก์„ fetchํ•ฉ๋‹ˆ๋‹ค. + * @returns {Promise<ProductType[]>} + */ +export async function fetchProducts(params: FetchProductsParams = {}): Promise<ProductType[]> { + const queryString = Object.entries(params) + .map(([key, value]) => { + if (key === 'category' && value === 'all') { + return; + } else { + return `${key}=${value}`; + } + }) + .join('&'); + const response = await makeRequest(`/products?${queryString}`, { + method: 'GET', + }); + const data = await response.json(); + + return data.content; +} + +/** + * addCartItem - ์„ ํƒํ•œ ์ƒํ’ˆ์„ ์žฅ๋ฐ”๊ตฌ๋‹ˆ์— ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค. + * @returns {Promise<void>} + */ +export async function addCartItem(productId: number): Promise<void> { + await makeRequest('/cart-items', { + method: 'POST', + body: JSON.stringify({ productId }), + }); +} + +/** + * fetchCartItem - API์—์„œ ์žฅ๋ฐ”๊ตฌ๋‹ˆ ๋ชฉ๋ก์„ fetchํ•ฉ๋‹ˆ๋‹ค. + * @returns {Promise<CartItemType[]>} + */ +export async function fetchCartItem(): Promise<CartItemType[]> { + const response = await makeRequest('/cart-items?page=0&size=100', { + method: 'GET', + }); + + const data = await response.json(); + + return data.content; +} + +/** + * deleteCartItem - ์„ ํƒํ•œ ์ƒํ’ˆ์„ ์žฅ๋ฐ”๊ตฌ๋‹ˆ์—์„œ ์‚ญ์ œํ•ฉ๋‹ˆ๋‹ค. + * @returns {Promise<void>} + */ +export async function deleteCartItem(cartItemId: number): Promise<void> { + await makeRequest(`/cart-items/${cartItemId}`, { + method: 'DELETE', + }); +}
TypeScript
๋งž์•„์š”... ์ž„์‹œ๋ฐฉํŽธ์ด์—ˆ๋Š”๋ฐ ๊ทธ๋ƒฅ ๊นŒ๋จน๊ณ  ๋„˜์–ด๊ฐ”๋„ค์š” ใ…œใ…œ
@@ -0,0 +1,95 @@ +import { CartItemType, ProductType } from '../types'; +import { generateBasicToken } from './auth'; + +const API_URL = import.meta.env.VITE_API_URL; +const USER_ID = import.meta.env.VITE_USER_ID; +const USER_PASSWORD = import.meta.env.VITE_USER_PASSWORD; + +/** + * ๊ณตํ†ต ์š”์ฒญ์„ ์ฒ˜๋ฆฌํ•˜๋Š” ํ•จ์ˆ˜ + * @param {string} endpoint - API endpoint + * @param {RequestInit} options - fetch options + * @returns {Response} - fetch response + */ +async function makeRequest(endpoint: string, options: RequestInit): Promise<Response> { + const token = generateBasicToken(USER_ID, USER_PASSWORD); + + const response = await fetch(`${API_URL}${endpoint}`, { + ...options, + headers: { + ...options.headers, + Authorization: token, + 'Content-Type': 'application/json', + }, + }); + + if (!response.ok) { + throw new Error(`Failed to ${options.method?.toLowerCase()} ${endpoint}`); + } + + return response; +} + +interface FetchProductsParams { + category?: string; + page?: number; + size?: number; + sort?: string; +} + +/** + * fetchCartItems - API์—์„œ ์ƒํ’ˆ ๋ชฉ๋ก์„ fetchํ•ฉ๋‹ˆ๋‹ค. + * @returns {Promise<ProductType[]>} + */ +export async function fetchProducts(params: FetchProductsParams = {}): Promise<ProductType[]> { + const queryString = Object.entries(params) + .map(([key, value]) => { + if (key === 'category' && value === 'all') { + return; + } else { + return `${key}=${value}`; + } + }) + .join('&'); + const response = await makeRequest(`/products?${queryString}`, { + method: 'GET', + }); + const data = await response.json(); + + return data.content; +} + +/** + * addCartItem - ์„ ํƒํ•œ ์ƒํ’ˆ์„ ์žฅ๋ฐ”๊ตฌ๋‹ˆ์— ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค. + * @returns {Promise<void>} + */ +export async function addCartItem(productId: number): Promise<void> { + await makeRequest('/cart-items', { + method: 'POST', + body: JSON.stringify({ productId }), + }); +} + +/** + * fetchCartItem - API์—์„œ ์žฅ๋ฐ”๊ตฌ๋‹ˆ ๋ชฉ๋ก์„ fetchํ•ฉ๋‹ˆ๋‹ค. + * @returns {Promise<CartItemType[]>} + */ +export async function fetchCartItem(): Promise<CartItemType[]> { + const response = await makeRequest('/cart-items?page=0&size=100', { + method: 'GET', + }); + + const data = await response.json(); + + return data.content; +} + +/** + * deleteCartItem - ์„ ํƒํ•œ ์ƒํ’ˆ์„ ์žฅ๋ฐ”๊ตฌ๋‹ˆ์—์„œ ์‚ญ์ œํ•ฉ๋‹ˆ๋‹ค. + * @returns {Promise<void>} + */ +export async function deleteCartItem(cartItemId: number): Promise<void> { + await makeRequest(`/cart-items/${cartItemId}`, { + method: 'DELETE', + }); +}
TypeScript
๊ทธ๋Ÿฐ๋ฐ.. ์ด๋ฒˆ ์žฅ๋ฐ”๊ตฌ๋‹ˆ api๋Š” 20๊ฐœ๋งŒ ๋‹ด์„ ์ˆ˜ ์žˆ๊ฒŒ ๋งŒ๋“ค์–ด์ ธ์žˆ๋”๋ผ๊ตฌ์š”.. ์ง€๊ธˆ api ๊ตฌํ˜„์‚ฌํ•ญ์— ๋งž์ถœ์ง€, ์•„๋‹ˆ๋ฉด ๋ฏธ๋ž˜์˜ ๋ณ€๊ฒฝ์—๋„ ์šฉ์ดํ•˜๊ฒŒ ์ฝ”๋“œ๋ฅผ ๋ฐ”๊ฟ€์ง€๋Š” ์ƒ๊ฐํ•ด ๋ด์•ผํ•  ๋ฌธ์ œ์ธ ๊ฒƒ ๊ฐ™์•„์š”. ์ด ๋ถ€๋ถ„์„ ๋ฐ”๊ฟ”์•ผ ํ•œ๋‹ค๋ฉด ์œ„์˜ >if (key === 'category' && value === 'all') ์ด ์ฝ”๋“œ์—์„œ๋„ default๋กœ ๋“ค์–ด๊ฐˆ ์ˆ˜ ์žˆ๋Š” sort=id,asc๋„ ์ƒ๊ฐํ•ด๋ด์•ผ ํ•  ๊ฒƒ ๊ฐ™๊ณ ์š”
@@ -0,0 +1,21 @@ +import { SelectHTMLAttributes, PropsWithChildren } from 'react'; +import styles from './Select.module.css'; + +interface Props extends PropsWithChildren<SelectHTMLAttributes<HTMLSelectElement>> { + options: Record<string, string>; +} + +const Select = ({ options, defaultValue, children, ...props }: Props) => { + return ( + <select {...props} className={styles.selectContainer} defaultValue={defaultValue}> + {children} + {Object.keys(options).map((option) => ( + <option key={option} value={option}> + {options[option]} + </option> + ))} + </select> + ); +}; + +export default Select;
Unknown
entries๋ผ๋Š” ํ•จ์ˆ˜๋„ ์žˆ์œผ๋‹ˆ ์ฐพ์•„๋ณด์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”..! ``` js Object.entries(options).map([optionEn,optionKo])=>{ ... } ```
@@ -1 +1,60 @@ # spring-security-authentication + +## 1๋‹จ๊ณ„ - SecurityFilterChain ์ ์šฉ + +์ธํ„ฐ์…‰ํ„ฐ๋กœ ๊ตฌํ˜„ํ•œ ์ธ์ฆ ๋กœ์ง์„ ํ•„ํ„ฐ ํ˜•ํƒœ๋กœ ๋ณ€ํ˜•ํ•œ๋‹ค. +์ธ์ฆ ๋กœ์ง์ด ๋‹ด๊ธด ํ•„ํ„ฐ๋ฅผ ๋ฐ”๋กœ ์„œ๋ธ”๋ฆฟ ํ•„ํ„ฐ๋กœ ๋“ฑ๋กํ•˜์ง€ ์•Š๊ณ  ์•„๋ž˜ ์ด๋ฏธ์ง€๋ฅผ ์ฐธ๊ณ ํ•˜์—ฌ ๋ณ„๋„์˜ ํ•„ํ„ฐ ์ฒด์ธ์„ ๊ตฌ์ถ•ํ•˜์—ฌ ๊ตฌํ˜„ํ•œ๋‹ค. +์ฃผ์š” ํด๋ž˜์Šค: DelegatingFilterProxy, FilterChainProxy, SecurityFilterChain, DefaultSecurityFilterChain, VirtualFilterChain(FilterChainProxy์˜ ๋‚ด๋ถ€ ํด๋ž˜์Šค) + +![SecurityFilterChain.png](docs-img/SecurityFilterChain.png) + +### ์š”๊ตฌ ์‚ฌํ•ญ +- [X] ๊ธฐ์กด Interceptor ์ธ์ฆ ๋กœ์ง ๋ณ€ํ™˜ + - ์ œ๊ณต๋œ Interceptor ๊ธฐ๋ฐ˜ ์ธ์ฆ ๋กœ์ง์„ Filter๋กœ ๋ณ€ํ™˜ + - ๋ณ€ํ™˜๋œ Filter๋Š” HttpServletRequest์™€ HttpServletResponse๋ฅผ ์ฒ˜๋ฆฌํ•˜๋ฉฐ, ์ธ์ฆ ์—ฌ๋ถ€๋ฅผ ๊ฒฐ์ • + - ์š”์ฒญ์ด ์ธ์ฆ๋˜์ง€ ์•Š์€ ๊ฒฝ์šฐ, ์ ์ ˆํ•œ HTTP ์ƒํƒœ ์ฝ”๋“œ(์˜ˆ: 401 Unauthorized) ๋ฐ˜ํ™˜ + - ์ธ์ฆ๋œ ์‚ฌ์šฉ์ž ์ •๋ณด๋Š” ์š”์ฒญ ๊ฐ์ฒด์— ์ถ”๊ฐ€ํ•˜์—ฌ ์ดํ›„ ํ•„ํ„ฐ์—์„œ ์ ‘๊ทผ ๊ฐ€๋Šฅํ•˜๋„๋ก ์„ค์ • +- [X] DelegatingFilterProxy ์„ค์ • + - Spring Bean์œผ๋กœ DelegatingFilterProxy๋ฅผ ๋“ฑ๋กํ•˜๊ณ  ์ด๋ฅผ ํ†ตํ•ด FilterChainProxy๋ฅผ ํ˜ธ์ถœํ•˜๋„๋ก ์„ค์ • + - DelegatingFilterProxy๋Š” Servlet ์ปจํ…Œ์ด๋„ˆ์˜ Filter์™€ Spring ์ปจํ…์ŠคํŠธ๋ฅผ ์—ฐ๊ฒฐ +- [X] FilterChainProxy ๊ตฌํ˜„ + - FilterChainProxy๋Š” ์š”์ฒญ URI์— ๋”ฐ๋ผ ์ ์ ˆํ•œ SecurityFilterChain์„ ์„ ํƒํ•˜์—ฌ ์‹คํ–‰ + - SecurityFilterChain์€ Filter ๋ฆฌ์ŠคํŠธ๋ฅผ ํฌํ•จํ•˜๋ฉฐ ์š”์ฒญ์„ ์ฒ˜๋ฆฌ +- [X] SecurityFilterChain ๋ฆฌํŒฉํ„ฐ๋ง + - ๊ฐ SecurityFilterChain์€ ์—ญํ• ์— ๋”ฐ๋ผ ๋‹ค๋ฅธ ํ•„ํ„ฐ ์„ธํŠธ๋ฅผ ๊ด€๋ฆฌ + - ์ธ์ฆ(Authentication) ํ•„ํ„ฐ์™€ ๊ถŒํ•œ(Authorization) ํ•„ํ„ฐ๋ฅผ ํฌํ•จํ•˜๋„๋ก ๊ตฌ์„ฑ + +## 2๋‹จ๊ณ„ - AuthenticationManager ์ ์šฉ + +๋‹ค์–‘ํ•œ ์ธ์ฆ ๋ฐฉ์‹์„ ์ฒ˜๋ฆฌํ•˜๊ธฐ ์œ„ํ•ด AuthenticationManager๋ฅผ ํ™œ์šฉํ•˜์—ฌ ์ธ์ฆ ๊ณผ์ •์„ ์ถ”์ƒํ™”ํ•œ๋‹ค. +๊ธฐ์กด์˜ ์ธ์ฆ ๋กœ์ง์„ ๋ถ„๋ฆฌํ•˜๊ณ , ์ธ์ฆ ๋ฐฉ์‹์„ ์œ ์—ฐํ•˜๊ฒŒ ํ™•์žฅ ๊ฐ€๋Šฅํ•˜๋„๋ก ๊ตฌ์กฐํ™”ํ•œ๋‹ค. +์ฃผ์š” ํด๋ž˜์Šค: AuthenticationManager, ProviderManager, AuthenticationProvider, DaoAuthenticationProvider + +![AuthenticationManager.png](docs-img/AuthenticationManager.png) + +### ์š”๊ตฌ ์‚ฌํ•ญ + +- [X] Authentication์™€ UsernamePasswordAuthenticationToken ๊ตฌํ˜„ +- [X] ์ œ๊ณต๋œ AuthenticationManager๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ProviderManager ๊ตฌํ˜„ +- [X] ์ œ๊ณต๋œ AuthenticationProvider๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ DaoAuthenticationProvider ๊ตฌํ˜„ +- [X] ๊ธฐ์กด ์ธ์ฆ ํ•„ํ„ฐ์—์„œ ์ธ์ฆ ๋กœ์ง ๋ถ„๋ฆฌ ๋ฐ AuthenticationManager๋กœ ํ†ตํ•ฉ + +## 3๋‹จ๊ณ„ - SecurityContextHolder ์ ์šฉ +- ์ธ์ฆ ์„ฑ๊ณต ํ›„ ์ƒ์„ฑ๋œ Authentication ๊ฐ์ฒด๋ฅผ ๊ธฐ์กด์˜ ์„ธ์…˜ ๋ฐฉ์‹ ๋Œ€์‹  ์Šค๋ ˆ๋“œ ๋กœ์ปฌ(Thread Local)์— ๋ณด๊ด€ํ•˜๋„๋ก ๋ณ€๊ฒฝํ•œ๋‹ค. +- ๊ฐ ํ•„ํ„ฐ์—์„œ ์Šค๋ ˆ๋“œ ๋กœ์ปฌ์— ๋ณด๊ด€๋œ ์ธ์ฆ ์ •๋ณด๋ฅผ ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋„๋ก SecurityContextHolder์™€ SecurityContext ๊ตฌ์กฐ๋ฅผ ๊ตฌํ˜„ํ•œ๋‹ค. + +![SecurityContextHolder.png](docs-img/SecurityContextHolder.png) + +### ์š”๊ตฌ์‚ฌํ•ญ +-[X] SecurityContext ๋ฐ SecurityContextHolder ์ž‘์„ฑ +-[X] BasicAuthenticationFilter์—์„œ SecurityContextHolder ํ™œ์šฉ +-[X] ๊ธฐ์กด ์„ธ์…˜ ๋ฐฉ์‹์—์„œ ์Šค๋ ˆ๋“œ ๋กœ์ปฌ ๋ฐฉ์‹์œผ๋กœ ์ธ์ฆ ์ •๋ณด ๊ด€๋ฆฌ ๋ณ€๊ฒฝ + +## 4๋‹จ๊ณ„ - SecurityContextHolderFilter ๊ตฌํ˜„ +* ์„ธ์…˜์— ๋ณด๊ด€๋œ ์ธ์ฆ ์ •๋ณด๋ฅผ SecurityContextHolder๋กœ ์˜ฎ๊ธฐ๊ธฐ ์œ„ํ•œ SecurityContextHolderFilter๋ฅผ ๊ตฌํ˜„ํ•œ๋‹ค. + +### ์š”๊ตฌ ์‚ฌํ•ญ +- [X] SecurityContextRepository ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ HttpSessionSecurityContextRepository ๊ตฌํ˜„ +- [X] SecurityContextHolderFilter ์ž‘์„ฑ ๋ฐ ํ•„ํ„ฐ ์ฒด์ธ์— ๋“ฑ๋ก +- [X] login_after_members ํ…Œ์ŠคํŠธ๋กœ ๋™์ž‘ ๊ฒ€์ฆ +
Unknown
์š”๊ตฌ์‚ฌํ•ญ์„ ์•„์ฃผ ๊ผผ๊ผผํ•˜๊ฒŒ ์ž‘์„ฑํ•ด ์ฃผ์…จ๋„ค์š”! ๐Ÿ‘
@@ -0,0 +1,33 @@ +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.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 { + try { + SecurityContext securityContext = securityContextRepository.loadContext((HttpServletRequest) request); + SecurityContextHolder.setContext(securityContext); + + chain.doFilter(request, response); + } finally { + 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 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 UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication); + } +}
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 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 UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication); + } +}
Java
== ์—ฐ์‚ฐ์ž๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ UsernamePasswordAuthenticationToken๊ณผ ์ง์ ‘ ๋น„๊ตํ•˜๊ณ  ์žˆ๋Š”๋ฐ์š”, isAssignableFrom() ๋กœ ๋น„๊ตํ•˜๋Š” ๊ฒƒ๊ณผ ์–ด๋– ํ•œ ์ฐจ์ด๊ฐ€ ์žˆ์„๊นŒ์š”? ๐Ÿ˜„
@@ -0,0 +1,39 @@ +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 DEFAULT_SESSION_KEY = "SPRING_SECURITY_CONTEXT"; + + private final String sessionKey; + + public HttpSessionSecurityContextRepository() { + this(DEFAULT_SESSION_KEY); + } + + public HttpSessionSecurityContextRepository(String sessionKey) { + if (sessionKey == null) { + sessionKey = DEFAULT_SESSION_KEY; + } + this.sessionKey = sessionKey; + } + + @Override + public SecurityContext loadContext(HttpServletRequest request) { + HttpSession session = request.getSession(false); + if (session == null) { + return SecurityContextHolder.createEmptyContext(); + } + return (SecurityContext) session.getAttribute(sessionKey); + } + + @Override + public void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response) { + HttpSession session = request.getSession(); + session.setAttribute(sessionKey, context); + + SecurityContextHolder.setContext(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 true; + } + return !authorization.toLowerCase().startsWith(BASIC_PREFIX); + } +}
Java
isNotBasicAuth() ๋ฉ”์„œ๋“œ์˜ ๋„ค์ด๋ฐ์„ ๋ณด๋ฉด Basic ์ธ์ฆ์ด ์•„๋‹ ๊ฒฝ์šฐ true๋ฅผ ๋ฐ˜ํ™˜ํ•ด์•ผ ํ•  ๊ฒƒ ๊ฐ™์ง€๋งŒ, ํ˜„์žฌ ๊ตฌํ˜„์—์„œ๋Š” Basic ์ธ์ฆ์ผ ๋•Œ true๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ณ  ์žˆ๋„ค์š” ๐Ÿ˜„
@@ -0,0 +1,33 @@ +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.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 { + try { + SecurityContext securityContext = securityContextRepository.loadContext((HttpServletRequest) request); + SecurityContextHolder.setContext(securityContext); + + chain.doFilter(request, response); + } finally { + SecurityContextHolder.clearContext(); + } + } +}
Java
์•— ๊ทธ๋Ÿฌ๋„ค์š” ! ์ธ์ฆ์„ ๋ฐ›์ž๋งˆ์ž securityContextRepository ์— ์ €์žฅํ•˜๋Š”๊ฒŒ ์ข‹๊ฒ ๋„ค์š” [57d0f5](https://github.com/next-step/spring-security-authentication/pull/32/commits/57d0f520733998b10aec3ac441e30bf93b21cfa6) ํ•ด๋‹น ์ปค๋ฐ‹์— ๋ฐ˜์˜ํ•˜์˜€์Šต๋‹ˆ๋‹ค
@@ -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 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 UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication); + } +}
Java
๐Ÿ˜ข ๋‹จ์ถ•ํ‚ค๋ฅผ ์ž˜ ๋ชป์จ์„œ ์˜คํƒ€๊ฐ€ ๋‚ฌ๋‚˜๋ด์š”.. [0f8f88b](https://github.com/next-step/spring-security-authentication/pull/32/commits/0f8f88b23614c091cf8dc72c8c06aca34a7c6b4c) ํ•ด๋‹น์ปค๋ฐ‹์— ๋ฐ˜์˜ํ•˜์˜€์Šต๋‹ˆ๋‹ค~
@@ -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 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 UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication); + } +}
Java
isAssignableFrom() ๋น„๊ต ํ•˜๋ฉด ์ƒ์œ„ํƒ€์ž…๊นŒ์ง€ ๋น„๊ต ํ•  ์ˆ˜ ์žˆ๊ตฐ์š”! ์Œ... ์ œ๊ฐ€ ์ƒ๊ฐํ•˜๊ธฐ์— ํ”„๋ ˆ์ž„์›Œํฌ ์‚ฌ์šฉ์ž์— ๋Œ€ํ•ด์„œ ์ƒ์†์„ ํ†ตํ•ด UsernamePasswordAuthenticationToken๋ฅผ ํ™•์žฅํ•˜์—ฌ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์„๊บผ ๊ฐ™๋„ค์š”. ์ด์Šฌ๋‹˜์˜ ๋‹ค๋ฅธ์˜๊ฒฌ์ด ์žˆ๋‹ค๋ฉด ๋“ฃ๊ณ  ์‹ถ๋„ค์š” e36ce53464741014a8391df7e2761816fb381512 ์‚ฌ์šฉ์ž์—๊ฒŒ ํ™•์žฅ์„ ์ œ๊ณตํ•˜๊ณ ์ž ํ•ด๋‹น ์ปค๋ฐ‹์— ๋ณ€๊ฒฝํ•˜์˜€์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,39 @@ +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 DEFAULT_SESSION_KEY = "SPRING_SECURITY_CONTEXT"; + + private final String sessionKey; + + public HttpSessionSecurityContextRepository() { + this(DEFAULT_SESSION_KEY); + } + + public HttpSessionSecurityContextRepository(String sessionKey) { + if (sessionKey == null) { + sessionKey = DEFAULT_SESSION_KEY; + } + this.sessionKey = sessionKey; + } + + @Override + public SecurityContext loadContext(HttpServletRequest request) { + HttpSession session = request.getSession(false); + if (session == null) { + return SecurityContextHolder.createEmptyContext(); + } + return (SecurityContext) session.getAttribute(sessionKey); + } + + @Override + public void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response) { + HttpSession session = request.getSession(); + session.setAttribute(sessionKey, context); + + SecurityContextHolder.setContext(context); + } +}
Java
์•—.. ์ƒ์„ธํ•œ ์˜ต์…˜์— ๋Œ€ํ•ด์„œ๋Š” ๊ณ ๋ คํ•˜์ง€ ๋ชปํ–ˆ์—ˆ๋„ค์š” getSession(false)์€ ์„ธ์…˜์„ ์ƒ์„ฑํ•˜์ง€ ์•Š๊ณ  null ์„ ๋ฐ˜ํ™˜ ํ•˜๋Š” ๊ตฐ์š” ๋ถˆํ•„์š”ํ•œ ์„ธ์…˜์ด ์ƒ์„ฑ๋˜์ง€ ์•Š๋„๋ก [291d54e](https://github.com/next-step/spring-security-authentication/pull/32/commits/291d54ecda1c0cae213d2bf9432e339a34c8c7f6) ํ•ด๋‹น ์ปค๋ฐ‹์— ์ˆ˜์ •ํ•˜์˜€์Šต๋‹ˆ๋‹ค
@@ -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 true; + } + return !authorization.toLowerCase().startsWith(BASIC_PREFIX); + } +}
Java
if ๋ฌธ์— ๋ฉ”์„œ๋“œ๋ฅผ true ํ•˜๊ฒŒ ๋ฐ”๊พธ๋ ค๋‹ค๊ฐ€ ๋ฆฌํŽ™ํ† ๋ง ๋ถ€๋ถ„๋งŒํ•˜๊ณ  ์ปค๋ฐ‹๋งŒ ์ฐ์–ด๋ฒ„๋ ท๋„ค์š” ใ…Žใ…Ž... [0455587](https://github.com/next-step/spring-security-authentication/pull/32/commits/0455587ca34b85135e20207244a250667422db0b) ๋ฐ˜์˜ํ•˜์˜€์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,39 @@ +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 DEFAULT_SESSION_KEY = "SPRING_SECURITY_CONTEXT"; + + private final String sessionKey; + + public HttpSessionSecurityContextRepository() { + this(DEFAULT_SESSION_KEY); + } + + public HttpSessionSecurityContextRepository(String sessionKey) { + if (sessionKey == null) { + sessionKey = DEFAULT_SESSION_KEY; + } + this.sessionKey = sessionKey; + } + + @Override + public SecurityContext loadContext(HttpServletRequest request) { + HttpSession session = request.getSession(false); + if (session == null) { + return SecurityContextHolder.createEmptyContext(); + } + return (SecurityContext) session.getAttribute(sessionKey); + } + + @Override + public void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response) { + HttpSession session = request.getSession(); + session.setAttribute(sessionKey, context); + + SecurityContextHolder.setContext(context); + } +}
Java
saveContext()์—์„œ๋Š” ์„ธ์…˜ ์ €์žฅ ์—ญํ• ๋งŒ ์ˆ˜ํ–‰ํ•˜๋Š” ๊ฒƒ์ด ๋” ์ ์ ˆํ•˜์ง€ ์•Š์„๊นŒ ์ƒ๊ฐ๋˜๋Š”๋ฐ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”? ๐Ÿ˜Š
@@ -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 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 UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication); + } +}
Java
๋งž์•„์š”! ๐Ÿ‘ isAssignableFrom()์„ ์‚ฌ์šฉํ•˜๋ฉด UsernamePasswordAuthenticationToken์„ ํ™•์žฅํ•œ ์ปค์Šคํ…€ ์ธ์ฆ ํ† ํฐ๋„ ์ง€์›ํ•  ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์—, ํ™•์žฅ์„ฑ์„ ๊ณ ๋ คํ•  ๋•Œ ๋” ์œ ์—ฐํ•œ ๋ฐฉ์‹์ด ๋  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๐Ÿ˜„
@@ -0,0 +1,39 @@ +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 DEFAULT_SESSION_KEY = "SPRING_SECURITY_CONTEXT"; + + private final String sessionKey; + + public HttpSessionSecurityContextRepository() { + this(DEFAULT_SESSION_KEY); + } + + public HttpSessionSecurityContextRepository(String sessionKey) { + if (sessionKey == null) { + sessionKey = DEFAULT_SESSION_KEY; + } + this.sessionKey = sessionKey; + } + + @Override + public SecurityContext loadContext(HttpServletRequest request) { + HttpSession session = request.getSession(false); + if (session == null) { + return SecurityContextHolder.createEmptyContext(); + } + return (SecurityContext) session.getAttribute(sessionKey); + } + + @Override + public void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response) { + HttpSession session = request.getSession(); + session.setAttribute(sessionKey, context); + + SecurityContextHolder.setContext(context); + } +}
Java
๋‹จ์ˆœํ•˜๊ฒŒ ์ƒ๊ฐํ–ˆ์„๋•Œ ๋ ˆํฌ์ง€ํ† ๋ฆฌ์—์„œ ์ €์žฅํ•˜๋Š”๊ฒŒ ๊น”๋”ํ•˜์ง€ ์•Š์„๊นŒ ๊ณ ๋ฏผ์ด ๋˜์—ˆ์—ˆ๋Š”๋ฐ ์ฝ”๋ฉ˜ํŠธ ๋‚จ๊ฒจ์ฃผ์‹  ๋‚ด์šฉ์„ ๋ณด๋‹ˆ ์ƒˆ๋กœ์šด ๋ ˆํฌ์ง€ํ† ๋ฆฌ ๊ตฌํ˜„์ฒด์—์„œ๋Š” SecurityContextHolder๋ฅผ ๊ณ„์† ์ฑ™๊ฒจ์ค˜์•ผ๋˜๋Š” ๋ถ€๋‹ด์ด ์ƒ๊ธธ๊บผ ๊ฐ™์•„์š”! ํ•„ํ„ฐ์ชฝ์— ์ด๊ด€์„ ํ•ด์•ผํ• ๊บผ ๊ฐ™์•„์š”
@@ -0,0 +1,11 @@ +package baseball.util; + +import java.util.Random; + +public class RamdomNumberGenerator { + private static final Random RANDOM = new Random(); + + public static Integer generate() { + return RANDOM.nextInt(9) + 1; + } +}
Java
๋ฌด์ž‘์œ„์˜ ์ˆซ์ž๋ฅผ ์ƒ์„ฑํ•˜๋Š” ํด๋ž˜์Šค๋ฅผ ๋”ฐ๋กœ ๋นผ์„œ ํ…Œ์ŠคํŠธ๋ฅผ ์šฉ์ดํ•˜๊ฒŒ ํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•œ ๊ฒŒ ์ข‹๋„ค์š”!
@@ -0,0 +1,101 @@ +package baseball.domain; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class NumericBalls implements Iterable { + private List<NumericBall> numericBalls; + + public NumericBalls() { + numericBalls = new ArrayList<>(); + } + + public NumericBalls(List<Integer> numbers) { + validate(numbers); + List<NumericBall> newBalls = new ArrayList<>(); + for (Integer number : numbers) { + newBalls.add(new NumericBall(number)); + } + this.numericBalls = newBalls; + } + + private void validate(List<Integer> numbers) { + if (numbers.size() != 3) { + throw new IllegalArgumentException(); + } + } + + public List<Integer> match(NumericBalls otherBalls) { + List<Integer> matchPoints = new ArrayList<>(); + int matchedCnt = matchBall(otherBalls); + int strikeCnt = strikeCheck(otherBalls); + matchPoints.add(strikeCnt); + matchPoints.add(matchedCnt - strikeCnt); + return matchPoints; + } + + private Integer matchBall(NumericBalls otherBalls) { + Map<Integer, Integer> map = new HashMap<>(); + for (NumericBall num : numericBalls) { + map.put(num.numericBall(), 0); + } + + int ballCnt = 0; + + Iterator otherIterator = otherBalls.iterator(); + while(otherIterator.hasNext()) { + NumericBall otherBall = otherIterator.next(); + if (map.containsKey(otherBall.numericBall())) { + map.put(otherBall.numericBall(), map.get(otherBall.numericBall()) + 1); + } + } + for (Integer value : map.values()) { + ballCnt += value; + } + return ballCnt; + } + + private Integer strikeCheck(NumericBalls otherBalls) { + int strikeCnt = 0; + for (int i = 0; i < numericBalls.size(); i++) { + if (numericBalls.get(i).equals(otherBalls.numericBall(i))) { + strikeCnt++; + } + } + return strikeCnt; + } + + public NumericBall numericBall(int index) { + return numericBalls.get(index); + } + + public int size() { + return numericBalls.size(); + } + + @Override + public Iterator iterator() { + return new NumericBallsIterator(this); + } + + private static class NumericBallsIterator implements Iterator { + private int index = 0; + private NumericBalls numericBalls; + + public NumericBallsIterator(NumericBalls numericBalls) { + this.numericBalls = numericBalls; + } + + @Override + public boolean hasNext() { + return (this.index < this.numericBalls.size()); + } + + @Override + public NumericBall next() { + return numericBalls.numericBall(this.index++); + } + } +}
Java
๋ฆฌ์ŠคํŠธ์— ๋„ฃ๊ณ  ๋งต์— ๋‹ค์‹œ ๋„ฃ๋Š” ๊ฒƒ๋ณด๋‹ค ์ฒ˜์Œ๋ถ€ํ„ฐ ํ•„๋“œ๋ฅผ ๋งต์œผ๋กœ ์„ ์–ธํ•˜๊ณ  ๋งต์˜ ์ˆซ์ž์™€ ์ธ๋ฑ์Šค๋ฅผ ๋น„๊ตํ•˜๋ฉด ํšจ์œจ์ด ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”.
@@ -0,0 +1,23 @@ +package baseball.view; + +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + +public class InputView { + private static final Scanner SCANNER = new Scanner(System.in); + public static List<Integer> inputNumbers() { + System.out.println("์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š” : "); + List<Integer> nums = new ArrayList<>(); + nums.addAll(parse(List.of(SCANNER.next().split("")))); + return nums; + } + + private static List<Integer> parse(List<String> strArr) { + List<Integer> nums = new ArrayList<>(); + for (String str : strArr) { + nums.add(Integer.parseInt(str)); + } + return nums; + } +}
Java
๊ฐ์ฒด๋ฅผ ์ƒ์ˆ˜๋กœ ์„ ์–ธํ•˜๋ฉด ์ฝ”๋“œ๊ฐ€ ํ›จ์”ฌ ๊ฐ„ํŽธํ•ด์ง€์ง€๋งŒ, final์ž„์—๋„ ๊ฐ’์ด ๋ฐ”๋€” ์ˆ˜ ์žˆ์–ด ๊ด€๋ จ์ด์Šˆ๊ฐ€ ์žˆ์„ ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค. ์œ ์˜ํ•˜๊ณ  ์‚ฌ์šฉํ•ด์ฃผ์„ธ์š”:)
@@ -0,0 +1,18 @@ +package racingcar.view; + +import camp.nextstep.edu.missionutils.Console; + +public class InputView { + private static final String ASK_CAR_NAMES = "๊ฒฝ์ฃผํ•  ์ž๋™์ฐจ ์ด๋ฆ„์„ ์ž…๋ ฅํ•˜์„ธ์š”.(์ด๋ฆ„์€ ์‰ผํ‘œ(,) ๊ธฐ์ค€์œผ๋กœ ๊ตฌ๋ถ„)"; + private static final String ASK_TURN = "์‹œ๋„ํ•  ํšŒ์ˆ˜๋Š” ๋ช‡ํšŒ์ธ๊ฐ€์š”?"; + + public static String readCarNames() { + System.out.println(ASK_CAR_NAMES); + return Console.readLine(); + } + + public static String readTurn() { + System.out.println(ASK_TURN); + return Console.readLine(); + } +}
Java
๋ฉ”์‹œ์ง€ ๊ด€๋ฆฌ์— ๋Œ€ํ•ด์„œ static์ด ์ข‹์€์ง€ enum์ด ์ข‹์€์ง€ ์ด์•ผ๊ธฐ ๋‚˜๋ˆ ๋ณด๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ํ•ญ์ƒ ์–ด๋–ค๊ฒŒ ๋‚˜์€์ง€ ๊ณ ๋ฏผํ•ด์„œ ๋งค๋ฒˆ ์“ธ๋•Œ๋งˆ๋‹ค ํ•œ๋ฒˆ์€ ์ด๋ ‡๊ฒŒ ํ•œ๋ฒˆ์€ ์ €๋ ‡๊ฒŒ ํ–ˆ์—ˆ๊ฑฐ๋“ ์š”.
@@ -0,0 +1,18 @@ +package racingcar.view; + +import camp.nextstep.edu.missionutils.Console; + +public class InputView { + private static final String ASK_CAR_NAMES = "๊ฒฝ์ฃผํ•  ์ž๋™์ฐจ ์ด๋ฆ„์„ ์ž…๋ ฅํ•˜์„ธ์š”.(์ด๋ฆ„์€ ์‰ผํ‘œ(,) ๊ธฐ์ค€์œผ๋กœ ๊ตฌ๋ถ„)"; + private static final String ASK_TURN = "์‹œ๋„ํ•  ํšŒ์ˆ˜๋Š” ๋ช‡ํšŒ์ธ๊ฐ€์š”?"; + + public static String readCarNames() { + System.out.println(ASK_CAR_NAMES); + return Console.readLine(); + } + + public static String readTurn() { + System.out.println(ASK_TURN); + return Console.readLine(); + } +}
Java
์ €๋Š” System.out.print~์‚ฌ์šฉํ•˜๋Š” ๋ถ€๋ถ„์€ ์ „๋ถ€ ์ถœ๋ ฅ์œผ๋กœ ์‚ฌ์šฉ์ž์—๊ฒŒ ๋ณด์—ฌ์ง€๋Š” ๋ถ€๋ถ„์ด๋ผ๊ณ  ์ƒ๊ฐํ•ด์„œ ๋ชจ๋‘ OutputView์— ์ž‘์„ฑํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ์‚ฌ์‹ค ์ฒจ์— ์ €๋„ InputView์— ์จ๋„ ๋ ์ง€ ๊ณ ๋ฏผํ–ˆ๋Š”๋ฐ ์ด ๋ถ€๋ถ„์— ๋Œ€ํ•ด์„œ๋Š” ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋Š”์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,38 @@ +package racingcar.view; + +import java.util.stream.Collectors; +import racingcar.domain.RacingCar; +import racingcar.domain.RacingCars; +import racingcar.domain.Winner; + +public class OutputView { + private static final String RACE_RESULT_MESSAGE = "\n์‹คํ–‰ ๊ฒฐ๊ณผ"; + private static final String DISTANCE_UNIT = "-"; + private static final String RACE_RESULT_FORMAT = "%s : %s%n"; + private static final String WINNER = "์ตœ์ข… ์šฐ์Šน์ž : "; + private static final String DELIMITER = ", "; + + public static void printRaceResultNotice() { + System.out.println(RACE_RESULT_MESSAGE); + } + + public static void printRaceResult(RacingCars racingCars) { + racingCars.getRacingCars() + .forEach(racingCar -> System.out.printf(RACE_RESULT_FORMAT + , racingCar.getCarName(), changeDistanceForm(racingCar.getDistance()))); + System.out.println(); + } + + private static String changeDistanceForm(int distance) { + return DISTANCE_UNIT.repeat(distance); + } + + public static void printWinner(Winner winner) { + System.out.print(WINNER); + String winners = winner.getWinner() + .stream() + .map(RacingCar::getCarName) + .collect(Collectors.joining(DELIMITER)); + System.out.println(winners); + } +}
Java
Winnerํด๋ž˜์Šค์˜ getWinner()์—์„œ ์•„๋ž˜ ์—ฐ์‚ฐ์ด ๋๋‚œ ๊ฒฐ๊ณผ๋ฅผ ๋ฆฌํ„ดํ•˜๋ฉด getter๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ ๋„ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ›์•„์˜ฌ ์ˆ˜ ์žˆ๋‹ค๊ณ  ์ƒ๊ฐํ•˜๋Š”๋ฐ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”?
@@ -0,0 +1,17 @@ +package racingcar.domain; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class CarNameTest { + @ParameterizedTest + @DisplayName("์ฐจ๋Ÿ‰์ด๋ฆ„์€ 1-5๊ธ€์ž์ด๊ณ  ํŠน์ˆ˜๋ฌธ์ž๋ฅผ ํฌํ•จํ•˜์ง€ ์•Š๋Š”๋‹ค.") + @ValueSource(strings = {"abcdef", "", "$", "&", " ", "!", "(", "$", "%"}) + void createCarName(String input) { + assertThatThrownBy(() -> new CarName(input)) + .isInstanceOf(IllegalArgumentException.class); + } +} \ No newline at end of file
Java
assertThatCode๋ฅผ ์ด์šฉํ•ด์„œ ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•˜์ง€ ์•Š๊ณ  ์˜ฌ๋ฐ”๋ฅด๊ฒŒ ๋˜๋Š”์ง€ ํ•œ๋ฒˆ ํ…Œ์ŠคํŠธ ํ•ด๋ณด๋Š” ๊ฒƒ๋„ ์ถ”์ฒœ ๋“œ๋ฆฝ๋‹ˆ๋‹ค.
@@ -0,0 +1,22 @@ +package racingcar.domain; + +public enum ErrorMessage { + ERROR("[ERROR] "), + INVALID_NAME_LENGTH(ERROR + "์ฐจ๋Ÿ‰ ์ด๋ฆ„์€ 1-5๊ธ€์ž ์‚ฌ์ด์—ฌ์•ผ ํ•ฉ๋‹ˆ๋‹ค."), + INVALID_NAME_TYPE(ERROR + "์ฐจ๋Ÿ‰ ์ด๋ฆ„์€ ํŠน์ˆ˜๋ฌธ์ž๋ฅผ ํฌํ•จํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + DUPLICATED_NAME(ERROR + "์ฐจ๋Ÿ‰ ์ด๋ฆ„์€ ์ค‘๋ณต๋  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + INVALID_RACING_CARS_SIZE(ERROR + "๊ฒฝ์ฃผ์—๋Š” ์ตœ์†Œ 2๋Œ€์˜ ์ฐจ๋Ÿ‰์ด ์ฐธ์—ฌํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค."), + INVALID_TURN_RANGE(ERROR + "์‹œ๋„ํšŸ์ˆ˜๋Š” ์ตœ์†Œ 1ํšŒ ์ด์ƒ์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค."), + INVALID_TURN_TYPE(ERROR + "์ˆซ์ž ์ด์™ธ์˜ ๊ฐ’์€ ์ž…๋ ฅํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + CANT_FIND_CAR(ERROR + "์ฐจ๋Ÿ‰์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + + private final String message; + + ErrorMessage(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } +}
Java
ERROR์€ ๋ณ€ํ•จ ์—†์„ ๊ฒƒ ๊ฐ™์€๋ฐ ์ƒ์ˆ˜๋กœ ๋‘๊ณ  ์ƒ์„ฑ์ž ๋ถ€๋ถ„์—์„œ this.message = "ERROR" + message๋กœ ํ•œ๋‹ค๋ฉด ๋ฉ”์‹œ์ง€ ์ž‘์„ฑํ•  ๋•Œ ์ค‘๋ณต์„ ํ”ผํ•˜๋Š”๋ฐ ๋„์›€ ๋  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,63 @@ +package racingcar.domain; + +import static racingcar.domain.ErrorMessage.CANT_FIND_CAR; +import static racingcar.domain.ErrorMessage.DUPLICATED_NAME; +import static racingcar.domain.ErrorMessage.INVALID_RACING_CARS_SIZE; + +import java.util.List; +import java.util.stream.Collectors; + +public class RacingCars { + private static final int MIN_SIZE = 2; + private final List<RacingCar> racingCars; + private RacingCar maxDistanceCar; + + public RacingCars(List<RacingCar> racingCars) { + validateSize(racingCars); + validateDuplicated(racingCars); + this.racingCars = racingCars; + } + + private void validateSize(List<RacingCar> racingCars) { + if (racingCars.size() < MIN_SIZE) { + throw new IllegalArgumentException(INVALID_RACING_CARS_SIZE.getMessage()); + } + } + + private void validateDuplicated(List<RacingCar> racingCars) { + if (isDuplicated(racingCars)) { + throw new IllegalArgumentException(DUPLICATED_NAME.getMessage()); + } + } + + private boolean isDuplicated(List<RacingCar> racingCars) { + int sizeAfterCut = (int) racingCars.stream() + .distinct() + .count(); + return racingCars.size() != sizeAfterCut; + } + + public void startRace() { + racingCars + .forEach(racingCar -> + racingCar.moveForward(RandomNumberGenerator.generateRandomNumber())); + } + + public Winner selectWinner() { + findMaxDistanceCar(); + List<RacingCar> winner = racingCars.stream() + .filter(maxDistanceCar::isWinner) + .collect(Collectors.toList()); + return new Winner(winner); + } + + private void findMaxDistanceCar() { + maxDistanceCar = racingCars.stream() + .max(RacingCar::compareTo) + .orElseThrow(() -> new IllegalArgumentException(CANT_FIND_CAR.getMessage())); + } + + public List<RacingCar> getRacingCars() { + return racingCars; + } +}
Java
return์— ๋ฐ”๋กœ ์ž‘์„ฑํ•˜๋ฉด ๊ฐ€๋…์„ฑ์ด ์กฐ๊ธˆ ๋–จ์–ด์ ธ ๋ณด์ผ๊นŒ์š”? ์ด ๋ฉ”์†Œ๋“œ ์ฒ˜๋Ÿผ ํ•œ๋ฒˆ๋งŒ ์‚ฌ์šฉํ•˜๋Š” ๋ณ€์ˆ˜๋ผ๋ฉด ๋ณ€์ˆ˜๋กœ ์ง€์ •ํ•˜์ง€ ์•Š๊ณ  ๋ฐ”๋กœ ์ž‘์„ฑํ•ด๋„ ๋  ๊ฒƒ ๊ฐ™์€๋ฐ... ์ด๋Ÿฌ๋ฉด ๊ฐ€๋…์„ฑ์ด ๋–จ์–ด์ ธ ๋ณด์ด๊ธฐ๋„ ํ•  ๊ฒƒ ๊ฐ™์•„ ๊ณ ๋ฏผ์ด ๋˜์„œ ์—ฌ์ญค๋ด…๋‹ˆ๋‹ค.
@@ -0,0 +1,51 @@ +package racingcar.domain; + +import static racingcar.domain.ErrorMessage.INVALID_NAME_LENGTH; +import static racingcar.domain.ErrorMessage.INVALID_NAME_TYPE; + +import java.util.Objects; +import java.util.regex.Pattern; + +public class CarName { + private static final int MAX_LENGTH = 5; + private static final String REGEX = "[0-9|a-zA-Zใ„ฑ-ใ…Žใ…-ใ…ฃ๊ฐ€-ํžฃ]*"; + private final String carName; + + public CarName(String carName) { + validateLength(carName); + validateType(carName); + this.carName = carName; + } + + private void validateLength(String carName) { + if (carName.isEmpty() || carName.length() > MAX_LENGTH) { + throw new IllegalArgumentException(INVALID_NAME_LENGTH.getMessage()); + } + } + + private void validateType(String carName) { + if (!Pattern.matches(REGEX, carName)) { + throw new IllegalArgumentException(INVALID_NAME_TYPE.getMessage()); + } + } + + public String getCarName() { + return carName; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof CarName carName1)) { + return false; + } + return Objects.equals(carName, carName1.carName); + } + + @Override + public int hashCode() { + return Objects.hash(carName); + } +}
Java
์ •๊ทœํ‘œํ˜„์‹์— ๋ฌธ์ž์ง€์ •ํ•œ ํ›„ {1,5}์„ ์‚ฌ์šฉํ•˜๋ฉด ๊ธ€์ž ์ˆ˜ ์ œํ•œ ํ•˜๋Š”๋ฐ๋„ ๋„์›€์ด ๋  ๊ฑฐ์—์š”.
@@ -0,0 +1,35 @@ +package racingcar.domain; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; + +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class RacingCarsTest { + @ParameterizedTest + @DisplayName("๊ฒฝ์ฃผ์—๋Š” ์ตœ์†Œ 2๋Œ€ ์ด์ƒ์˜ ์ฐจ๋Ÿ‰์ด ์ฐธ์—ฌํ•ด์•ผ ํ•˜๋ฉฐ ์ค‘๋ณต๋  ์ˆ˜ ์—†๋‹ค.") + @ValueSource(strings = {"์ƒ์ถ”", "์ƒ์ถ”,์ƒ์ถ”"}) + void createRacingCars(String input) { + List<RacingCar> racingCars = InputConvertor.convertToRacingCars(input); + assertThatThrownBy(() -> new RacingCars(racingCars)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("์šฐ์Šน์ž๋Š” ์ƒ์ถ”์™€ ๋ฐฐ์ถ”๋‹ค.") + void selectWinner() { + RacingCar sangchu = new RacingCar(new CarName("์ƒ์ถ”")); + RacingCar baechu = new RacingCar(new CarName("๋ฐฐ์ถ”")); + RacingCar moodosa = new RacingCar(new CarName("๋ฌด๋„์‚ฌ")); + RacingCars racingCars = new RacingCars(List.of(sangchu, baechu, moodosa)); + sangchu.moveForward(5); + baechu.moveForward(6); + Winner winner = racingCars.selectWinner(); + assertThat(winner.getWinner().get(0).getCarName()).isEqualTo("์ƒ์ถ”"); + assertThat(winner.getWinner().get(1).getCarName()).isEqualTo("๋ฐฐ์ถ”"); + } +} \ No newline at end of file
Java
2๋Œ€ ์ด์ƒ์ธ ๊ฒฝ์šฐ / ์ด๋ฆ„ ์ค‘๋ณต๋˜๋ฉด ์•ˆ๋˜๋Š” ๊ฒฝ์šฐ์— ๋Œ€ํ•ด ๋ฉ”์†Œ๋“œ๋ฅผ ๋‚˜๋ˆ ์„œ ํ…Œ์ŠคํŠธ ํ•ด๋„ ์ข‹์„๊ฑฐ๊ฐ™์Šด๋‹ค
@@ -0,0 +1,17 @@ +package racingcar.domain; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class TurnTest { + @ParameterizedTest + @DisplayName("1ํšŒ ๋ฏธ๋งŒ, ์ˆซ์ž ์ด์™ธ ๊ฐ’ ์ž…๋ ฅ์‹œ ์˜ˆ์™ธ ๋ฐœ์ƒ") + @ValueSource(strings = {"0", "-1", "d", "#", "", " "}) + void createTurn(String input) { + assertThatThrownBy(() -> new Turn(input)) + .isInstanceOf(IllegalArgumentException.class); + } +} \ No newline at end of file
Java
์ €๋Š” validate ๋กœ์ง์— ๋Œ€ํ•ด์„œ 1. ์ˆซ์ž๋งŒ ์ž…๋ ฅ ๋ฐ›์•„์•ผํ•˜๋Š” ๋ณ€์ˆ˜์— ๋ฌธ์ž ์ž…๋ ฅ๋˜๋Š” ๊ฒฝ์šฐ -> input์—์„œ ๊ฒ€์ฆ 2. 1ํšŒ ๋ฏธ๋งŒ์œผ๋กœ ์ž…๋ ฅ๋ฐ›๋Š” ๋ฉ”์†Œ๋“œ ๊ด€๋ จ ๊ฒ€์ฆ -> turn๋ฉ”์†Œ๋“œ์—์„œ ๊ฒ€์ฆ ํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ํ•ญ์ƒ ์ž‘์„ฑํ•ด ์™”๋Š”๋ฐ ์ด๋ถ€๋ถ„์— ๋Œ€ํ•ด์„œ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜๋Š”์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค !
@@ -0,0 +1,18 @@ +package racingcar.view; + +import camp.nextstep.edu.missionutils.Console; + +public class InputView { + private static final String ASK_CAR_NAMES = "๊ฒฝ์ฃผํ•  ์ž๋™์ฐจ ์ด๋ฆ„์„ ์ž…๋ ฅํ•˜์„ธ์š”.(์ด๋ฆ„์€ ์‰ผํ‘œ(,) ๊ธฐ์ค€์œผ๋กœ ๊ตฌ๋ถ„)"; + private static final String ASK_TURN = "์‹œ๋„ํ•  ํšŒ์ˆ˜๋Š” ๋ช‡ํšŒ์ธ๊ฐ€์š”?"; + + public static String readCarNames() { + System.out.println(ASK_CAR_NAMES); + return Console.readLine(); + } + + public static String readTurn() { + System.out.println(ASK_TURN); + return Console.readLine(); + } +}
Java
์ €๋Š” ์ด๋ฒˆ์— ํ”„๋ฆฌ์ฝ”์Šค๋ฅผ ์ง„ํ–‰ํ•˜๋ฉด์„œ ๋‚˜๋ฆ„์˜ ๊ธฐ์ค€์„ ์„ธ์›Œ๋ดค์Šต๋‹ˆ๋‹ค! 1. enum์œผ๋กœ ์‚ฌ์šฉํ• ๋งŒํผ ์ƒ์ˆ˜์˜ ๊ฐœ์ˆ˜๊ฐ€ ์ถฉ๋ถ„ํ•œ์ง€? ์ตœ์†Œ 3๊ฐœ ์ด์ƒ 2. ํ”„๋กœ๊ทธ๋žจ์ด ํ™•์žฅ๋œ๋‹ค๋ฉด ํ•ด๋‹น enum ์— ์ƒ์ˆ˜๊ฐ€ ์ถ”๊ฐ€๋  ๊ฐ€๋Šฅ์„ฑ์ด ์žˆ๋Š”์ง€? 3. ๋‹ค๋ฅธ ํด๋ž˜์Šค์—์„œ๋„ ์‚ฌ์šฉ๋  ๊ฐ€๋Šฅ์„ฑ์ด ์žˆ๋Š”์ง€?
@@ -0,0 +1,18 @@ +package racingcar.view; + +import camp.nextstep.edu.missionutils.Console; + +public class InputView { + private static final String ASK_CAR_NAMES = "๊ฒฝ์ฃผํ•  ์ž๋™์ฐจ ์ด๋ฆ„์„ ์ž…๋ ฅํ•˜์„ธ์š”.(์ด๋ฆ„์€ ์‰ผํ‘œ(,) ๊ธฐ์ค€์œผ๋กœ ๊ตฌ๋ถ„)"; + private static final String ASK_TURN = "์‹œ๋„ํ•  ํšŒ์ˆ˜๋Š” ๋ช‡ํšŒ์ธ๊ฐ€์š”?"; + + public static String readCarNames() { + System.out.println(ASK_CAR_NAMES); + return Console.readLine(); + } + + public static String readTurn() { + System.out.println(ASK_TURN); + return Console.readLine(); + } +}
Java
์ €๋„ ์ฒ˜์Œ์— 1์ฃผ์ฐจ ๋ฏธ์…˜์„ ์ง„ํ–‰ํ•  ๋•Œ๋Š” ์‚ฌ์šฉ์ž์—๊ฒŒ ๋ณด์ด๋Š” ๋ถ€๋ถ„์ด๋ผ๊ณ  ์ƒ๊ฐํ•˜์—ฌ OutputView์— ์ž‘์„ฑํ–ˆ์—ˆ๋Š”๋ฐ ๋งŽ์€ ๋ถ„๋“ค ์ฝ”๋“œ๋ฅผ ๋ณด๋‹ค๋ณด๋‹ˆ ์ž…๋ ฅ์„ ์š”์ฒญํ•˜๋Š” ๋ฉ”์‹œ์ง€๋Š” InputView์—์„œ ์ฒ˜๋ฆฌํ•˜์‹œ๋”๋ผ๊ตฌ์š”. ๊ทธ๋ฆฌ๊ณ  ๊ฒฐ์ •์ ์œผ๋กœ ์šฐํ…Œ์ฝ”์—์„œ ์ œ๊ณตํ•œ ์š”๊ตฌ์‚ฌํ•ญ ๋ถ€๋ถ„์„ ๋ณด์‹œ๋ฉด ์ž…๋ ฅ์„ ์š”๊ตฌํ•˜๋Š” ๋ฉ”์‹œ์ง€๋ฅผ InputView์—์„œ ์‚ฌ์šฉํ•˜๋Š”๊ฑธ ๋ณด์‹ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. <img width="914" alt="image" src="https://github.com/parksangchu/java-racingcar-6/assets/142131857/87aa54ff-07c6-4c03-87fe-331d6aba9664">
@@ -0,0 +1,22 @@ +package racingcar.domain; + +public enum ErrorMessage { + ERROR("[ERROR] "), + INVALID_NAME_LENGTH(ERROR + "์ฐจ๋Ÿ‰ ์ด๋ฆ„์€ 1-5๊ธ€์ž ์‚ฌ์ด์—ฌ์•ผ ํ•ฉ๋‹ˆ๋‹ค."), + INVALID_NAME_TYPE(ERROR + "์ฐจ๋Ÿ‰ ์ด๋ฆ„์€ ํŠน์ˆ˜๋ฌธ์ž๋ฅผ ํฌํ•จํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + DUPLICATED_NAME(ERROR + "์ฐจ๋Ÿ‰ ์ด๋ฆ„์€ ์ค‘๋ณต๋  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + INVALID_RACING_CARS_SIZE(ERROR + "๊ฒฝ์ฃผ์—๋Š” ์ตœ์†Œ 2๋Œ€์˜ ์ฐจ๋Ÿ‰์ด ์ฐธ์—ฌํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค."), + INVALID_TURN_RANGE(ERROR + "์‹œ๋„ํšŸ์ˆ˜๋Š” ์ตœ์†Œ 1ํšŒ ์ด์ƒ์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค."), + INVALID_TURN_TYPE(ERROR + "์ˆซ์ž ์ด์™ธ์˜ ๊ฐ’์€ ์ž…๋ ฅํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + CANT_FIND_CAR(ERROR + "์ฐจ๋Ÿ‰์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + + private final String message; + + ErrorMessage(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } +}
Java
enum ์ƒ์„ฑ์ž์— ๋Œ€ํ•œ ์ดํ•ด๊ฐ€ ๋ถ€์กฑํ–ˆ๋˜๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค ! ์ข‹์€ ์กฐ์–ธ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ใ…Žใ…Ž
@@ -0,0 +1,63 @@ +package racingcar.domain; + +import static racingcar.domain.ErrorMessage.CANT_FIND_CAR; +import static racingcar.domain.ErrorMessage.DUPLICATED_NAME; +import static racingcar.domain.ErrorMessage.INVALID_RACING_CARS_SIZE; + +import java.util.List; +import java.util.stream.Collectors; + +public class RacingCars { + private static final int MIN_SIZE = 2; + private final List<RacingCar> racingCars; + private RacingCar maxDistanceCar; + + public RacingCars(List<RacingCar> racingCars) { + validateSize(racingCars); + validateDuplicated(racingCars); + this.racingCars = racingCars; + } + + private void validateSize(List<RacingCar> racingCars) { + if (racingCars.size() < MIN_SIZE) { + throw new IllegalArgumentException(INVALID_RACING_CARS_SIZE.getMessage()); + } + } + + private void validateDuplicated(List<RacingCar> racingCars) { + if (isDuplicated(racingCars)) { + throw new IllegalArgumentException(DUPLICATED_NAME.getMessage()); + } + } + + private boolean isDuplicated(List<RacingCar> racingCars) { + int sizeAfterCut = (int) racingCars.stream() + .distinct() + .count(); + return racingCars.size() != sizeAfterCut; + } + + public void startRace() { + racingCars + .forEach(racingCar -> + racingCar.moveForward(RandomNumberGenerator.generateRandomNumber())); + } + + public Winner selectWinner() { + findMaxDistanceCar(); + List<RacingCar> winner = racingCars.stream() + .filter(maxDistanceCar::isWinner) + .collect(Collectors.toList()); + return new Winner(winner); + } + + private void findMaxDistanceCar() { + maxDistanceCar = racingCars.stream() + .max(RacingCar::compareTo) + .orElseThrow(() -> new IllegalArgumentException(CANT_FIND_CAR.getMessage())); + } + + public List<RacingCar> getRacingCars() { + return racingCars; + } +}
Java
์ œ๊ฐ€ 3์ฃผ์ฐจ ๋ฏธ์…˜์„ ํ• ๋•Œ ๊ฒช์—ˆ๋˜ ์—๋กœ์‚ฌํ•ญ์ด ๋ฉ”์„œ๋“œ๋‚ด ๋ชจ๋“  ์ฝ”๋“œ๋ฅผ ์ถ•์•ฝ์„ ์‹œํ‚ค๋‹ค๋ณด๋‹ˆ ๋‚˜์ค‘์— ์ œ๊ฐ€ ๊ทธ ์ฝ”๋“œ๋ฅผ ๋ณด์•˜์„๋•Œ ๋ฌด์Šจ ์ฝ”๋“œ์ธ์ง€ ํ•œ๋ˆˆ์— ์•Œ๊ธฐ๊ฐ€ ํž˜๋“ค๋”๊ตฐ์š” ใ…œใ…œ ๊ทธ๋ž˜์„œ 4์ฃผ์ฐจ๋•Œ๋ถ€ํ„ฐ๋Š” ์–ด๋А์ •๋„ ์ ˆ์ œํ•ด์„œ ์ถ•์•ฝ์„ ํ•ด๋ณด๋‹ˆ ๊ฐ€๋…์„ฑ์ด ํ›จ์”ฌ ๋†’์•„์กŒ์—ˆ๋˜ ๊ฒฝํ—˜์ด ์žˆ์–ด์„œ ์ด๋ฒˆ์—๋„ ์ด๋Ÿฐ ๋ฐฉ์‹์œผ๋กœ ์ง„ํ–‰์„ ํ•ด๋ดค์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,38 @@ +package racingcar.view; + +import java.util.stream.Collectors; +import racingcar.domain.RacingCar; +import racingcar.domain.RacingCars; +import racingcar.domain.Winner; + +public class OutputView { + private static final String RACE_RESULT_MESSAGE = "\n์‹คํ–‰ ๊ฒฐ๊ณผ"; + private static final String DISTANCE_UNIT = "-"; + private static final String RACE_RESULT_FORMAT = "%s : %s%n"; + private static final String WINNER = "์ตœ์ข… ์šฐ์Šน์ž : "; + private static final String DELIMITER = ", "; + + public static void printRaceResultNotice() { + System.out.println(RACE_RESULT_MESSAGE); + } + + public static void printRaceResult(RacingCars racingCars) { + racingCars.getRacingCars() + .forEach(racingCar -> System.out.printf(RACE_RESULT_FORMAT + , racingCar.getCarName(), changeDistanceForm(racingCar.getDistance()))); + System.out.println(); + } + + private static String changeDistanceForm(int distance) { + return DISTANCE_UNIT.repeat(distance); + } + + public static void printWinner(Winner winner) { + System.out.print(WINNER); + String winners = winner.getWinner() + .stream() + .map(RacingCar::getCarName) + .collect(Collectors.joining(DELIMITER)); + System.out.println(winners); + } +}
Java
๋ฐ›์•„์˜จ ๋ฐ์ดํ„ฐ๋ฅผ ์–ด๋–ค์‹์œผ๋กœ ์ฒ˜๋ฆฌํ• ์ง€ ๊ฒฐ์ •ํ•˜๋Š” ๊ฒƒ์€ OutputView์˜ ์ฑ…์ž„์ด๋ผ๊ณ  ์ƒ๊ฐํ•ด์„œ ํ•ด๋‹น ๋ฐฉ์‹์œผ๋กœ ์ง„ํ–‰ํ–ˆ์Šต๋‹ˆ๋‹ค~ 3์ฃผ์ฐจ ๊ณตํ†ต ํ”ผ๋“œ๋ฐฑ์—์„œ๋„ view์—์„œ ์‚ฌ์šฉํ•˜๋Š” ๋ฐ์ดํ„ฐ๋Š” getter๋ฅผ ์‚ฌ์šฉํ•˜๋ผ๊ณ  ์–ธ๊ธ‰์ด ๋˜์–ด์žˆ๊ตฌ์š”! <img width="619" alt="image" src="https://github.com/parksangchu/java-racingcar-6/assets/142131857/99c1b2c6-7c6d-49ee-8154-e9d7c306bd0b">
@@ -0,0 +1,17 @@ +package racingcar.domain; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class CarNameTest { + @ParameterizedTest + @DisplayName("์ฐจ๋Ÿ‰์ด๋ฆ„์€ 1-5๊ธ€์ž์ด๊ณ  ํŠน์ˆ˜๋ฌธ์ž๋ฅผ ํฌํ•จํ•˜์ง€ ์•Š๋Š”๋‹ค.") + @ValueSource(strings = {"abcdef", "", "$", "&", " ", "!", "(", "$", "%"}) + void createCarName(String input) { + assertThatThrownBy(() -> new CarName(input)) + .isInstanceOf(IllegalArgumentException.class); + } +} \ No newline at end of file
Java
์ฒ˜์Œ ๋ณด๋Š” ๋ฉ”์„œ๋“œ์˜€๋Š”๋ฐ ํ•œ๋ฒˆ ์‚ฌ์šฉํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค! ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ใ…Žใ…Ž
@@ -0,0 +1,35 @@ +package racingcar.domain; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; + +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class RacingCarsTest { + @ParameterizedTest + @DisplayName("๊ฒฝ์ฃผ์—๋Š” ์ตœ์†Œ 2๋Œ€ ์ด์ƒ์˜ ์ฐจ๋Ÿ‰์ด ์ฐธ์—ฌํ•ด์•ผ ํ•˜๋ฉฐ ์ค‘๋ณต๋  ์ˆ˜ ์—†๋‹ค.") + @ValueSource(strings = {"์ƒ์ถ”", "์ƒ์ถ”,์ƒ์ถ”"}) + void createRacingCars(String input) { + List<RacingCar> racingCars = InputConvertor.convertToRacingCars(input); + assertThatThrownBy(() -> new RacingCars(racingCars)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("์šฐ์Šน์ž๋Š” ์ƒ์ถ”์™€ ๋ฐฐ์ถ”๋‹ค.") + void selectWinner() { + RacingCar sangchu = new RacingCar(new CarName("์ƒ์ถ”")); + RacingCar baechu = new RacingCar(new CarName("๋ฐฐ์ถ”")); + RacingCar moodosa = new RacingCar(new CarName("๋ฌด๋„์‚ฌ")); + RacingCars racingCars = new RacingCars(List.of(sangchu, baechu, moodosa)); + sangchu.moveForward(5); + baechu.moveForward(6); + Winner winner = racingCars.selectWinner(); + assertThat(winner.getWinner().get(0).getCarName()).isEqualTo("์ƒ์ถ”"); + assertThat(winner.getWinner().get(1).getCarName()).isEqualTo("๋ฐฐ์ถ”"); + } +} \ No newline at end of file
Java
์ฝ”๋“œ๋ฅผ ์ค„์ด๋ ค๊ณ  ๋„ˆ๋ฌด ์š•์‹ฌ์„ ๋‚ด๋‹ค๋ณด๋‹ˆ ๊ทธ๋งŒ ... ใ…œ ์•„๋ฌด๋ž˜๋„ ๋”ฐ๋กœ ํ…Œ์ŠคํŠธํ•˜๋Š”๊ฒŒ ๊ฐ€๋…์„ฑ ์ธก๋ฉด์—์„œ๋„ ์ข‹์„๊ฑฐ ๊ฐ™์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,17 @@ +package racingcar.domain; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class TurnTest { + @ParameterizedTest + @DisplayName("1ํšŒ ๋ฏธ๋งŒ, ์ˆซ์ž ์ด์™ธ ๊ฐ’ ์ž…๋ ฅ์‹œ ์˜ˆ์™ธ ๋ฐœ์ƒ") + @ValueSource(strings = {"0", "-1", "d", "#", "", " "}) + void createTurn(String input) { + assertThatThrownBy(() -> new Turn(input)) + .isInstanceOf(IllegalArgumentException.class); + } +} \ No newline at end of file
Java
์ €๋„ ์›๋ž˜๋Š” ๊ทธ๋Ÿฐ ๋ฐฉ์‹์œผ๋กœ ๊ฒ€์ฆ์„ ์ง„ํ–‰ํ•ด์˜ค๋‹ค๊ฐ€ ์ด๋ฒˆ์— 'InputView์—์„œ domain์—์„œ ์“ฐ์ผ ๋ฐ์ดํ„ฐ ํ˜•ํƒœ๋ฅผ ์•„๋Š”๊ฒŒ ๋งž์„๊นŒ?'ํ•˜๋Š” ์˜๋ฌธ์ด ๋“ค์–ด ํ•ด๋‹น ๋ฐฉ์‹์œผ๋กœ ์ง„ํ–‰์„ ํ•ด๋ดค์Šต๋‹ˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  'RacingCar'์™€ ๊ฐ™์€ ํ•ด๋‹น ํ”„๋กœ๊ทธ๋žจ์˜ ๋„๋ฉ”์ธ์—์„œ ์“ฐ์ด๋Š” ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•ด์„œ ๋„˜๊ธฐ๋Š” ๊ฒƒ๋งŒ ์•„๋‹ˆ๋ผ๋ฉด int์™€ ๊ฐ™์€ ๊ธฐ๋ณธ๊ฐ’ ํ˜•ํƒœ๋Š” inputView์—์„œ ๊ฒ€์ฆํ•ด๋„ ๊ดœ์ฐฎ๊ฒ ๋‹ค๋ผ๋Š” ๊ฒฐ๋ก ์„ ๋ƒˆ์Šต๋‹ˆ๋‹ค.
@@ -1,7 +1,14 @@ package christmas; +import christmas.controller.ChristmasController; +import christmas.exception.ExceptionHandler; +import christmas.exception.RetryExceptionHandler; + public class Application { public static void main(String[] args) { - // TODO: ํ”„๋กœ๊ทธ๋žจ ๊ตฌํ˜„ + ExceptionHandler handler = new RetryExceptionHandler(); + + ChristmasController controller = new ChristmasController(handler); + controller.service(); } }
Java
๋ฉ”์„œ๋“œ๋Š” ๋™์‚ฌ๋กœ ํ•˜๋Š” ๊ฒƒ์ด ์ข‹๋‹ค๊ณ  ์ƒ๊ฐํ•˜๋Š”๋ฐ, service() ๋Š” ์ •๋น„ํ•˜๋‹ค ๋ผ๋Š” ์˜๋ฏธ๋ผ๊ณ  ํ•ด์š”! ๋ฌผ๋ก , ์„œ๋น„์Šค ํ•˜๋‹ค~ ๋ผ๋Š” ๋А๋‚Œ์ธ ๊ฑด ์ดํ•ดํ•˜์ง€๋งŒ execute()๋‚˜ operate() ์™€ ๊ฐ™์€ ๋™์ž‘์„ ๊ฐ•์กฐํ•˜๋Š” ๋™์‚ฌ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฑด ์–ด๋–จ๊นŒ ํ•˜๋Š” ๊ฐœ์ธ์  ์˜๊ฒฌ์ž…๋‹ˆ๋‹ค!
@@ -0,0 +1,25 @@ +package christmas.constant; + +public enum Badge { + NONE("์—†์Œ", 0), + STAR("๋ณ„", 5_000), + TREE("ํŠธ๋ฆฌ", 10_000), + SANTA("์‚ฐํƒ€", 20_000); + + + private final String badgeName; + private final long prize; + + Badge(String badgeName, long prize){ + this.badgeName = badgeName; + this.prize = prize; + } + + public String getBadgeName(){ + return badgeName; + } + + public long getPrize(){ + return prize; + } +}
Java
์ด ๋ถ€๋ถ„ ์ฐธ ๊ณ ๋ฏผ ๋งŽ์ด ํ—€๋Š”๋ฐ์š”, ์ €๋„ "์—†์Œ" ๋ฐฐ์ง€๋ฅผ ๋งŒ๋“  ๋’ค ๊ณ ๋ฏผํ•ด๋ณด๋‹ˆ ๋„๋ฉ”์ธ ์ชฝ์—์„œ ์ถœ๋ ฅ ๋กœ์ง์„ ์•Œ์•„์•ผํ•˜๋Š” ๊ฒƒ ๊ฐ™์•„์„œ ์—†์Œ ๋ฐฐ์ง€๋ฅผ ์‚ญ์ œํ•˜๊ณ , Dto์— ๋น„์–ด์žˆ๋Š” badgeName ๊ฐ’์„ ๋„ฃ๋Š” ์‹์œผ๋กœ ๊ตฌํ˜„ํ•œ ํ›„ OutputView์—์„œ ์ „๋‹ฌ๋ฐ›์€ ์ด๋ฒคํŠธ ๋ฐฐ์ง€ ๊ฐ’์ด ๋น„์–ด์žˆ๋Š” String์ด๋ฉด ์—†์• ๋Š” ์‹์œผ๋กœ ์ฒ˜๋ฆฌํ–ˆ์Šต๋‹ˆ๋‹ค. ์ˆ˜์ง„๋‹˜์€ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”?
@@ -0,0 +1,41 @@ +package christmas.constant; + +public enum Menu { + YANGSONGSOUP("์–‘์†ก์ด์ˆ˜ํ”„", 6000, MenuType.APPETIZER), + TAPAS("ํƒ€ํŒŒ์Šค", 5500, MenuType.APPETIZER), + CAESAR_SALAD("์‹œ์ €์ƒ๋Ÿฌ๋“œ", 8000, MenuType.APPETIZER), + + T_BONE_STEAK("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ", 55000, MenuType.MAIN), + BBQ_RIB("๋ฐ”๋น„ํ๋ฆฝ", 54000, MenuType.MAIN), + SEAFOOD_PASTA("ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€", 35000, MenuType.MAIN), + CHRISTMAS_PASTA("ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€", 25000, MenuType.MAIN), + + CHOCO_CAKE("์ดˆ์ฝ”์ผ€์ดํฌ", 15000, MenuType.DESSERT), + ICE_CREAM("์•„์ด์Šคํฌ๋ฆผ", 5000, MenuType.DESSERT), + + ZERO_COLA("์ œ๋กœ์ฝœ๋ผ", 3000, MenuType.BEVERAGE), + RED_WINE("๋ ˆ๋“œ์™€์ธ", 60000, MenuType.BEVERAGE), + CHAMPAGNE("์ƒดํŽ˜์ธ", 25000, MenuType.BEVERAGE); + + private final String name; + private final int price; + private final MenuType menuType; + + Menu(String name, int price, MenuType menuType) { + this.name = name; + this.price = price; + this.menuType = menuType; + } + + public String getName() { + return name; + } + + public int getPrice() { + return price; + } + + public MenuType getMenuType() { + return menuType; + } +}
Java
MenuType์„ static import ํ•˜๋ฉด ์ข€ ๋” ์งง๊ฒŒ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ์„๊ฑฐ ๊ฐ™์•„์š”!
@@ -0,0 +1,74 @@ +package christmas.controller; + +import christmas.constant.Menu; +import christmas.domain.BenefitStorage; +import christmas.dto.BenefitResult; +import christmas.domain.Customer; +import christmas.domain.EventPlanner; +import christmas.dto.OrderMenu; +import christmas.exception.ExceptionHandler; +import christmas.view.InputView; +import christmas.view.OutputView; +import java.util.Map; + +public class ChristmasController { + + private final ExceptionHandler handler; + private Customer customer; + private EventPlanner eventPlanner; + + + public ChristmasController(ExceptionHandler handler){ + this.handler = handler; + } + + public void service(){ + order(); + searchPromotion(customer); + } + + public void order(){ + int date = getDate(); + Map<Menu, Integer> menu = getMenu(); + customer = new Customer(date, menu); + + displayOrder(date, menu); + } + + private int getDate(){ + return handler.getResult(InputView::readVisitDate); + } + + private Map<Menu, Integer> getMenu(){ + return handler.getResult(InputView::readMenu); + } + + private void searchPromotion(Customer customer){ + eventPlanner = new EventPlanner(); + eventPlanner.findPromotion(customer); + + BenefitStorage benefitStorage = storeBenefits(); + previewEventBenefits(benefitStorage); + } + + private BenefitStorage storeBenefits(){ + if(eventPlanner.hasGiftMenu()){ + return new BenefitStorage(customer.getTotalOrderAmount(), true, eventPlanner.getPromotionResult()); + } + return new BenefitStorage(customer.getTotalOrderAmount(), false, eventPlanner.getPromotionResult()); + } + + private void displayOrder(int date, Map<Menu, Integer> menu){ + OrderMenu orderMenu = new OrderMenu(date, menu); + OutputView.printOrder(orderMenu); + } + + + private void previewEventBenefits(BenefitStorage benefitStorage){ + BenefitResult benefitResult = new BenefitResult(benefitStorage.getBeforeDiscountAmount(), + benefitStorage.isGiftMenu(), benefitStorage.getPromotionResult(), benefitStorage.totalBenefitAmount(), + benefitStorage.afterDiscountAmount(), benefitStorage.determineBadge()); + OutputView.printPreview(benefitResult); + } + +}
Java
์‚ฌ์†Œํ•˜์ง€๋งŒ ๋„ค์ด๋ฐ์„ `OrderedMenu` ๋กœ ํ•˜๋ฉด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,74 @@ +package christmas.controller; + +import christmas.constant.Menu; +import christmas.domain.BenefitStorage; +import christmas.dto.BenefitResult; +import christmas.domain.Customer; +import christmas.domain.EventPlanner; +import christmas.dto.OrderMenu; +import christmas.exception.ExceptionHandler; +import christmas.view.InputView; +import christmas.view.OutputView; +import java.util.Map; + +public class ChristmasController { + + private final ExceptionHandler handler; + private Customer customer; + private EventPlanner eventPlanner; + + + public ChristmasController(ExceptionHandler handler){ + this.handler = handler; + } + + public void service(){ + order(); + searchPromotion(customer); + } + + public void order(){ + int date = getDate(); + Map<Menu, Integer> menu = getMenu(); + customer = new Customer(date, menu); + + displayOrder(date, menu); + } + + private int getDate(){ + return handler.getResult(InputView::readVisitDate); + } + + private Map<Menu, Integer> getMenu(){ + return handler.getResult(InputView::readMenu); + } + + private void searchPromotion(Customer customer){ + eventPlanner = new EventPlanner(); + eventPlanner.findPromotion(customer); + + BenefitStorage benefitStorage = storeBenefits(); + previewEventBenefits(benefitStorage); + } + + private BenefitStorage storeBenefits(){ + if(eventPlanner.hasGiftMenu()){ + return new BenefitStorage(customer.getTotalOrderAmount(), true, eventPlanner.getPromotionResult()); + } + return new BenefitStorage(customer.getTotalOrderAmount(), false, eventPlanner.getPromotionResult()); + } + + private void displayOrder(int date, Map<Menu, Integer> menu){ + OrderMenu orderMenu = new OrderMenu(date, menu); + OutputView.printOrder(orderMenu); + } + + + private void previewEventBenefits(BenefitStorage benefitStorage){ + BenefitResult benefitResult = new BenefitResult(benefitStorage.getBeforeDiscountAmount(), + benefitStorage.isGiftMenu(), benefitStorage.getPromotionResult(), benefitStorage.totalBenefitAmount(), + benefitStorage.afterDiscountAmount(), benefitStorage.determineBadge()); + OutputView.printPreview(benefitResult); + } + +}
Java
`customer = new Customer(getDate(), getMenu());` ๋กœ ํ•œ๋ฒˆ์— ํ•ด๋„ ์ข‹์„ ๊ฑฐ ๊ฐ™์•„์š”. `getDate()` ๋‚˜ `getMenu()` ๋‘˜ ๋‹ค ๋ฉ”์„œ๋“œ ์ด๋ฆ„์œผ๋กœ ๋ญ๋ฅผ ํ•˜๋Š”์ง€ ์ •ํ™•ํžˆ ์•Œ ์ˆ˜ ์žˆ์–ด๋ณด์ž…๋‹ˆ๋‹ค.
@@ -0,0 +1,55 @@ +package christmas.domain; + +import christmas.constant.Badge; +import christmas.constant.Menu; +import christmas.domain.promotion.ChristmasPromotion; +import java.util.Arrays; +import java.util.HashMap; + +public class BenefitStorage { + + private final long beforeDiscountAmount; + private final boolean giftMenu; + private final HashMap<ChristmasPromotion, Long> promotionResult; + + public BenefitStorage(long beforeDiscountAmount, boolean giftMenu, HashMap<ChristmasPromotion, Long> promotionResult){ + this.beforeDiscountAmount = beforeDiscountAmount; + this.giftMenu = giftMenu; + this.promotionResult = promotionResult; + } + + public long totalBenefitAmount() { + return promotionResult.values().stream().mapToLong(Long::longValue).sum(); + } + + public long afterDiscountAmount() { + long totalBenefit = totalBenefitAmount(); + + if (giftMenu) { + totalBenefit -= Menu.CHAMPAGNE.getPrice(); + } + + return beforeDiscountAmount - totalBenefit; + } + + public Badge determineBadge() { + long totalBenefit = totalBenefitAmount(); + + return Arrays.stream(Badge.values()) + .filter(badge -> totalBenefit >= badge.getPrize()) + .reduce((first, second) -> second) + .orElse(Badge.NONE); + } + + public long getBeforeDiscountAmount() { + return beforeDiscountAmount; + } + + public boolean isGiftMenu() { + return giftMenu; + } + + public HashMap<ChristmasPromotion, Long> getPromotionResult() { + return promotionResult; + } +}
Java
Map ํƒ€์ž…์œผ๋กœ ์ธ์Šคํ„ด์Šค ๋ณ€์ˆ˜๋ฅผ ๊ฐ€์ง€๋ฉด ์ถ”ํ›„ ์„ธ๋ถ€ ๊ตฌํ˜„ ์ž๋ฃŒ๊ตฌ์กฐ๊ฐ€ ๋ฐ”๋€” ๋•Œ ๋Šฅ๋™์ ์œผ๋กœ ๋Œ€์ฒ˜ํ•  ์ˆ˜ ์žˆ์„๊ฑฐ ๊ฐ™์•„์š”!
@@ -0,0 +1,55 @@ +package christmas.domain; + +import christmas.constant.Badge; +import christmas.constant.Menu; +import christmas.domain.promotion.ChristmasPromotion; +import java.util.Arrays; +import java.util.HashMap; + +public class BenefitStorage { + + private final long beforeDiscountAmount; + private final boolean giftMenu; + private final HashMap<ChristmasPromotion, Long> promotionResult; + + public BenefitStorage(long beforeDiscountAmount, boolean giftMenu, HashMap<ChristmasPromotion, Long> promotionResult){ + this.beforeDiscountAmount = beforeDiscountAmount; + this.giftMenu = giftMenu; + this.promotionResult = promotionResult; + } + + public long totalBenefitAmount() { + return promotionResult.values().stream().mapToLong(Long::longValue).sum(); + } + + public long afterDiscountAmount() { + long totalBenefit = totalBenefitAmount(); + + if (giftMenu) { + totalBenefit -= Menu.CHAMPAGNE.getPrice(); + } + + return beforeDiscountAmount - totalBenefit; + } + + public Badge determineBadge() { + long totalBenefit = totalBenefitAmount(); + + return Arrays.stream(Badge.values()) + .filter(badge -> totalBenefit >= badge.getPrize()) + .reduce((first, second) -> second) + .orElse(Badge.NONE); + } + + public long getBeforeDiscountAmount() { + return beforeDiscountAmount; + } + + public boolean isGiftMenu() { + return giftMenu; + } + + public HashMap<ChristmasPromotion, Long> getPromotionResult() { + return promotionResult; + } +}
Java
์–ด์ฐŒ๋ณด๋ฉด Dto์— ๊ฐ€๊นŒ์šด ์„ฑ๊ฒฉ์„ ๊ฐ€์ง€๋Š” ํด๋ž˜์Šค์ธ๋ฐ ๋„๋ฉ”์ธ ๋กœ์ง์„ ๋‹ค ๋„ฃ์–ด๋‘” ๋А๋‚Œ์„ ๋ฐ›์•˜์Šต๋‹ˆ๋‹ค. ๊ฒฐ๊ตญ ์ถœ๋ ฅ๋•Œ ํ•„์š”ํ•œ ์ž๋ฃŒ๋“ค์„ ๋‹ค ๊ฐ€์ง€๊ณ  ์žˆ์–ด์„œ ๋„๋ฉ”์ธ์„ ๋‹ค๋ฅธ ๋ฐฉ์‹์œผ๋กœ ๋ถ„๋ฆฌํ•ด๋ณด๋Š” ๊ฒƒ์„ ๊ณ ๋ คํ•ด๋ณด๋ฉด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,71 @@ +package christmas.domain; + +import christmas.constant.MenuType; +import christmas.constant.PromotionType; +import christmas.domain.promotion.ChristmasPromotion; +import christmas.domain.promotion.DdayPromotion; +import christmas.domain.promotion.GiftPromotion; +import christmas.domain.promotion.SpecialPromotion; +import christmas.domain.promotion.WeekDayPromotion; +import christmas.domain.promotion.WeekendPromotion; +import java.util.HashMap; +import java.util.Map; + +public class EventPlanner { + private final HashMap<ChristmasPromotion, Long> promotionResult; + + public EventPlanner(){ + promotionResult = new HashMap<>(); + promotionResult.put(new DdayPromotion(), 0L); + promotionResult.put(new GiftPromotion(), 0L); + promotionResult.put(new SpecialPromotion(), 0L); + promotionResult.put(new WeekDayPromotion(), 0L); + promotionResult.put(new WeekendPromotion(), 0L); + } + + public void findPromotion(Customer customer){ + for(ChristmasPromotion promotion : promotionResult.keySet()){ + checkPromotionConditions(promotion, customer); + } + } + + public boolean hasGiftMenu(){ + return promotionResult.entrySet() + .stream() + .filter(entry -> entry.getKey() instanceof GiftPromotion) + .mapToLong(Map.Entry::getValue) + .sum() > 0; + } + + public HashMap<ChristmasPromotion, Long> getPromotionResult(){ + return promotionResult; + } + + private void checkPromotionConditions(ChristmasPromotion promotion, Customer customer){ + long discount = customer.applicablePromotion(promotion); + + if (isContainWeekOrWeekend(promotion)) { + discount *= checkMenuCount(customer, promotion.getPromotionType()); + } + promotionResult.put(promotion, promotionResult.get(promotion) + discount); + } + + private int checkMenuCount(Customer customer, PromotionType promotionType) { + Map<PromotionType, MenuType> promotionTypeMenuTypeMap = Map.of( + PromotionType.WEEKDAY, MenuType.DESSERT, + PromotionType.WEEKEND, MenuType.MAIN + ); + + MenuType menuType = promotionTypeMenuTypeMap.getOrDefault(promotionType, MenuType.NONE); + return customer.countMenuType(menuType); + } + + private boolean isContainWeekOrWeekend(ChristmasPromotion promotion){ + if(promotion.getPromotionType() == PromotionType.WEEKDAY + || promotion.getPromotionType() == PromotionType.WEEKEND) + return true; + + return false; + } + +}
Java
๋ณ€์ˆ˜ ๋ช…์— Map ์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ๋ณด๋‹ค๋Š” `PromotionsAppliedToEachMenu` ์™€ ๊ฐ™์ด ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์€ ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,43 @@ +package christmas.domain.promotion; + +import christmas.constant.PromotionItem; +import christmas.constant.PromotionType; +import java.util.Arrays; + +public class DdayPromotion extends ChristmasPromotion{ + + private static final int START_DATE = 1; + private static final int END_DATE = 25; + private static final int INIT_DISCOUNT_AMOUNT = 1000; + private static final int MIN_ORDER_AMOUNT = 10000; + + + public DdayPromotion(){ + this.period = Arrays.asList(START_DATE, END_DATE); + this.targetItems = PromotionItem.TOTAL_ORDER_AMOUNT; + this.discountAmount = INIT_DISCOUNT_AMOUNT; + this.promotionType = PromotionType.DDAY; + } + + @Override + public long applyPromotion(int data, long orderAmount){ + if(isApplicable(data) && isEligibleForPromotion(orderAmount)){ + return getDiscountAmount(data); + } + return 0L; + } + + @Override + protected boolean isApplicable(int date) { + return date >= period.get(0) && date <= period.get(1); + } + + @Override + protected boolean isEligibleForPromotion(long orderAmount){ + return orderAmount >= MIN_ORDER_AMOUNT; + } + + public long getDiscountAmount(int date) { + return discountAmount + 100L * (date - 1); + } +}
Java
๋งค์ง๋„˜๋ฒ„๋ฅผ ์ƒ์ˆ˜๋กœ ๋‘๋Š”๊ฑด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,39 @@ +package christmas.domain.promotion; + +import christmas.constant.PromotionItem; +import christmas.constant.PromotionType; +import java.util.Arrays; + +public class GiftPromotion extends ChristmasPromotion{ + + private static final long PRICETHRESHOLD = 120000; + private static final int START_DATE = 1; + private static final int END_DATE = 31; + private static final int INIT_DISCOUNT_AMOUNT = 25000; + + public GiftPromotion(){ + this.period = Arrays.asList(START_DATE, END_DATE); + this.targetItems = PromotionItem.GIFT_CHAMPAGNE; + this.discountAmount = INIT_DISCOUNT_AMOUNT; + this.promotionType = PromotionType.GIFT; + } + + @Override + public long applyPromotion(int data, long orderAmount){ + if(isApplicable(data) && isEligibleForPromotion(orderAmount)){ + return getDiscountAmount(); + } + return 0L; + } + + @Override + protected boolean isApplicable(int date) { + return date >= period.get(0) && date <= period.get(1); + } + + @Override + protected boolean isEligibleForPromotion(long orderAmount){ + return orderAmount >= PRICETHRESHOLD; + } + +}
Java
`PRICE_THRESHOLD` ์™€ ๊ฐ™์ด ๋‚˜๋ˆ ์ฃผ๋ฉด ๊ฐ€๋…์„ฑ์ด ๋” ์ข‹์•„์งˆ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,38 @@ +package christmas.domain.promotion; + +import christmas.constant.PromotionItem; +import christmas.constant.PromotionType; +import java.util.Arrays; + +public class SpecialPromotion extends ChristmasPromotion{ + + private static final int INIT_DISCOUNT_AMOUNT = 1000; + private static final int MIN_ORDER_AMOUNT = 10000; + + public SpecialPromotion(){ + this.period = Arrays.asList(3, 10, 17, 24, 25, 31); + this.targetItems = PromotionItem.TOTAL_ORDER_AMOUNT; + this.discountAmount = INIT_DISCOUNT_AMOUNT; + this.promotionType = PromotionType.SPECIAL; + } + + @Override + public long applyPromotion(int data, long orderAmount){ + if(isApplicable(data) && isEligibleForPromotion(orderAmount)){ + return getDiscountAmount(); + } + return 0L; + } + + @Override + protected boolean isApplicable(int date) { + return period.contains(date); + } + + @Override + protected boolean isEligibleForPromotion(long orderAmount){ + return orderAmount >= MIN_ORDER_AMOUNT; + } + + +}
Java
์š”๊ฒƒ๋„ ๋งค์ง๋„˜๋ฒ„! ํ˜น์€ 1~31 ๊ฐ’ ์ค‘ 7๋กœ ๋‚˜๋ˆ„์—ˆ์„ ๋•Œ ๋‚˜๋จธ์ง€๊ฐ€ 3์ธ ๋‚ ์งœ๋กœ ์ดˆ๊ธฐํ™”ํ•ด์ค˜๋„ ์ข‹์„ ๊ฑฐ ๊ฐ™์•„์š”
@@ -0,0 +1,38 @@ +package christmas.domain.promotion; + +import christmas.constant.PromotionItem; +import christmas.constant.PromotionType; +import java.util.Arrays; + +public class SpecialPromotion extends ChristmasPromotion{ + + private static final int INIT_DISCOUNT_AMOUNT = 1000; + private static final int MIN_ORDER_AMOUNT = 10000; + + public SpecialPromotion(){ + this.period = Arrays.asList(3, 10, 17, 24, 25, 31); + this.targetItems = PromotionItem.TOTAL_ORDER_AMOUNT; + this.discountAmount = INIT_DISCOUNT_AMOUNT; + this.promotionType = PromotionType.SPECIAL; + } + + @Override + public long applyPromotion(int data, long orderAmount){ + if(isApplicable(data) && isEligibleForPromotion(orderAmount)){ + return getDiscountAmount(); + } + return 0L; + } + + @Override + protected boolean isApplicable(int date) { + return period.contains(date); + } + + @Override + protected boolean isEligibleForPromotion(long orderAmount){ + return orderAmount >= MIN_ORDER_AMOUNT; + } + + +}
Java
๊ณต๋ฐฑ๋„ ์ฝ”๋”ฉ์ปจ๋ฒค์…˜์ด๋ผ, ๋‹ค๋ฅธ ํด๋ž˜์Šค ํŒŒ์ผ๊ณผ ๋งž์ถฐ์ฃผ๋Š”๊ฒŒ ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,47 @@ +package christmas.domain.promotion; + +import christmas.constant.PromotionItem; +import christmas.constant.PromotionType; +import java.time.LocalDate; +import java.time.DayOfWeek; +import java.util.Arrays; + +public class WeekDayPromotion extends ChristmasPromotion{ + + private static final int START_DATE = 1; + private static final int END_DATE = 31; + private static final int INIT_DISCOUNT_AMOUNT = 2023; + private static final int MIN_ORDER_AMOUNT = 10000; + + public WeekDayPromotion(){ + this.period = Arrays.asList(START_DATE, END_DATE); + this.targetItems = PromotionItem.DESSERT_MENU; + this.discountAmount = INIT_DISCOUNT_AMOUNT; + this.promotionType = PromotionType.WEEKDAY; + } + + @Override + public long applyPromotion(int data, long orderAmount){ + if(isApplicable(data) && isEligibleForPromotion(orderAmount)){ + return getDiscountAmount(); + } + return 0L; + } + + @Override + protected boolean isApplicable(int date) { + LocalDate orderDate = LocalDate.of(2023, 12, date); + + return isWeekday(orderDate); + } + + @Override + protected boolean isEligibleForPromotion(long orderAmount){ + return orderAmount >= MIN_ORDER_AMOUNT; + } + + private boolean isWeekday(LocalDate date) { + DayOfWeek dayOfWeek = date.getDayOfWeek(); + return dayOfWeek != DayOfWeek.FRIDAY && dayOfWeek != DayOfWeek.SATURDAY; + } +}
Java
๋‚ด๋ถ€ ์ƒ์ˆ˜๋กœ ๋‘๋Š” ๊ฒƒ๋ณด๋‹ค, ์ƒ์„ฑ๋  ๋•Œ ์œ„์˜ ์ƒ์ˆ˜ ๊ฐ’์œผ๋กœ ์ดˆ๊ธฐํ™” ์‹œํ‚ค๊ณ  ๊ฐ์ฒด๋ฅผ ์‹ฑ๊ธ€ํ†ค์œผ๋กœ ๊ด€๋ฆฌํ•˜๋Š” ๊ฒƒ๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”
@@ -0,0 +1,7 @@ +package christmas.exception; + +import java.util.function.Supplier; + +public interface ExceptionHandler { + <T> T getResult(Supplier<T> supplier); +}
Java
`Supplier` ๋ผ๋Š” ๋ฌธ๋ฒ•์€ ์ฒ˜์Œ๋ณด๋„ค์š”! ํ•จ์ˆ˜ํ˜• ํ”„๋กœ๊ทธ๋ž˜๋ฐ? ์ธ๊ฐ€ ๋ณด๋„ค์š” ใ…Žใ…Ž ๋ฐฐ์›Œ๊ฐ‘๋‹ˆ๋‹ค.
@@ -0,0 +1,28 @@ +package christmas.exception; + +import christmas.view.OutputView; +import java.util.function.Supplier; + +public class RetryExceptionHandler implements ExceptionHandler{ + + @Override + public <T> T getResult(Supplier<T> supplier) { + while (true) { + try { + return supplier.get(); + } catch (IllegalArgumentException e) { + printException(e); + } finally { + afterHandlingException(); + } + } + } + + private void printException(IllegalArgumentException e) { + OutputView.printErrorMessage(e); + } + + private void afterHandlingException() { + OutputView.printEmptyLine(); + } +}
Java
์ด๋ ‡๊ฒŒ ํ•˜๋ฉด try-catch๋ฌธ์˜ ์ค‘๋ณต ๋กœ์ง์„ ๋บ„ ์ˆ˜ ์žˆ๊ฒ ๊ตฐ์š”.!
@@ -0,0 +1,119 @@ +package christmas.validator; + +import christmas.constant.Menu; +import christmas.constant.MenuType; +import christmas.exception.ErrorCode; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class InputValidator { + + private static int START_DATE = 1; + private static int END_DATE = 31; + private static String COMMA = ","; + private static String HYPHEN = "-"; + private static int MENU_FORMAT_LENGTH = 2; + private static int MINIMUM_ORDER_COUNT = 1; + private static int MAXIMUN_ORDER_COUNT = 20; + + public static void validateVisitDate(String input){ + validateInteger(input); + validateNumberInRange(Integer.parseInt(input)); + } + + public static Map<Menu, Integer> validateMenuOrder(String input, Map<Menu, Integer> orderMenu){ + String[] orders = input.split(COMMA); + Set<Menu> uniqueMenu = new HashSet<>(); + + for (String order : orders) { + validate(order, orderMenu, uniqueMenu); + } + + validateOnlyBeverage(orderMenu); + validateMaxOrder(orderMenu); + + return orderMenu; + } + + private static void validate(String order, Map<Menu, Integer> orderMenu, Set<Menu> uniqueMenu){ + String[] parts = validateMenuOrderFormat(order.trim()); + + String menuName = parts[0]; + String quantity = parts[1]; + + Menu menu = getMenuByName(menuName); + + validateMenuFound(menu); + validateMinimumOrder(quantity); + validateDuplicateMenu(menu, uniqueMenu); + + orderMenu.put(menu, Integer.parseInt(quantity)); + } + + private static void validateInteger(String input){ + if(!input.chars().allMatch(Character::isDigit)){ + throw new IllegalArgumentException(ErrorCode.INVALID_DATE.getMessage()); + } + } + + private static void validateNumberInRange(int input){ + if(input > END_DATE || input < START_DATE) + throw new IllegalArgumentException(ErrorCode.INVALID_DATE.getMessage()); + } + + private static String[] validateMenuOrderFormat(String orders){ + String[] parts = orders.split(HYPHEN); + if (parts.length != MENU_FORMAT_LENGTH) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + + return parts; + } + + private static void validateMenuFound(Menu menu){ + if(menu == null) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateMinimumOrder(String quantity){ + if(!quantity.chars().allMatch(Character::isDigit)) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + + if(Integer.parseInt(quantity) < MINIMUM_ORDER_COUNT) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateMaxOrder(Map<Menu, Integer> orderMenu){ + int orderCount = 0; + for(Menu menu: orderMenu.keySet()) { + orderCount += orderMenu.get(menu); + } + + if(orderCount > MAXIMUN_ORDER_COUNT) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateDuplicateMenu(Menu menu, Set<Menu> uniqueMenu){ + if(!uniqueMenu.add(menu)) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + + private static void validateOnlyBeverage(Map<Menu, Integer> orderMenu){ + boolean allBeverages = orderMenu.keySet().stream() + .allMatch(menu -> menu.getMenuType() == MenuType.BEVERAGE); + + if (allBeverages) { + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + } + + private static Menu getMenuByName(String name) { + for (Menu menu : Menu.values()) { + if (menu.getName().equalsIgnoreCase(name)) { + return menu; + } + } + return null; + } +}
Java
ํ•ด๋‹น ๋ฉ”์„œ๋“œ๋Š” Map์„ ๋ฐ˜ํ™˜ํ•˜๊ธฐ ๋ณด๋‹ค๋Š” void ํ˜•์‹์œผ๋กœ ์˜ˆ์™ธ๋ฅผ ๋˜์งˆ ๊ฒƒ ๊ฐ™์€ ๋„ค์ด๋ฐ์ด๋ผ ๋А๊ปด์ ธ์š”. ์—ญํ• ์„ ๊ฒ€์ฆ ๋ฐ ๋ฐ˜ํ™˜ ๋‘๊ฐœ๋ฅผ ํ•˜๋Š” ๊ฒƒ ๊ฐ™์€๋ฐ ๊ฐ ์—ญํ• ์— ๋งž๋Š” ๋ฉ”์„œ๋“œ๋กœ ๋‚˜๋ˆ ๋ณด๋Š” ๊ฒƒ์€ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”?
@@ -0,0 +1,119 @@ +package christmas.validator; + +import christmas.constant.Menu; +import christmas.constant.MenuType; +import christmas.exception.ErrorCode; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class InputValidator { + + private static int START_DATE = 1; + private static int END_DATE = 31; + private static String COMMA = ","; + private static String HYPHEN = "-"; + private static int MENU_FORMAT_LENGTH = 2; + private static int MINIMUM_ORDER_COUNT = 1; + private static int MAXIMUN_ORDER_COUNT = 20; + + public static void validateVisitDate(String input){ + validateInteger(input); + validateNumberInRange(Integer.parseInt(input)); + } + + public static Map<Menu, Integer> validateMenuOrder(String input, Map<Menu, Integer> orderMenu){ + String[] orders = input.split(COMMA); + Set<Menu> uniqueMenu = new HashSet<>(); + + for (String order : orders) { + validate(order, orderMenu, uniqueMenu); + } + + validateOnlyBeverage(orderMenu); + validateMaxOrder(orderMenu); + + return orderMenu; + } + + private static void validate(String order, Map<Menu, Integer> orderMenu, Set<Menu> uniqueMenu){ + String[] parts = validateMenuOrderFormat(order.trim()); + + String menuName = parts[0]; + String quantity = parts[1]; + + Menu menu = getMenuByName(menuName); + + validateMenuFound(menu); + validateMinimumOrder(quantity); + validateDuplicateMenu(menu, uniqueMenu); + + orderMenu.put(menu, Integer.parseInt(quantity)); + } + + private static void validateInteger(String input){ + if(!input.chars().allMatch(Character::isDigit)){ + throw new IllegalArgumentException(ErrorCode.INVALID_DATE.getMessage()); + } + } + + private static void validateNumberInRange(int input){ + if(input > END_DATE || input < START_DATE) + throw new IllegalArgumentException(ErrorCode.INVALID_DATE.getMessage()); + } + + private static String[] validateMenuOrderFormat(String orders){ + String[] parts = orders.split(HYPHEN); + if (parts.length != MENU_FORMAT_LENGTH) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + + return parts; + } + + private static void validateMenuFound(Menu menu){ + if(menu == null) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateMinimumOrder(String quantity){ + if(!quantity.chars().allMatch(Character::isDigit)) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + + if(Integer.parseInt(quantity) < MINIMUM_ORDER_COUNT) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateMaxOrder(Map<Menu, Integer> orderMenu){ + int orderCount = 0; + for(Menu menu: orderMenu.keySet()) { + orderCount += orderMenu.get(menu); + } + + if(orderCount > MAXIMUN_ORDER_COUNT) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateDuplicateMenu(Menu menu, Set<Menu> uniqueMenu){ + if(!uniqueMenu.add(menu)) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + + private static void validateOnlyBeverage(Map<Menu, Integer> orderMenu){ + boolean allBeverages = orderMenu.keySet().stream() + .allMatch(menu -> menu.getMenuType() == MenuType.BEVERAGE); + + if (allBeverages) { + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + } + + private static Menu getMenuByName(String name) { + for (Menu menu : Menu.values()) { + if (menu.getName().equalsIgnoreCase(name)) { + return menu; + } + } + return null; + } +}
Java
์กฐ๊ฑด๋ฌธ์˜ ์กฐ๊ฑด์„ ํ•˜๋‚˜์˜ ๋ฉ”์„œ๋“œ๋กœ ๋นผ๋Š” ๊ฒƒ๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,119 @@ +package christmas.validator; + +import christmas.constant.Menu; +import christmas.constant.MenuType; +import christmas.exception.ErrorCode; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class InputValidator { + + private static int START_DATE = 1; + private static int END_DATE = 31; + private static String COMMA = ","; + private static String HYPHEN = "-"; + private static int MENU_FORMAT_LENGTH = 2; + private static int MINIMUM_ORDER_COUNT = 1; + private static int MAXIMUN_ORDER_COUNT = 20; + + public static void validateVisitDate(String input){ + validateInteger(input); + validateNumberInRange(Integer.parseInt(input)); + } + + public static Map<Menu, Integer> validateMenuOrder(String input, Map<Menu, Integer> orderMenu){ + String[] orders = input.split(COMMA); + Set<Menu> uniqueMenu = new HashSet<>(); + + for (String order : orders) { + validate(order, orderMenu, uniqueMenu); + } + + validateOnlyBeverage(orderMenu); + validateMaxOrder(orderMenu); + + return orderMenu; + } + + private static void validate(String order, Map<Menu, Integer> orderMenu, Set<Menu> uniqueMenu){ + String[] parts = validateMenuOrderFormat(order.trim()); + + String menuName = parts[0]; + String quantity = parts[1]; + + Menu menu = getMenuByName(menuName); + + validateMenuFound(menu); + validateMinimumOrder(quantity); + validateDuplicateMenu(menu, uniqueMenu); + + orderMenu.put(menu, Integer.parseInt(quantity)); + } + + private static void validateInteger(String input){ + if(!input.chars().allMatch(Character::isDigit)){ + throw new IllegalArgumentException(ErrorCode.INVALID_DATE.getMessage()); + } + } + + private static void validateNumberInRange(int input){ + if(input > END_DATE || input < START_DATE) + throw new IllegalArgumentException(ErrorCode.INVALID_DATE.getMessage()); + } + + private static String[] validateMenuOrderFormat(String orders){ + String[] parts = orders.split(HYPHEN); + if (parts.length != MENU_FORMAT_LENGTH) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + + return parts; + } + + private static void validateMenuFound(Menu menu){ + if(menu == null) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateMinimumOrder(String quantity){ + if(!quantity.chars().allMatch(Character::isDigit)) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + + if(Integer.parseInt(quantity) < MINIMUM_ORDER_COUNT) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateMaxOrder(Map<Menu, Integer> orderMenu){ + int orderCount = 0; + for(Menu menu: orderMenu.keySet()) { + orderCount += orderMenu.get(menu); + } + + if(orderCount > MAXIMUN_ORDER_COUNT) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateDuplicateMenu(Menu menu, Set<Menu> uniqueMenu){ + if(!uniqueMenu.add(menu)) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + + private static void validateOnlyBeverage(Map<Menu, Integer> orderMenu){ + boolean allBeverages = orderMenu.keySet().stream() + .allMatch(menu -> menu.getMenuType() == MenuType.BEVERAGE); + + if (allBeverages) { + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + } + + private static Menu getMenuByName(String name) { + for (Menu menu : Menu.values()) { + if (menu.getName().equalsIgnoreCase(name)) { + return menu; + } + } + return null; + } +}
Java
null ์„ ์ง์ ‘ ๋‹ค๋ฃจ๋Š” ๊ฒƒ๋ณด๋‹ค, Menu ๋‚ด์—์„œ ์ด๋ฆ„์„ ๋ฐ›์•„์„œ Menu์˜ ์œ ๋ฌด๋ฅผ ์ฒ˜๋ฆฌํ•˜๋Š” ๋ฉ”์„œ๋“œ๋ฅผ ๋งŒ๋“œ๋Š” ๊ฒƒ์€ ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,119 @@ +package christmas.validator; + +import christmas.constant.Menu; +import christmas.constant.MenuType; +import christmas.exception.ErrorCode; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class InputValidator { + + private static int START_DATE = 1; + private static int END_DATE = 31; + private static String COMMA = ","; + private static String HYPHEN = "-"; + private static int MENU_FORMAT_LENGTH = 2; + private static int MINIMUM_ORDER_COUNT = 1; + private static int MAXIMUN_ORDER_COUNT = 20; + + public static void validateVisitDate(String input){ + validateInteger(input); + validateNumberInRange(Integer.parseInt(input)); + } + + public static Map<Menu, Integer> validateMenuOrder(String input, Map<Menu, Integer> orderMenu){ + String[] orders = input.split(COMMA); + Set<Menu> uniqueMenu = new HashSet<>(); + + for (String order : orders) { + validate(order, orderMenu, uniqueMenu); + } + + validateOnlyBeverage(orderMenu); + validateMaxOrder(orderMenu); + + return orderMenu; + } + + private static void validate(String order, Map<Menu, Integer> orderMenu, Set<Menu> uniqueMenu){ + String[] parts = validateMenuOrderFormat(order.trim()); + + String menuName = parts[0]; + String quantity = parts[1]; + + Menu menu = getMenuByName(menuName); + + validateMenuFound(menu); + validateMinimumOrder(quantity); + validateDuplicateMenu(menu, uniqueMenu); + + orderMenu.put(menu, Integer.parseInt(quantity)); + } + + private static void validateInteger(String input){ + if(!input.chars().allMatch(Character::isDigit)){ + throw new IllegalArgumentException(ErrorCode.INVALID_DATE.getMessage()); + } + } + + private static void validateNumberInRange(int input){ + if(input > END_DATE || input < START_DATE) + throw new IllegalArgumentException(ErrorCode.INVALID_DATE.getMessage()); + } + + private static String[] validateMenuOrderFormat(String orders){ + String[] parts = orders.split(HYPHEN); + if (parts.length != MENU_FORMAT_LENGTH) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + + return parts; + } + + private static void validateMenuFound(Menu menu){ + if(menu == null) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateMinimumOrder(String quantity){ + if(!quantity.chars().allMatch(Character::isDigit)) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + + if(Integer.parseInt(quantity) < MINIMUM_ORDER_COUNT) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateMaxOrder(Map<Menu, Integer> orderMenu){ + int orderCount = 0; + for(Menu menu: orderMenu.keySet()) { + orderCount += orderMenu.get(menu); + } + + if(orderCount > MAXIMUN_ORDER_COUNT) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateDuplicateMenu(Menu menu, Set<Menu> uniqueMenu){ + if(!uniqueMenu.add(menu)) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + + private static void validateOnlyBeverage(Map<Menu, Integer> orderMenu){ + boolean allBeverages = orderMenu.keySet().stream() + .allMatch(menu -> menu.getMenuType() == MenuType.BEVERAGE); + + if (allBeverages) { + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + } + + private static Menu getMenuByName(String name) { + for (Menu menu : Menu.values()) { + if (menu.getName().equalsIgnoreCase(name)) { + return menu; + } + } + return null; + } +}
Java
์ด ๋ถ€๋ถ„์—์„œ Exception์„ ๋˜์ ธ์ฃผ๋Š” ๊ฒƒ๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,44 @@ +package christmas.view; + +import christmas.constant.Badge; +import christmas.constant.OutputMessage; +import christmas.domain.promotion.ChristmasPromotion; +import java.util.HashMap; + +public class BenefitsView { + + public static String giftMenuOutputStatement(boolean giftMenu){ + if(giftMenu) + return OutputMessage.CHAMPAGNE.getMessage(); + + return OutputMessage.DOES_NOT_EXIST.getMessage(); + } + + public static String promotionResultOutputStatement(long totalBenefitAmount, HashMap<ChristmasPromotion, Long> promotionResult){ + if(totalBenefitAmount == 0) + return OutputMessage.DOES_NOT_EXIST.getMessage(); + + return findPromotionDetail(promotionResult).toString(); + } + + public static String badgeOutputStatement(Badge badge){ + if(badge == Badge.NONE) + return OutputMessage.DOES_NOT_EXIST.getMessage(); + return badge.getBadgeName(); + } + + private static StringBuilder findPromotionDetail(HashMap<ChristmasPromotion, Long> promotionResult){ + StringBuilder sb = new StringBuilder(); + for(ChristmasPromotion promotion: promotionResult.keySet()){ + long discount = promotionResult.get(promotion); + if(discount == 0) continue; + + sb.append(String.format(OutputMessage.BENEFIT_DETAILS.getMessage(), + promotion.getPromotionType().getMessage(), discount)); + } + + if(sb.isEmpty()) + return sb.append(OutputMessage.DOES_NOT_EXIST.getMessage()); + return sb; + } +}
Java
if ๋ฌธ ์„ {} ๋กœ ๊ฐ์‹ธ์ฃผ๋Š”๊ฒŒ ์ฝ”๋”ฉ ์ปจ๋ฒค์…˜์œผ๋กœ ์•Œ๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,74 @@ +package christmas.view; + +import christmas.constant.Badge; +import christmas.constant.Menu; +import christmas.constant.OutputMessage; +import christmas.domain.promotion.ChristmasPromotion; +import christmas.dto.BenefitResult; +import christmas.dto.OrderMenu; +import java.util.HashMap; +import java.util.Map; + +public class OutputView { + + public static void printErrorMessage(IllegalArgumentException e){ + System.out.println(e.getMessage()); + } + + public static void printEmptyLine(){ + System.out.println(); + } + + public static void printOrder(OrderMenu orderMenu){ + printDate(orderMenu.date()); + printEmptyLine(); + printOrderedMenu(orderMenu.menu()); + } + + public static void printPreview(BenefitResult benefits){ + printBeforeDiscountAmount(benefits.beforeDiscountAmount()); + printHasGift(benefits.giftMenu()); + printBenefitsDetail(benefits.beforeDiscountAmount(), benefits.promotionResult()); + printTotalBenefits(benefits.totalBenefitAmount()); + printAfterDiscountAmount(benefits.afterDiscountAmount()); + printBadge(benefits.badge()); + } + + private static void printOrderedMenu(Map<Menu, Integer> orderMenu){ + System.out.println(String.format(OutputMessage.ORDER_MENU_PREFIX.getMessage(), + OrderMenuView.orderMenuOutputStatement(orderMenu))); + } + + private static void printDate(int date){ + System.out.println(String.format(OutputMessage.RESERVATION_DATE.getMessage(), date)); + } + + private static void printBeforeDiscountAmount(long total){ + System.out.println(String.format(OutputMessage.BEFORE_DISCOUNT_AMOUNT.getMessage(), total)); + } + + private static void printHasGift(boolean hasGift){ + System.out.println(String.format(OutputMessage.GIVEAWAY_MENU.getMessage(), + BenefitsView.giftMenuOutputStatement(hasGift))); + + } + + private static void printBenefitsDetail(long price, HashMap<ChristmasPromotion, Long> result){ + System.out.println(String.format(OutputMessage.BENEFIT_DETAILS_PREFIX.getMessage(), + BenefitsView.promotionResultOutputStatement(price, result))); + } + + private static void printTotalBenefits(long price){ + System.out.println(String.format(OutputMessage.TOTAL_BENEFIT_AMOUNT.getMessage(), -price)); + } + + private static void printAfterDiscountAmount(long price){ + System.out.println(String.format(OutputMessage.AFTER_DISCOUNT_AMOUNT.getMessage(), price)); + } + + private static void printBadge(Badge badge){ + System.out.println(String.format(OutputMessage.PROMOTION_BADGE.getMessage(), + BenefitsView.badgeOutputStatement(badge))); + } + +}
Java
์˜ˆ์™ธ๋ฅผ ์ง์ ‘ ๋ฐ›๋Š” ๊ฒƒ๋ณด๋‹ค ์˜ˆ์™ธ๋ฅผ ๋˜์ง€๋Š” ์ชฝ์—์„œ e.getMessage() ๋กœ String ๊ฐ’์„ ๋˜์ ธ์ฃผ๋ฉด ๋ฉ”์„œ๋“œ๊ฐ€ ์ข€ ๋” ๋ฒ”์šฉ์„ฑ์ด ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,27 @@ +package christmas.constant; + +public enum OutputMessage { + + RESERVATION_DATE("12์›” %d์ผ์— ์šฐํ…Œ์ฝ” ์‹๋‹น์—์„œ ๋ฐ›์„ ์ด๋ฒคํŠธ ํ˜œํƒ ๋ฏธ๋ฆฌ ๋ณด๊ธฐ!"), + ORDER_MENU_PREFIX("<์ฃผ๋ฌธ ๋ฉ”๋‰ด>%n%s"), + ORDER_MENU("%s %d๊ฐœ\n"), + BEFORE_DISCOUNT_AMOUNT("<ํ• ์ธ ์ „ ์ด์ฃผ๋ฌธ ๊ธˆ์•ก>%n%,d์›\n"), + GIVEAWAY_MENU("<์ฆ์ • ๋ฉ”๋‰ด>%n%s"), + DOES_NOT_EXIST("์—†์Œ\n"), + CHAMPAGNE("์ƒดํŽ˜์ธ 1๊ฐœ\n"), + BENEFIT_DETAILS_PREFIX("<ํ˜œํƒ ๋‚ด์—ญ>%n%s"), + BENEFIT_DETAILS("%s: %,d์›\n"), + TOTAL_BENEFIT_AMOUNT("<์ดํ˜œํƒ ๊ธˆ์•ก>%n%,d์›\n"), + AFTER_DISCOUNT_AMOUNT("<ํ• ์ธ ํ›„ ์˜ˆ์ƒ ๊ฒฐ์ œ ๊ธˆ์•ก>%n%,d์›\n"), + PROMOTION_BADGE("<12์›” ์ด๋ฒคํŠธ ๋ฐฐ์ง€>%n%s\n"); + + private final String message; + + OutputMessage(String message) { + this.message = message; + } + + public String getMessage(){ + return this.message; + } +}
Java
๊ฐœํ–‰๋ฌธ์ž๋ฅผ System.lineseparator() ๋กœ ์ฒ˜๋ฆฌํ•˜๋Š”๊ฑธ ์ถ”์ฒœ๋“œ๋ฆฝ๋‹ˆ๋‹ค! ์šด์˜์ฒด์ œ ๋ณ„๋กœ ๊ฐœํ–‰๋ฌธ์ž ํ‘œํ˜„์ด ์ƒ์ดํ•  ์ˆ˜ ์žˆ๊ฑฐ๋“ ์š”!
@@ -0,0 +1,55 @@ +package christmas.domain; + +import christmas.constant.Badge; +import christmas.constant.Menu; +import christmas.domain.promotion.ChristmasPromotion; +import java.util.Arrays; +import java.util.HashMap; + +public class BenefitStorage { + + private final long beforeDiscountAmount; + private final boolean giftMenu; + private final HashMap<ChristmasPromotion, Long> promotionResult; + + public BenefitStorage(long beforeDiscountAmount, boolean giftMenu, HashMap<ChristmasPromotion, Long> promotionResult){ + this.beforeDiscountAmount = beforeDiscountAmount; + this.giftMenu = giftMenu; + this.promotionResult = promotionResult; + } + + public long totalBenefitAmount() { + return promotionResult.values().stream().mapToLong(Long::longValue).sum(); + } + + public long afterDiscountAmount() { + long totalBenefit = totalBenefitAmount(); + + if (giftMenu) { + totalBenefit -= Menu.CHAMPAGNE.getPrice(); + } + + return beforeDiscountAmount - totalBenefit; + } + + public Badge determineBadge() { + long totalBenefit = totalBenefitAmount(); + + return Arrays.stream(Badge.values()) + .filter(badge -> totalBenefit >= badge.getPrize()) + .reduce((first, second) -> second) + .orElse(Badge.NONE); + } + + public long getBeforeDiscountAmount() { + return beforeDiscountAmount; + } + + public boolean isGiftMenu() { + return giftMenu; + } + + public HashMap<ChristmasPromotion, Long> getPromotionResult() { + return promotionResult; + } +}
Java
์ด ๋ถ€๋ถ„์„ Map์œผ๋กœ ์„ ์–ธํ•˜๋ฉด ๋‹คํ˜•์„ฑ์„ ์ข€ ๋” ํ™œ์šฉํ•˜์‹ค ์ˆ˜ ์žˆ์„๊ฑฐ์—์š”!
@@ -0,0 +1,26 @@ +package christmas.domain.promotion; + +import christmas.constant.PromotionItem; +import christmas.constant.PromotionType; +import java.util.List; + +public abstract class ChristmasPromotion { + + protected List<Integer> period; + protected PromotionItem targetItems; + protected long discountAmount; + protected PromotionType promotionType; + + public long getDiscountAmount() { + return discountAmount; + } + + public PromotionType getPromotionType(){ + return promotionType; + } + + public abstract long applyPromotion(int data, long orderAmount); + protected abstract boolean isApplicable(int date); + protected abstract boolean isEligibleForPromotion(long orderAmount); + +}
Java
์ด ๋ถ€๋ถ„์„ ์ถ”์ƒ ํด๋ž˜์Šค๋กœ ๊ตฌํ˜„ํ•˜์‹  ์ด์œ ๋ฅผ ์•Œ์ˆ˜์žˆ์„๊นŒ์š”?? ์ œ๊ฐ€ ์ถ”์ƒ ํด๋ž˜์Šค์— ๋Œ€ํ•ด ์ต์ˆ™ํ•˜์ง€ ์•Š์•„์„œ์š”!
@@ -0,0 +1,17 @@ +package christmas.dto; + +import christmas.constant.Badge; +import christmas.domain.promotion.ChristmasPromotion; +import java.util.HashMap; + +public record BenefitResult( + + long beforeDiscountAmount, + boolean giftMenu, + HashMap<ChristmasPromotion, Long> promotionResult, + long totalBenefitAmount, + long afterDiscountAmount, + Badge badge) +{ + +}
Java
๋ ˆ์ฝ”๋“œ๋ฅผ ํ™œ์šฉํ•˜์…จ๋„ค์š”. ์ด ๋ถ€๋ถ„์€ ๋ฉ”๋ชจํ•ด๋‘์—ˆ๋‹ค๊ฐ€ ์ €๋„ ์ ์šฉํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค! ์ข‹์€ ์ฝ”๋“œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,9 @@ +package christmas.util; + +public class Parser { + + public static int stringToInteger(String input) { + return Integer.parseInt(input); + } + +}
Java
์‚ฌ์†Œํ•œ ์ปจ๋ฒ„ํŒ…์ด๋ผ๋„ ๊ฐ์ฒด๋กœ ๋งŒ๋“ค์–ด์„œ ํ™œ์šฉํ•˜์‹ ๊ฒŒ ์ข‹๋„ค์š”!
@@ -0,0 +1,119 @@ +package christmas.validator; + +import christmas.constant.Menu; +import christmas.constant.MenuType; +import christmas.exception.ErrorCode; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class InputValidator { + + private static int START_DATE = 1; + private static int END_DATE = 31; + private static String COMMA = ","; + private static String HYPHEN = "-"; + private static int MENU_FORMAT_LENGTH = 2; + private static int MINIMUM_ORDER_COUNT = 1; + private static int MAXIMUN_ORDER_COUNT = 20; + + public static void validateVisitDate(String input){ + validateInteger(input); + validateNumberInRange(Integer.parseInt(input)); + } + + public static Map<Menu, Integer> validateMenuOrder(String input, Map<Menu, Integer> orderMenu){ + String[] orders = input.split(COMMA); + Set<Menu> uniqueMenu = new HashSet<>(); + + for (String order : orders) { + validate(order, orderMenu, uniqueMenu); + } + + validateOnlyBeverage(orderMenu); + validateMaxOrder(orderMenu); + + return orderMenu; + } + + private static void validate(String order, Map<Menu, Integer> orderMenu, Set<Menu> uniqueMenu){ + String[] parts = validateMenuOrderFormat(order.trim()); + + String menuName = parts[0]; + String quantity = parts[1]; + + Menu menu = getMenuByName(menuName); + + validateMenuFound(menu); + validateMinimumOrder(quantity); + validateDuplicateMenu(menu, uniqueMenu); + + orderMenu.put(menu, Integer.parseInt(quantity)); + } + + private static void validateInteger(String input){ + if(!input.chars().allMatch(Character::isDigit)){ + throw new IllegalArgumentException(ErrorCode.INVALID_DATE.getMessage()); + } + } + + private static void validateNumberInRange(int input){ + if(input > END_DATE || input < START_DATE) + throw new IllegalArgumentException(ErrorCode.INVALID_DATE.getMessage()); + } + + private static String[] validateMenuOrderFormat(String orders){ + String[] parts = orders.split(HYPHEN); + if (parts.length != MENU_FORMAT_LENGTH) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + + return parts; + } + + private static void validateMenuFound(Menu menu){ + if(menu == null) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateMinimumOrder(String quantity){ + if(!quantity.chars().allMatch(Character::isDigit)) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + + if(Integer.parseInt(quantity) < MINIMUM_ORDER_COUNT) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateMaxOrder(Map<Menu, Integer> orderMenu){ + int orderCount = 0; + for(Menu menu: orderMenu.keySet()) { + orderCount += orderMenu.get(menu); + } + + if(orderCount > MAXIMUN_ORDER_COUNT) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateDuplicateMenu(Menu menu, Set<Menu> uniqueMenu){ + if(!uniqueMenu.add(menu)) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + + private static void validateOnlyBeverage(Map<Menu, Integer> orderMenu){ + boolean allBeverages = orderMenu.keySet().stream() + .allMatch(menu -> menu.getMenuType() == MenuType.BEVERAGE); + + if (allBeverages) { + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + } + + private static Menu getMenuByName(String name) { + for (Menu menu : Menu.values()) { + if (menu.getName().equalsIgnoreCase(name)) { + return menu; + } + } + return null; + } +}
Java
์ค€๋‹˜์ด ๋ง์”€ํ•˜์‹ ๊ฒƒ ์ฒ˜๋Ÿผ Menu์˜ ์œ ๋ฌด๋ฅผ ์ฒ˜๋ฆฌํ•˜๋Š” ๋ฉ”์„œ๋“œ๋ฅผ ๊ตฌํ˜„ํ•˜์‹œ๊ฑฐ๋‚˜, Optional ๊ฐ์ฒด๋ฅผ ํ™œ์šฉํ•˜์‹œ๋Š”๊ฑธ ์ถ”์ฒœ๋“œ๋ฆฝ๋‹ˆ๋‹ค!
@@ -0,0 +1,44 @@ +package christmas.view; + +import christmas.constant.Badge; +import christmas.constant.OutputMessage; +import christmas.domain.promotion.ChristmasPromotion; +import java.util.HashMap; + +public class BenefitsView { + + public static String giftMenuOutputStatement(boolean giftMenu){ + if(giftMenu) + return OutputMessage.CHAMPAGNE.getMessage(); + + return OutputMessage.DOES_NOT_EXIST.getMessage(); + } + + public static String promotionResultOutputStatement(long totalBenefitAmount, HashMap<ChristmasPromotion, Long> promotionResult){ + if(totalBenefitAmount == 0) + return OutputMessage.DOES_NOT_EXIST.getMessage(); + + return findPromotionDetail(promotionResult).toString(); + } + + public static String badgeOutputStatement(Badge badge){ + if(badge == Badge.NONE) + return OutputMessage.DOES_NOT_EXIST.getMessage(); + return badge.getBadgeName(); + } + + private static StringBuilder findPromotionDetail(HashMap<ChristmasPromotion, Long> promotionResult){ + StringBuilder sb = new StringBuilder(); + for(ChristmasPromotion promotion: promotionResult.keySet()){ + long discount = promotionResult.get(promotion); + if(discount == 0) continue; + + sb.append(String.format(OutputMessage.BENEFIT_DETAILS.getMessage(), + promotion.getPromotionType().getMessage(), discount)); + } + + if(sb.isEmpty()) + return sb.append(OutputMessage.DOES_NOT_EXIST.getMessage()); + return sb; + } +}
Java
์ด ๋ถ€๋ถ„์„ ๋ณ„๋„ ๋ฉ”์„œ๋“œ๋กœ ๋นผ์„œ ์ธ๋ดํŠธ๋ฅผ ์ค„์—ฌ๋ณด๋Š”๊ฒŒ ์–ด๋–จ๊นŒ์š”?? ์ธํ…”๋ฆฌ์ œ์ด์—์„œ ํ•ด๋‹น ๋ถ€๋ถ„์„ ๋“œ๋ž˜๊ทธํ•œ ๋’ค cmd+option+m ์„ ์ž…๋ ฅํ•˜์‹œ๋ฉด ๋ฉ”์„œ๋“œ๋กœ ์ถ”์ถœํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,16 @@ +package christmas.view; + +import christmas.constant.Menu; +import christmas.constant.OutputMessage; +import java.util.Map; + +public class OrderMenuView { + + public static String orderMenuOutputStatement(Map<Menu, Integer> orderMenu){ + StringBuilder sb = new StringBuilder(); + for(Menu menu : orderMenu.keySet()){ + sb.append(String.format(OutputMessage.ORDER_MENU.getMessage(), menu.getName(), orderMenu.get(menu))); + } + return sb.toString(); + } +}
Java
์ €๋Š” view๋ฅผ ์œ„ํ•œ log๋ฐ์ดํ„ฐ๋ฅผ ํ•˜๋‚˜์˜ ๋„๋ฉ”์ธ์—์„œ ์ฒ˜๋ฆฌํ–ˆ๋Š”๋ฐ ์ด๋ ‡๊ฒŒ ๋ณ„๋„์˜ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•ด์„œ ๊ด€๋ฆฌํ•˜๋ฉด ์—ญํ• ๊ณผ ์ฑ…์ž„์ด ๋ช…ํ™•ํ•ด์ง€๊ฒ ๋„ค์š”! ํ•œ ์ˆ˜ ๋ฐฐ์›Œ๊ฐ‘๋‹ˆ๋‹ค!
@@ -0,0 +1,71 @@ +import { generateBasicToken } from '../utils/auth'; +import convertCartItem from '../utils/convertCartItem'; + +const API_URL = process.env.VITE_API_URL ?? 'undefined_URL'; +const USER_ID = process.env.VITE_API_USER_ID ?? 'undefined_USER_ID'; +const USER_PASSWORD = + process.env.VITE_API_USER_PASSWORD ?? 'undefined_USER_PASSWORD'; + +export const requestCartItemList = async () => { + const token = generateBasicToken(USER_ID, USER_PASSWORD); + const response = await fetch(`${API_URL}/cart-items`, { + method: 'GET', + headers: { Authorization: token, 'Content-Type': 'application/json' }, + }); + + if (!response.ok) { + throw new Error('Failed to fetch products:'); + } + const data = await response.json(); + + return convertCartItem(data.content); +}; + +export const requestSetCartItemQuantity = async ( + cartItemId: number, + quantity: number, +) => { + const token = generateBasicToken(USER_ID, USER_PASSWORD); + const response = await fetch(`${API_URL}/cart-items/${cartItemId}`, { + method: 'PATCH', + headers: { Authorization: token, 'Content-Type': 'application/json' }, + body: JSON.stringify({ + quantity, + }), + }); + + if (!response.ok) { + throw new Error('Failed to setCartItemQuantity'); + } +}; + +export const requestDeleteCartItem = async (cartItemId: number) => { + const token = generateBasicToken(USER_ID, USER_PASSWORD); + const response = await fetch(`${API_URL}/cart-items/${cartItemId}`, { + method: 'DELETE', + headers: { Authorization: token, 'Content-Type': 'application/json' }, + body: JSON.stringify({ + id: cartItemId, + }), + }); + + if (!response.ok) { + throw new Error('Failed to deleteCartItem'); + } +}; + +// TEST๋ฅผ ์œ„ํ•œ cartItem์ถ”๊ฐ€ API ์‹คํ–‰ +export const requestAddCartItemForTest = async (cartItemId: number) => { + const token = generateBasicToken(USER_ID, USER_PASSWORD); + const response = await fetch(`${API_URL}/cart-items`, { + method: 'POST', + headers: { Authorization: token, 'Content-Type': 'application/json' }, + body: JSON.stringify({ + productId: cartItemId, + }), + }); + + if (!response.ok) { + throw new Error('Failed to addCartItem'); + } +};
TypeScript
์š”๊ณ ๋Š” ๊ฐ api๋งˆ๋‹ค ์„ ์–ธํ•ด์„œ ์‚ฌ์šฉํ•ด์ฃผ์‹œ๋Š” ๊ฑธ๋กœ ํ™•์ธ๋๋Š”๋ฐ, ์ƒ์ˆ˜๋กœ ๋ถ„๋ฆฌํ•ด๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”! ๐Ÿซ
@@ -0,0 +1,87 @@ +import * as S from './CartItem.style'; +import Text from '../common/Text/Text'; +import Button from '../common/Button/Button'; +import Divider from '../common/Divider/Divider'; +import Checkbox from '../common/Checkbox/Checkbox'; +import ImageBox from '../common/ImageBox/ImageBox'; +import useCartItemList from '../../hooks/cartItem/useCartItemList'; +import ChangeQuantity from '../common/ChangeQuantity/ChangeQuantity'; +import { useCartItemQuantity } from '../../hooks/cartItem/useCartItemQuantity'; +import { useSelectedCartItemId } from '../../hooks/cartItem/useSelectedCartItemId'; +import useApiErrorState from '../../hooks/error/useApiErrorState'; + +export type CartItemProps = { + type?: 'cart' | 'confirm'; + cartItem: CartItem; +}; + +const CartItem = ({ type = 'cart', cartItem }: CartItemProps) => { + const { id, name, price, imageUrl } = cartItem; + const { apiError } = useApiErrorState(); + const { cartItemQuantity, increaseQuantity, decreaseQuantity } = + useCartItemQuantity(); + const { isSelectedId, selectCartItem, unselectCartItem } = + useSelectedCartItemId(); + const { deleteCartItem } = useCartItemList(); + + if ( + apiError?.name === 'FailedDeleteCartItemError' || + apiError?.name === 'FailedSetCartItemQuantityError' + ) { + throw apiError; + } + + return ( + <S.CartItem> + <Divider /> + {type === 'cart' ? ( + <S.ItemHeader> + <Checkbox + state={isSelectedId(id)} + handleClick={ + isSelectedId(id) + ? () => unselectCartItem(id) + : () => selectCartItem(id) + } + /> + <Button size="s" radius="s" onClick={() => deleteCartItem(id)}> + ์‚ญ์ œ + </Button> + </S.ItemHeader> + ) : null} + <S.ItemBody> + <ImageBox + width={112} + height={112} + radius="m" + border="lightGray" + src={imageUrl} + alt="์ƒํ’ˆ ์ด๋ฏธ์ง€" + /> + <S.ItemDetail> + <S.ItemNameAndCost> + <Text size="s" weight="m"> + {name} + </Text> + <Text size="l" weight="l"> + {`${price.toLocaleString('ko-KR')}์›`} + </Text> + </S.ItemNameAndCost> + {type === 'cart' ? ( + <ChangeQuantity + quantity={cartItemQuantity(id)} + increaseQuantity={() => increaseQuantity(id)} + decreaseQuantity={() => decreaseQuantity(id)} + /> + ) : ( + <Text size="s" weight="m"> + {`${cartItemQuantity(id)}๊ฐœ`} + </Text> + )} + </S.ItemDetail> + </S.ItemBody> + </S.CartItem> + ); +}; + +export default CartItem;
Unknown
type์„ 2๊ฐœ๋กœ ๋ถ„๋ฆฌํ•ด์„œ ๊ตฌํ˜„ํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”? ์ œ๊ฐ€ ๋А๋ผ๊ธฐ์—๋Š” ์ปดํฌ๋„ŒํŠธ๋ฅผ ๋ถ„๋ฆฌํ–ˆ์–ด๋„ ๊ดœ์ฐฎ์ง€ ์•Š๋‚˜ ์‹ถ์€ ์ƒ๊ฐ๋„ ๋“ค์–ด์„œ์š”!
@@ -1,10 +1,41 @@ -import "./App.css"; +import { Suspense } from 'react'; + +import styled from 'styled-components'; +import { ErrorBoundary } from 'react-error-boundary'; +import { BrowserRouter, Route, Routes } from 'react-router-dom'; + +import CartPage from './pages/CartPage'; +import ConfirmPurchasePage from './pages/ConfirmPurchasePage'; +import CompletePurchasePage from './pages/CompletePurchasePage'; +import ErrorFallback from './components/ErrorFallback/ErrorFallback'; +import LoadingFallback from './components/LoadingFallback/LoadingFallback'; + +const AppContainer = styled.div` + max-width: 768px; + width: 100%; +`; function App() { return ( - <> - <h1>react-shopping-cart</h1> - </> + <BrowserRouter> + <AppContainer> + <ErrorBoundary FallbackComponent={ErrorFallback}> + <Suspense fallback={<LoadingFallback />}> + <Routes> + <Route path="/" element={<CartPage />} /> + <Route + path="/confirm-purchase" + element={<ConfirmPurchasePage />} + /> + <Route + path="/complete-purchase" + element={<CompletePurchasePage />} + /> + </Routes> + </Suspense> + </ErrorBoundary> + </AppContainer> + </BrowserRouter> ); }
Unknown
์‚ฌ์†Œํ•˜์ง€๋งŒ RESTfulํ•˜๊ฒŒ path๋ฅผ ์ž‘์„ฑํ•ด์ฃผ์…จ๋„ค์š” ๐Ÿ‘๐Ÿ‘๐Ÿ‘๐Ÿ‘
@@ -1,10 +1,41 @@ -import "./App.css"; +import { Suspense } from 'react'; + +import styled from 'styled-components'; +import { ErrorBoundary } from 'react-error-boundary'; +import { BrowserRouter, Route, Routes } from 'react-router-dom'; + +import CartPage from './pages/CartPage'; +import ConfirmPurchasePage from './pages/ConfirmPurchasePage'; +import CompletePurchasePage from './pages/CompletePurchasePage'; +import ErrorFallback from './components/ErrorFallback/ErrorFallback'; +import LoadingFallback from './components/LoadingFallback/LoadingFallback'; + +const AppContainer = styled.div` + max-width: 768px; + width: 100%; +`; function App() { return ( - <> - <h1>react-shopping-cart</h1> - </> + <BrowserRouter> + <AppContainer> + <ErrorBoundary FallbackComponent={ErrorFallback}> + <Suspense fallback={<LoadingFallback />}> + <Routes> + <Route path="/" element={<CartPage />} /> + <Route + path="/confirm-purchase" + element={<ConfirmPurchasePage />} + /> + <Route + path="/complete-purchase" + element={<CompletePurchasePage />} + /> + </Routes> + </Suspense> + </ErrorBoundary> + </AppContainer> + </BrowserRouter> ); }
Unknown
์‚ฌ์†Œํ•˜์ง€๋งŒ, ๋‹ค์Œ ๋ฏธ์…˜๋ถ€ํ„ฐ๋Š” [createBrowserRouter](https://reactrouter.com/en/main/routers/create-browser-router)๋ฅผ ์‚ฌ์šฉํ•ด๋ด๋„ ๊ดœ์ฐฎ์„ ๊ฒƒ ๊ฐ™์•„์„œ ๊ณต์œ ๋“œ๋ ค์š”! ๊ด€๋ จํ•ด์„œ ์ˆ˜์•ผ์™€๋„ ๋ฆฌ๋ทฐ๋ฅผ ํ•œ ์ ์ด ์žˆ์–ด์„œ ์ฒจ๋ถ€ํ•ฉ๋‹ˆ๋‹ค! https://github.com/cys4585/react-shopping-cart/pull/1/files/0636ab3b3126ca9b8873cb7fec59c13b05c81985#r1603187152
@@ -0,0 +1,71 @@ +import { generateBasicToken } from '../utils/auth'; +import convertCartItem from '../utils/convertCartItem'; + +const API_URL = process.env.VITE_API_URL ?? 'undefined_URL'; +const USER_ID = process.env.VITE_API_USER_ID ?? 'undefined_USER_ID'; +const USER_PASSWORD = + process.env.VITE_API_USER_PASSWORD ?? 'undefined_USER_PASSWORD'; + +export const requestCartItemList = async () => { + const token = generateBasicToken(USER_ID, USER_PASSWORD); + const response = await fetch(`${API_URL}/cart-items`, { + method: 'GET', + headers: { Authorization: token, 'Content-Type': 'application/json' }, + }); + + if (!response.ok) { + throw new Error('Failed to fetch products:'); + } + const data = await response.json(); + + return convertCartItem(data.content); +}; + +export const requestSetCartItemQuantity = async ( + cartItemId: number, + quantity: number, +) => { + const token = generateBasicToken(USER_ID, USER_PASSWORD); + const response = await fetch(`${API_URL}/cart-items/${cartItemId}`, { + method: 'PATCH', + headers: { Authorization: token, 'Content-Type': 'application/json' }, + body: JSON.stringify({ + quantity, + }), + }); + + if (!response.ok) { + throw new Error('Failed to setCartItemQuantity'); + } +}; + +export const requestDeleteCartItem = async (cartItemId: number) => { + const token = generateBasicToken(USER_ID, USER_PASSWORD); + const response = await fetch(`${API_URL}/cart-items/${cartItemId}`, { + method: 'DELETE', + headers: { Authorization: token, 'Content-Type': 'application/json' }, + body: JSON.stringify({ + id: cartItemId, + }), + }); + + if (!response.ok) { + throw new Error('Failed to deleteCartItem'); + } +}; + +// TEST๋ฅผ ์œ„ํ•œ cartItem์ถ”๊ฐ€ API ์‹คํ–‰ +export const requestAddCartItemForTest = async (cartItemId: number) => { + const token = generateBasicToken(USER_ID, USER_PASSWORD); + const response = await fetch(`${API_URL}/cart-items`, { + method: 'POST', + headers: { Authorization: token, 'Content-Type': 'application/json' }, + body: JSON.stringify({ + productId: cartItemId, + }), + }); + + if (!response.ok) { + throw new Error('Failed to addCartItem'); + } +};
TypeScript
์ œ๊ฐ€ ์ง€๋‚œ ๋ฒˆ์— ๋‚จ๊ฒผ๋˜ ๋ฆฌ๋ทฐ๋ฅผ ๋ฐ˜์˜ํ•ด์ฃผ์‹ ๊ฒƒ ๊ฐ™์•„์„œ ๊ธฐ๋ถ„์ด ์กฐ์œผ๋„ค์š”..ใ…Žใ…Ž
@@ -0,0 +1,121 @@ +import { render, screen, fireEvent } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import CartItem, { CartItemProps } from './CartItem'; +import { RecoilRoot } from 'recoil'; +import { useCartItemQuantity } from '../../recoil/cartItem/useCartItemQuantity'; +import { useCartItemSelectedIdList } from '../../recoil/cartItem/useCartItemSelectedIdList'; +import useCartItemList from '../../recoil/cartItemList/useCartItemList'; + +// Mock Recoil hooks +jest.mock('../../recoil/cartItem/useCartItemQuantity'); +jest.mock('../../recoil/cartItem/useCartItemSelectedIdList'); +jest.mock('../../recoil/cartItemList/useCartItemList'); + +const mockedUseCartItemQuantity = useCartItemQuantity as jest.Mock; +const mockedUseCartItemSelectedIdList = useCartItemSelectedIdList as jest.Mock; +const mockedUseCartItemList = useCartItemList as jest.Mock; + +// Sample product data +const product = { + productId: 3, + name: '์•„๋””๋‹ค์Šค', + price: 2000, + imageUrl: 'https://sitem.ssgcdn.com/74/25/04/item/1000373042574_i1_750.jpg', + category: 'fashion', +}; + +const mockCartItemProps: CartItemProps = { + product, + quantity: 5, + cartItemId: 1, +}; + +describe('CartItem ์ปดํฌ๋„ŒํŠธ', () => { + beforeEach(() => { + mockedUseCartItemQuantity.mockReturnValue({ + quantity: 5, + updateQuantity: jest.fn(), + increaseQuantity: jest.fn(), + decreaseQuantity: jest.fn(), + }); + + mockedUseCartItemSelectedIdList.mockReturnValue({ + getIsSelected: jest.fn().mockReturnValue(false), + addSelectedId: jest.fn(), + removeSelectedId: jest.fn(), + }); + + mockedUseCartItemList.mockReturnValue({ + deleteCartItem: jest.fn(), + }); + }); + + afterEach(() => { + jest.clearAllMocks(); + }); + + test('์ปดํฌ๋„ŒํŠธ๊ฐ€ ์˜ฌ๋ฐ”๋ฅด๊ฒŒ ๋ Œ๋”๋ง๋œ๋‹ค', () => { + render( + <RecoilRoot> + <CartItem {...mockCartItemProps} /> + </RecoilRoot>, + ); + + expect(screen.getByText('์•„๋””๋‹ค์Šค')).toBeInTheDocument(); + expect(screen.getByText('2,000์›')).toBeInTheDocument(); + expect(screen.getByText('5')).toBeInTheDocument(); + }); + + test('์‚ญ์ œ ๋ฒ„ํŠผ์„ ํด๋ฆญํ–ˆ์„ ๋•Œ deleteCartItem ํ•จ์ˆ˜๊ฐ€ ํ˜ธ์ถœ๋œ๋‹ค', () => { + const { deleteCartItem } = mockedUseCartItemList(); + + render( + <RecoilRoot> + <CartItem {...mockCartItemProps} /> + </RecoilRoot>, + ); + + fireEvent.click(screen.getByText('์‚ญ์ œ')); + expect(deleteCartItem).toHaveBeenCalledWith(mockCartItemProps.cartItemId); + }); + + test('์ฒดํฌ๋ฐ•์Šค๋ฅผ ํด๋ฆญํ–ˆ์„ ๋•Œ ์„ ํƒ ์ƒํƒœ๊ฐ€ ๋ณ€๊ฒฝ๋œ๋‹ค', () => { + const { addSelectedId, removeSelectedId, getIsSelected } = mockedUseCartItemSelectedIdList(); + + render( + <RecoilRoot> + <CartItem {...mockCartItemProps} /> + </RecoilRoot>, + ); + + // Initially not selected + getIsSelected.mockReturnValue(false); + const checkbox = screen.getByAltText('Checkbox'); + fireEvent.click(checkbox); + expect(addSelectedId).toHaveBeenCalledWith(mockCartItemProps.cartItemId); + + // Now selected + getIsSelected.mockReturnValue(true); + fireEvent.click(checkbox); + expect(removeSelectedId).toHaveBeenCalledWith(mockCartItemProps.cartItemId); + }); + + test('์ˆ˜๋Ÿ‰ ์ฆ๊ฐ€ ๋ฐ ๊ฐ์†Œ ๋ฒ„ํŠผ์ด ์ œ๋Œ€๋กœ ์ž‘๋™ํ•œ๋‹ค', () => { + const { increaseQuantity, decreaseQuantity } = mockedUseCartItemQuantity(); + + render( + <RecoilRoot> + <CartItem {...mockCartItemProps} /> + </RecoilRoot>, + ); + + const increaseButton = screen.getByLabelText('plus'); + const decreaseButton = screen.getByLabelText('minus'); + + fireEvent.click(increaseButton); + expect(increaseQuantity).toHaveBeenCalledTimes(1); + + fireEvent.click(decreaseButton); + expect(decreaseQuantity).toHaveBeenCalledTimes(1); + }); +});
Unknown
uiํ…Œ์ŠคํŠธ๋„ ์ž‘์„ฑ์„ ํ•ด์ฃผ์…จ๋„ค์š”...!! ๊ตฟ๊ตฟ~~!
@@ -0,0 +1,87 @@ +import * as S from './CartItem.style'; +import Text from '../common/Text/Text'; +import Button from '../common/Button/Button'; +import Divider from '../common/Divider/Divider'; +import Checkbox from '../common/Checkbox/Checkbox'; +import ImageBox from '../common/ImageBox/ImageBox'; +import useCartItemList from '../../hooks/cartItem/useCartItemList'; +import ChangeQuantity from '../common/ChangeQuantity/ChangeQuantity'; +import { useCartItemQuantity } from '../../hooks/cartItem/useCartItemQuantity'; +import { useSelectedCartItemId } from '../../hooks/cartItem/useSelectedCartItemId'; +import useApiErrorState from '../../hooks/error/useApiErrorState'; + +export type CartItemProps = { + type?: 'cart' | 'confirm'; + cartItem: CartItem; +}; + +const CartItem = ({ type = 'cart', cartItem }: CartItemProps) => { + const { id, name, price, imageUrl } = cartItem; + const { apiError } = useApiErrorState(); + const { cartItemQuantity, increaseQuantity, decreaseQuantity } = + useCartItemQuantity(); + const { isSelectedId, selectCartItem, unselectCartItem } = + useSelectedCartItemId(); + const { deleteCartItem } = useCartItemList(); + + if ( + apiError?.name === 'FailedDeleteCartItemError' || + apiError?.name === 'FailedSetCartItemQuantityError' + ) { + throw apiError; + } + + return ( + <S.CartItem> + <Divider /> + {type === 'cart' ? ( + <S.ItemHeader> + <Checkbox + state={isSelectedId(id)} + handleClick={ + isSelectedId(id) + ? () => unselectCartItem(id) + : () => selectCartItem(id) + } + /> + <Button size="s" radius="s" onClick={() => deleteCartItem(id)}> + ์‚ญ์ œ + </Button> + </S.ItemHeader> + ) : null} + <S.ItemBody> + <ImageBox + width={112} + height={112} + radius="m" + border="lightGray" + src={imageUrl} + alt="์ƒํ’ˆ ์ด๋ฏธ์ง€" + /> + <S.ItemDetail> + <S.ItemNameAndCost> + <Text size="s" weight="m"> + {name} + </Text> + <Text size="l" weight="l"> + {`${price.toLocaleString('ko-KR')}์›`} + </Text> + </S.ItemNameAndCost> + {type === 'cart' ? ( + <ChangeQuantity + quantity={cartItemQuantity(id)} + increaseQuantity={() => increaseQuantity(id)} + decreaseQuantity={() => decreaseQuantity(id)} + /> + ) : ( + <Text size="s" weight="m"> + {`${cartItemQuantity(id)}๊ฐœ`} + </Text> + )} + </S.ItemDetail> + </S.ItemBody> + </S.CartItem> + ); +}; + +export default CartItem;
Unknown
์ €๋„ ๋น„์Šทํ•˜๊ฒŒ ์ƒ๊ฐํ•˜๋Š”๋ฐ์š”. ์ฒดํฌ, ์‚ญ์ œ๋ฒ„ํŠผ, ์ˆซ์ž ๋ฒ„ํŠผ ๋“ฑ ์ง€๊ธˆ์€ ๊ฒฝ์šฐ์˜ ์ˆ˜๊ฐ€ 2**3๊ฐœ ๋ฐ–์— ์—†์–ด์„œ ํƒ€์ž…์œผ๋กœ ์ผ์ผํžˆ ์ง€์ •ํ•ด์ค„ ์ˆ˜ ์žˆ์ง€๋งŒ, ์š”๊ตฌ์‚ฌํ•ญ์ด ๋Š˜์–ด๋‚˜๋ฉด ํƒ€์ž…์œผ๋กœ๋Š” ๋ฒ„๊ฑฐ์šธ์ˆ˜๋„ ์žˆ๋‹ค๋Š” ์ƒ๊ฐ์ด ๋“ค์–ด์š”..!
@@ -0,0 +1,172 @@ +import type { Meta, StoryObj } from '@storybook/react'; +<<<<<<< HEAD +import CartItemList from './CartItemList'; +import { RecoilRoot } from 'recoil'; +import { cartItemListState } from '../../recoil/cartItem/atom'; + +const MOCK_DATA = [ + { + id: 586, + quantity: 4, + name: '๋‚˜์ดํ‚ค', + price: 1000, + imageUrl: + 'https://static.nike.com/a/images/c_limit,w_592,f_auto/t_product_v1/a28864e3-de02-48bb-b861-9c592bc9a68b/%EB%B6%81-1-ep-%EB%86%8D%EA%B5%AC%ED%99%94-UOp6QQvg.png', + }, + { + id: 587, + quantity: 3, + + name: '์•„๋””๋‹ค์Šค', + price: 2000, + imageUrl: 'https://sitem.ssgcdn.com/74/25/04/item/1000373042574_i1_750.jpg', + }, + { + id: 588, + quantity: 1, + name: 'ํ“จ๋งˆ', + price: 10000, + imageUrl: 'https://sitem.ssgcdn.com/47/78/22/item/1000031227847_i1_750.jpg', + }, + { + id: 589, + quantity: 4, + + name: '๋ฆฌ๋ณต', + price: 20000, + imageUrl: + 'https://image.msscdn.net/images/goods_img/20221031/2909092/2909092_6_500.jpg', + }, + { + id: 590, + quantity: 5, + + name: '์ปจ๋ฒ„์Šค', + price: 20000, + imageUrl: 'https://sitem.ssgcdn.com/65/73/69/item/1000163697365_i1_750.jpg', + }, +]; +======= +import CartItemList, { CartItemListProps } from './CartItemList'; +import { RecoilRoot } from 'recoil'; +>>>>>>> todari + +const meta = { + title: 'Components/CartItemList', + component: CartItemList, + tags: ['autodocs'], + argTypes: { +<<<<<<< HEAD + type: { + description: '', + control: { type: 'radio' }, + options: ['cart', 'confirm'], + }, + cartItemList: { + description: '', + control: { type: 'object' }, + }, + }, + args: { + type: 'cart', + cartItemList: MOCK_DATA, + }, +======= + itemList: { + description: '', + control: { type: 'object' }, + } + }, + args: { + itemList: [ + { + "cartItemId": 586, + "quantity": 4, + "product": { + "productId": 2, + "name": "๋‚˜์ดํ‚ค", + "price": 1000, + "imageUrl": "https://static.nike.com/a/images/c_limit,w_592,f_auto/t_product_v1/a28864e3-de02-48bb-b861-9c592bc9a68b/%EB%B6%81-1-ep-%EB%86%8D%EA%B5%AC%ED%99%94-UOp6QQvg.png", + "category": "fashion" + } + }, + { + "cartItemId": 587, + "quantity": 3, + "product": { + "productId": 3, + "name": "์•„๋””๋‹ค์Šค", + "price": 2000, + "imageUrl": "https://sitem.ssgcdn.com/74/25/04/item/1000373042574_i1_750.jpg", + "category": "fashion" + } + }, + { + "cartItemId": 588, + "quantity": 1, + "product": { + "productId": 10, + "name": "ํ“จ๋งˆ", + "price": 10000, + "imageUrl": "https://sitem.ssgcdn.com/47/78/22/item/1000031227847_i1_750.jpg", + "category": "fashion" + } + }, + { + "cartItemId": 589, + "quantity": 4, + "product": { + "productId": 11, + "name": "๋ฆฌ๋ณต", + "price": 20000, + "imageUrl": "https://image.msscdn.net/images/goods_img/20221031/2909092/2909092_6_500.jpg", + "category": "fashion" + } + }, + { + "cartItemId": 590, + "quantity": 5, + "product": { + "productId": 12, + "name": "์ปจ๋ฒ„์Šค", + "price": 20000, + "imageUrl": "https://sitem.ssgcdn.com/65/73/69/item/1000163697365_i1_750.jpg", + "category": "fashion" + } + } + ], + } +>>>>>>> todari +} satisfies Meta<typeof CartItemList>; + +export default meta; + +type Story = StoryObj<typeof meta>; + +<<<<<<< HEAD +export const Playground: Story = { + render: ({ type, cartItemList }) => { + return ( + <RecoilRoot + initializeState={({ set }) => set(cartItemListState, MOCK_DATA)} + > + <div style={{ width: '430px' }}> + <CartItemList type={type} cartItemList={cartItemList} /> + </div> + </RecoilRoot> + ); + }, +======= +// TODO : decorator ์‚ฌ์šฉํ•˜์—ฌ ๋™์ž‘ํ•  ์ˆ˜ ์žˆ๋„๋ก current: recoil๋กœ ์ธํ•ด ์ž‘๋™ x +export const Playground: Story = { + render: ({ ...args }: CartItemListProps) => { + return ( + <RecoilRoot> + <div style={{ width: '430px' }}> + <CartItemList {...args} /> + </div> + </RecoilRoot> + ) + } +>>>>>>> todari +};
Unknown
๋ฆฌ๋ฒ ์ด์Šค์˜ ํ”์ ์ดใ… 
@@ -0,0 +1,44 @@ +package christmas.controller; + +import christmas.domain.event.EventCalculator; +import christmas.domain.date.ReservationDate; +import christmas.domain.order.OrderMenuParser; +import christmas.view.InputView; +import christmas.view.OutputView; + +public class ChristmasController { + public void run(){ + OutputView.printStart(); + ReservationDate reservationDate = reservationDate(); + OrderMenuParser orderMenu = orderMenu(); + OutputView.printDate(reservationDate); + OutputView.printOrderMenu(orderMenu); + OutputView.printTotalPrice(orderMenu); + EventCalculator eventCalculator = new EventCalculator(reservationDate, orderMenu); + OutputView.printGiftMenu(orderMenu); + OutputView.printEvent(eventCalculator); + OutputView.printTotalDiscount(eventCalculator); + OutputView.printExpectedDiscount(eventCalculator); + OutputView.printEventBadge(eventCalculator); + } + + private ReservationDate reservationDate() { + while (true) { + try { + return new ReservationDate(InputView.readDate()); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private OrderMenuParser orderMenu(){ + while (true) { + try { + return new OrderMenuParser(InputView.readMenu()); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } +}
Java
ํ•œ ๋ฉ”์„œ๋“œ์—์„œ ๋„ˆ๋ฌด ๋ณต์žกํ•ด ๋ณด์ด๋„ค์š” ๋ฉ”์„œ๋“œ๋ฅผ ๋ถ„๋ฆฌํ•˜๋ฉด ๋” ์ข‹์„๊ฑฐ ๊ฐ™์•„์š”!
@@ -0,0 +1,22 @@ +package christmas.domain.event; + +import christmas.constant.ChristmasConfig; + +public class ChristmasEvent { + private final int reservationDate; + + public ChristmasEvent(int reservationDate) { + this.reservationDate = reservationDate; + } + + public int calculateDiscount() { + if (isChristmasPeriod()) { + return ChristmasConfig.DISCOUNT_MONEY + ChristmasConfig.INCREASE_MONEY * (reservationDate - ChristmasConfig.START_DAY); + } + return ChristmasConfig.ZERO; + } + + private boolean isChristmasPeriod() { + return reservationDate >= ChristmasConfig.START_DAY && reservationDate <= ChristmasConfig.END_DAY; + } +} \ No newline at end of file
Java
๊ฐ ์ด๋ฒคํŠธ ํด๋ž˜์Šค์—์„œ ๋‚ ์งœ๋ฅผ ๊ฒ€์ฆํ•˜๋Š” ๊ฒƒ๋„ ์ข‹์€๋ฐ ๊ฐ๊ฐ์˜ ์ด๋ฒคํŠธ ๊ธฐ๊ฐ„์— ํฌํ•จ๋˜๋Š”์ง€ ์ฒ˜๋ฆฌํ•˜๋Š” ๋ถ€๋ถ„์„ ReservationDate ํด๋ž˜์Šค์—์„œ ์ฒ˜๋ฆฌํ•ด๋„ ์ข‹์„๊ฑฐ ๊ฐ™์•„์š”!
@@ -0,0 +1,77 @@ +import React, { useState } from "react"; +import styled from "styled-components"; +import { Star as StarIcon } from "lucide-react"; + +interface StarRatingProps { + totalStars?: number; + initialRating?: number; + onRatingChange?: (rating: number) => void; +} + +const BackgroundContainer = styled.div` + background-color: #f7f7f7; + width: 807.73px; + height: 251.63px; + display: flex; + align-items: center; + justify-content: center; +`; + +const StarContainer = styled.div` + display: flex; + gap: 4px; +`; + +const StyledStar = styled.div<{ filled: boolean }>` + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + svg { + width: 94.96px; + height: 99.25px; + color: ${(props) => (props.filled ? "#facc15" : "#d1d5db")}; + } +`; + +const StarRating: React.FC<StarRatingProps> = ({ + totalStars = 5, + initialRating = 0, + onRatingChange, +}) => { + const [rating, setRating] = useState(initialRating); + + const handleRating = (index: number) => { + let newRating = rating; + if (index + 1 === rating) { + newRating = index; + } else if (index < rating) { + newRating = index; + } else { + newRating = index + 1; + } + + setRating(newRating); + if (onRatingChange) { + onRatingChange(newRating); + } + }; + + return ( + <BackgroundContainer> + <StarContainer> + {Array.from({ length: totalStars }, (_, index) => ( + <StyledStar + key={index} + filled={index < rating} + onClick={() => handleRating(index)} + > + <StarIcon fill={index < rating ? "#facc15" : "none"} stroke="#facc15" /> + </StyledStar> + ))} + </StarContainer> + </BackgroundContainer> + ); +}; + +export default StarRating;
Unknown
filled ์•ˆ์ชฝ์— String์œผ๋กœ ๊ฐ์‹ธ์ฃผ์„ธ์š”
@@ -0,0 +1,77 @@ +import React, { useState } from "react"; +import styled from "styled-components"; +import { Star as StarIcon } from "lucide-react"; + +interface StarRatingProps { + totalStars?: number; + initialRating?: number; + onRatingChange?: (rating: number) => void; +} + +const BackgroundContainer = styled.div` + background-color: #f7f7f7; + width: 807.73px; + height: 251.63px; + display: flex; + align-items: center; + justify-content: center; +`; + +const StarContainer = styled.div` + display: flex; + gap: 4px; +`; + +const StyledStar = styled.div<{ filled: boolean }>` + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + svg { + width: 94.96px; + height: 99.25px; + color: ${(props) => (props.filled ? "#facc15" : "#d1d5db")}; + } +`; + +const StarRating: React.FC<StarRatingProps> = ({ + totalStars = 5, + initialRating = 0, + onRatingChange, +}) => { + const [rating, setRating] = useState(initialRating); + + const handleRating = (index: number) => { + let newRating = rating; + if (index + 1 === rating) { + newRating = index; + } else if (index < rating) { + newRating = index; + } else { + newRating = index + 1; + } + + setRating(newRating); + if (onRatingChange) { + onRatingChange(newRating); + } + }; + + return ( + <BackgroundContainer> + <StarContainer> + {Array.from({ length: totalStars }, (_, index) => ( + <StyledStar + key={index} + filled={index < rating} + onClick={() => handleRating(index)} + > + <StarIcon fill={index < rating ? "#facc15" : "none"} stroke="#facc15" /> + </StyledStar> + ))} + </StarContainer> + </BackgroundContainer> + ); +}; + +export default StarRating;
Unknown
์ œ๊ฐ€ ํ›„๊ธฐ ํŽ˜์ด์ง€ ๋งŒ๋“ค๋ฉด์„œ ์ด ๋ถ€๋ถ„ ์ˆ˜์ •ํ•ด์„œ ํ•œ๊บผ๋ฒˆ์— PR ์˜ฌ๋ฆฌ๊ฒ ์Šต๋‹ˆ๋‹ค
@@ -3,28 +3,50 @@ import './Login.scss'; import Login_Button from './Login_Button/Login_Button'; class Login extends Component { + constructor(props) { + super(props); + this.state = { + id: 'a', + pw: 0, + }; + } + + handleInput = e => { + const { value, name } = e.target; + this.setState({ + [name]: value, + }); + }; + render() { + const { handleInput } = this; + const { id, pw } = this.state; + return ( <div className="log_in_box"> <div className="title">westagram</div> <div className="log_in"> <div className="id"> <input + onChange={handleInput} className="id_input" + name="id" type="text" placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" /> </div> <div className="password"> <input + onChange={handleInput} className="password_input" + name="pw" type="password" placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" /> </div> </div> - <Login_Button /> + <Login_Button idvalue={this.state.id} pwvalue={this.state.pw} /> <p> ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”? </p> </div>
JavaScript
this.state ... ์ด๊ฑฐ ๋„ˆ๋ฌด ๊ธฐ๋‹ˆ๊นŒ ์ด๊ฒƒ๋„ ๋น„๊ตฌ์กฐํ™” ํ• ๋‹นํ•˜์‹œ๋Š” ๊ฒŒ ๊ฐ€๋…์„ฑ์ด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -1,14 +1,51 @@ import React, { Component } from 'react'; +import Comment from './Comment/Comment'; import './Feeds.scss'; class Feeds extends Component { + constructor(props) { + super(props); + this.state = { + comment: '', + comments: [], + idnumber: 1, + }; + } + + componentDidMount = () => { + this.setState({ comments: this.props.comments }); + }; + + handleComment = e => { + this.setState({ + comment: e.target.value, + }); + }; + + addComment = e => { + e.preventDefault(); + + this.setState({ + comments: this.state.comments.concat({ + id: this.state.idnumber + 3, + text: this.state.comment, + }), + comment: '', + idnumber: this.state.idnumber + 1, + }); + }; + render() { + const { comments, comment } = this.state; + const { handleComment, addComment } = this; + // console.log(this.state); + return ( <div className="feeds"> <article> <div className="feeds_profile"> <div className="feeds_profile_image"> - <img alt="ํ”„๋กœํ•„" src="/images/jaesangChoi/profile1.jpeg" /> + <img alt="profile" src={this.props.profilesrc} /> </div> <p className="feeds_profile_name"> <span className="feeds_profile_main_name"> @@ -23,28 +60,28 @@ class Feeds extends Component { <img alt="sunset" className="main_feed_img" - src="https://images.unsplash.com/photo-1623659993428-0c5504a16ca5?ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw0Mnx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" + src={this.props.mainfeedsrc} /> </div> <div className="comment_icon_box"> <div className="left_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> <img - alt="์ฝ”๋ฉ˜ํŠธ์•„์ด์ฝ˜" + alt="comment_icon" src="/images/jaesangChoi/commentary.png" /> - <img alt="๊ณต์œ ์•„์ด์ฝ˜" src="/images/jaesangChoi/send.png" /> + <img alt="share_icon" src="/images/jaesangChoi/send.png" /> </div> <div className="right_icon"> - <img alt="๋ถ๋งˆํฌ์•„์ด์ฝ˜" src="/images/jaesangChoi/bookmark.png" /> + <img alt="bookmark_icon" src="/images/jaesangChoi/bookmark.png" /> </div> </div> <div className="comment_profile"> <div className="comment_profile_icon"> <img - alt="ํ”„๋กœํ•„" + alt="profile" src="/images/jaesangChoi/comment_profile.jpeg" /> </div> @@ -67,25 +104,33 @@ class Feeds extends Component { ์ข‹์•˜์ž–์•„~~~~~ </div> <div className="second_comment_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> </div> </div> <div className="third_comment">42๋ถ„ ์ „</div> + <ul className="comment_list"> + {comments.map(comment => { + return <Comment key={comment.id} text={comment.text} />; + })} + </ul> + <div className="push_comment"> <div className="push_comment_icon"> - <img alt="์Šค๋งˆ์ผ์•„์ด์ฝ˜" src="/images/jaesangChoi/smile.png" /> + <img alt="smile_icon" src="/images/jaesangChoi/smile.png" /> </div> - <div className="push_comment_text"> + <form className="push_comment_text" onSubmit={addComment}> <input + onChange={handleComment} + value={comment} className="input_comment" type="text" placeholder="๋Œ“๊ธ€๋‹ฌ๊ธฐ..." /> - </div> + </form> <div className="push_comment_button"> - <button>๊ฒŒ์‹œ</button> + <button onClick={addComment}>๊ฒŒ์‹œ</button> </div> </div> </article>
JavaScript
์—ฌ๊ธฐ form ํƒœ๊ทธ๋กœ ๊ฐ์‹ธ์‹œ๊ณ  onSubmit ์ด๋ฒคํŠธ์ฃผ์‹œ๋ฉด ์—”ํ„ฐํ‚ค ๋ˆ„๋ฅผ ๋•Œ ์‹คํ–‰๋˜๋Š” ๋ฉ”์†Œ๋“œ ๋”ฐ๋กœ ์•ˆ ๋งŒ๋“œ์…”๋„ pressButton ๋ฉ”์†Œ๋“œ ํ•˜๋‚˜๋งŒ์œผ๋กœ ๋Œ“๊ธ€ ์ถ”๊ฐ€์‹œํ‚ฌ ์ˆ˜ ์žˆ์–ด์š”!
@@ -3,28 +3,50 @@ import './Login.scss'; import Login_Button from './Login_Button/Login_Button'; class Login extends Component { + constructor(props) { + super(props); + this.state = { + id: 'a', + pw: 0, + }; + } + + handleInput = e => { + const { value, name } = e.target; + this.setState({ + [name]: value, + }); + }; + render() { + const { handleInput } = this; + const { id, pw } = this.state; + return ( <div className="log_in_box"> <div className="title">westagram</div> <div className="log_in"> <div className="id"> <input + onChange={handleInput} className="id_input" + name="id" type="text" placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" /> </div> <div className="password"> <input + onChange={handleInput} className="password_input" + name="pw" type="password" placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" /> </div> </div> - <Login_Button /> + <Login_Button idvalue={this.state.id} pwvalue={this.state.pw} /> <p> ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”? </p> </div>
JavaScript
๋ง์”€ํ•˜์‹ ๋Œ€๋กœ ๋ฐ”๊ฟจ์Šต๋‹ˆ๋‹ค!
@@ -1,14 +1,51 @@ import React, { Component } from 'react'; +import Comment from './Comment/Comment'; import './Feeds.scss'; class Feeds extends Component { + constructor(props) { + super(props); + this.state = { + comment: '', + comments: [], + idnumber: 1, + }; + } + + componentDidMount = () => { + this.setState({ comments: this.props.comments }); + }; + + handleComment = e => { + this.setState({ + comment: e.target.value, + }); + }; + + addComment = e => { + e.preventDefault(); + + this.setState({ + comments: this.state.comments.concat({ + id: this.state.idnumber + 3, + text: this.state.comment, + }), + comment: '', + idnumber: this.state.idnumber + 1, + }); + }; + render() { + const { comments, comment } = this.state; + const { handleComment, addComment } = this; + // console.log(this.state); + return ( <div className="feeds"> <article> <div className="feeds_profile"> <div className="feeds_profile_image"> - <img alt="ํ”„๋กœํ•„" src="/images/jaesangChoi/profile1.jpeg" /> + <img alt="profile" src={this.props.profilesrc} /> </div> <p className="feeds_profile_name"> <span className="feeds_profile_main_name"> @@ -23,28 +60,28 @@ class Feeds extends Component { <img alt="sunset" className="main_feed_img" - src="https://images.unsplash.com/photo-1623659993428-0c5504a16ca5?ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw0Mnx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" + src={this.props.mainfeedsrc} /> </div> <div className="comment_icon_box"> <div className="left_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> <img - alt="์ฝ”๋ฉ˜ํŠธ์•„์ด์ฝ˜" + alt="comment_icon" src="/images/jaesangChoi/commentary.png" /> - <img alt="๊ณต์œ ์•„์ด์ฝ˜" src="/images/jaesangChoi/send.png" /> + <img alt="share_icon" src="/images/jaesangChoi/send.png" /> </div> <div className="right_icon"> - <img alt="๋ถ๋งˆํฌ์•„์ด์ฝ˜" src="/images/jaesangChoi/bookmark.png" /> + <img alt="bookmark_icon" src="/images/jaesangChoi/bookmark.png" /> </div> </div> <div className="comment_profile"> <div className="comment_profile_icon"> <img - alt="ํ”„๋กœํ•„" + alt="profile" src="/images/jaesangChoi/comment_profile.jpeg" /> </div> @@ -67,25 +104,33 @@ class Feeds extends Component { ์ข‹์•˜์ž–์•„~~~~~ </div> <div className="second_comment_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> </div> </div> <div className="third_comment">42๋ถ„ ์ „</div> + <ul className="comment_list"> + {comments.map(comment => { + return <Comment key={comment.id} text={comment.text} />; + })} + </ul> + <div className="push_comment"> <div className="push_comment_icon"> - <img alt="์Šค๋งˆ์ผ์•„์ด์ฝ˜" src="/images/jaesangChoi/smile.png" /> + <img alt="smile_icon" src="/images/jaesangChoi/smile.png" /> </div> - <div className="push_comment_text"> + <form className="push_comment_text" onSubmit={addComment}> <input + onChange={handleComment} + value={comment} className="input_comment" type="text" placeholder="๋Œ“๊ธ€๋‹ฌ๊ธฐ..." /> - </div> + </form> <div className="push_comment_button"> - <button>๊ฒŒ์‹œ</button> + <button onClick={addComment}>๊ฒŒ์‹œ</button> </div> </div> </article>
JavaScript
form์— ์ด๋Ÿฐ ๊ธฐ๋Šฅ์ด ์žˆ๋Š” ์ค„ ์ฒ˜์Œ์•Œ์•˜์Šต๋‹ˆ๋‹ค! ๋•๋ถ„์— ์ƒˆ๋กœ์šด ์ง€์‹์„ ์–ป์—ˆ์Šต๋‹ˆ๋‹ค. ์ •๋ง ๊ฐ์‚ฌํ•ด์š”!
@@ -3,28 +3,50 @@ import './Login.scss'; import Login_Button from './Login_Button/Login_Button'; class Login extends Component { + constructor(props) { + super(props); + this.state = { + id: 'a', + pw: 0, + }; + } + + handleInput = e => { + const { value, name } = e.target; + this.setState({ + [name]: value, + }); + }; + render() { + const { handleInput } = this; + const { id, pw } = this.state; + return ( <div className="log_in_box"> <div className="title">westagram</div> <div className="log_in"> <div className="id"> <input + onChange={handleInput} className="id_input" + name="id" type="text" placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" /> </div> <div className="password"> <input + onChange={handleInput} className="password_input" + name="pw" type="password" placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" /> </div> </div> - <Login_Button /> + <Login_Button idvalue={this.state.id} pwvalue={this.state.pw} /> <p> ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”? </p> </div>
JavaScript
idValue๋ฅผ ๋„˜๊ฒจ์ฃผ๋Š” ๊ฑธ๋กœ ๋ณด์ด๋Š”๋ฐ idfunc๋ผ๋Š” ์ด๋ฆ„์€ ๋งˆ์น˜ ํ•จ์ˆ˜๊ฐ™์•„์„œ ์ ํ•ฉํ•˜์ง€ ์•Š์•„๋ณด์ž…๋‹ˆ๋‹ค! pwfunc, colorfunc ๋ชจ๋‘ ๋งˆ์ฐฌ๊ฐ€์ง€์ž…๋‹ˆ๋‹ค! ๊ทธ๋ฆฌ๊ณ  colorfunc๋ผ๋Š” ๊ฐ’์€ id๋ž‘ pwํ†ตํ•ด์„œ ๊ณ„์‚ฐ ๊ฐ€๋Šฅํ•ด๋ณด์ด๋Š”๋ฐ ๊ทธ๋Ÿฌ๋ฉด idValue๋ž‘ pwValue๋งŒ Props๋กœ ๋ฐ›๊ณ , colorfunc์—์„œ ๊ณ„์‚ฐ ํ•˜๋Š” ๊ฐ’์€ LoginButton ์ปดํฌ๋„ŒํŠธ์—์„œ propsํ†ตํ•ด์„œ ๋ฐ”๋กœ ๊ณ„์‚ฐํ•ด์„œ ์‚ฌ์šฉํ•ด๋„ ๋ฌด๋ฐฉํ•ด๋ณด์ž…๋‹ˆ๋‹ค!
@@ -1,14 +1,51 @@ import React, { Component } from 'react'; +import Comment from './Comment/Comment'; import './Feeds.scss'; class Feeds extends Component { + constructor(props) { + super(props); + this.state = { + comment: '', + comments: [], + idnumber: 1, + }; + } + + componentDidMount = () => { + this.setState({ comments: this.props.comments }); + }; + + handleComment = e => { + this.setState({ + comment: e.target.value, + }); + }; + + addComment = e => { + e.preventDefault(); + + this.setState({ + comments: this.state.comments.concat({ + id: this.state.idnumber + 3, + text: this.state.comment, + }), + comment: '', + idnumber: this.state.idnumber + 1, + }); + }; + render() { + const { comments, comment } = this.state; + const { handleComment, addComment } = this; + // console.log(this.state); + return ( <div className="feeds"> <article> <div className="feeds_profile"> <div className="feeds_profile_image"> - <img alt="ํ”„๋กœํ•„" src="/images/jaesangChoi/profile1.jpeg" /> + <img alt="profile" src={this.props.profilesrc} /> </div> <p className="feeds_profile_name"> <span className="feeds_profile_main_name"> @@ -23,28 +60,28 @@ class Feeds extends Component { <img alt="sunset" className="main_feed_img" - src="https://images.unsplash.com/photo-1623659993428-0c5504a16ca5?ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw0Mnx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" + src={this.props.mainfeedsrc} /> </div> <div className="comment_icon_box"> <div className="left_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> <img - alt="์ฝ”๋ฉ˜ํŠธ์•„์ด์ฝ˜" + alt="comment_icon" src="/images/jaesangChoi/commentary.png" /> - <img alt="๊ณต์œ ์•„์ด์ฝ˜" src="/images/jaesangChoi/send.png" /> + <img alt="share_icon" src="/images/jaesangChoi/send.png" /> </div> <div className="right_icon"> - <img alt="๋ถ๋งˆํฌ์•„์ด์ฝ˜" src="/images/jaesangChoi/bookmark.png" /> + <img alt="bookmark_icon" src="/images/jaesangChoi/bookmark.png" /> </div> </div> <div className="comment_profile"> <div className="comment_profile_icon"> <img - alt="ํ”„๋กœํ•„" + alt="profile" src="/images/jaesangChoi/comment_profile.jpeg" /> </div> @@ -67,25 +104,33 @@ class Feeds extends Component { ์ข‹์•˜์ž–์•„~~~~~ </div> <div className="second_comment_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> </div> </div> <div className="third_comment">42๋ถ„ ์ „</div> + <ul className="comment_list"> + {comments.map(comment => { + return <Comment key={comment.id} text={comment.text} />; + })} + </ul> + <div className="push_comment"> <div className="push_comment_icon"> - <img alt="์Šค๋งˆ์ผ์•„์ด์ฝ˜" src="/images/jaesangChoi/smile.png" /> + <img alt="smile_icon" src="/images/jaesangChoi/smile.png" /> </div> - <div className="push_comment_text"> + <form className="push_comment_text" onSubmit={addComment}> <input + onChange={handleComment} + value={comment} className="input_comment" type="text" placeholder="๋Œ“๊ธ€๋‹ฌ๊ธฐ..." /> - </div> + </form> <div className="push_comment_button"> - <button>๊ฒŒ์‹œ</button> + <button onClick={addComment}>๊ฒŒ์‹œ</button> </div> </div> </article>
JavaScript
api์ฃผ์†Œ๊ฐ€ data์•ˆ์— ๋“ค์–ด์žˆ๋Š” ํ˜•ํƒœ๋Š” ๋น„์ •์ƒ์ ์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! api์ฃผ์†Œ๋Š” ์ผ๋ฐ˜์ ์œผ๋กœ ๋ฐฑ์—”๋“œ์—์„œ ์ „์†กํ•ด์ฃผ์ง€ ์•Š์Šต๋‹ˆ๋‹ค! comment์ •๋ณด๋ž‘ feed์ •๋ณด๋ฅผ ๋ถ„๋ฆฌ์‹œ์ผœ๋†“์œผ์…”์„œ ๊ทธ๋Ÿฐ ๊ฒƒ ๊ฐ™์€๋ฐ, feed์•ˆ์— comment์ •๋ณด๋ฅผ ๊ทธ๋ƒฅ ๋‹ค ๋„ฃ์–ด์ฃผ์‹œ๋ฉด ๋  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ``` { id: 1, profilesrc: '/images/jaesangChoi/profile1.jpeg', mainfeedsrc: 'https://images.unsplash.com/photo-1623659993428-0c5504a16ca5?ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw0Mnx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60', comment:["foo","bar"] }, ``` ์ด๋Ÿฐ์‹์œผ๋กœ์š”! ์ฝ”๋ฉ˜ํŠธ๋ž€ ์ •๋ณด๋Š” ํ”ผ๋“œ์— ์ข…์†๋˜์–ด ์žˆ๋Š” ์ •๋ณด๋‹ˆ๊นŒ ์ €๋Ÿฐ ํ˜•ํƒœ๊ฐ€ ์ ํ•ฉํ•ด๋ณด์ž…๋‹ˆ๋‹ค!
@@ -1,14 +1,51 @@ import React, { Component } from 'react'; +import Comment from './Comment/Comment'; import './Feeds.scss'; class Feeds extends Component { + constructor(props) { + super(props); + this.state = { + comment: '', + comments: [], + idnumber: 1, + }; + } + + componentDidMount = () => { + this.setState({ comments: this.props.comments }); + }; + + handleComment = e => { + this.setState({ + comment: e.target.value, + }); + }; + + addComment = e => { + e.preventDefault(); + + this.setState({ + comments: this.state.comments.concat({ + id: this.state.idnumber + 3, + text: this.state.comment, + }), + comment: '', + idnumber: this.state.idnumber + 1, + }); + }; + render() { + const { comments, comment } = this.state; + const { handleComment, addComment } = this; + // console.log(this.state); + return ( <div className="feeds"> <article> <div className="feeds_profile"> <div className="feeds_profile_image"> - <img alt="ํ”„๋กœํ•„" src="/images/jaesangChoi/profile1.jpeg" /> + <img alt="profile" src={this.props.profilesrc} /> </div> <p className="feeds_profile_name"> <span className="feeds_profile_main_name"> @@ -23,28 +60,28 @@ class Feeds extends Component { <img alt="sunset" className="main_feed_img" - src="https://images.unsplash.com/photo-1623659993428-0c5504a16ca5?ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw0Mnx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" + src={this.props.mainfeedsrc} /> </div> <div className="comment_icon_box"> <div className="left_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> <img - alt="์ฝ”๋ฉ˜ํŠธ์•„์ด์ฝ˜" + alt="comment_icon" src="/images/jaesangChoi/commentary.png" /> - <img alt="๊ณต์œ ์•„์ด์ฝ˜" src="/images/jaesangChoi/send.png" /> + <img alt="share_icon" src="/images/jaesangChoi/send.png" /> </div> <div className="right_icon"> - <img alt="๋ถ๋งˆํฌ์•„์ด์ฝ˜" src="/images/jaesangChoi/bookmark.png" /> + <img alt="bookmark_icon" src="/images/jaesangChoi/bookmark.png" /> </div> </div> <div className="comment_profile"> <div className="comment_profile_icon"> <img - alt="ํ”„๋กœํ•„" + alt="profile" src="/images/jaesangChoi/comment_profile.jpeg" /> </div> @@ -67,25 +104,33 @@ class Feeds extends Component { ์ข‹์•˜์ž–์•„~~~~~ </div> <div className="second_comment_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> </div> </div> <div className="third_comment">42๋ถ„ ์ „</div> + <ul className="comment_list"> + {comments.map(comment => { + return <Comment key={comment.id} text={comment.text} />; + })} + </ul> + <div className="push_comment"> <div className="push_comment_icon"> - <img alt="์Šค๋งˆ์ผ์•„์ด์ฝ˜" src="/images/jaesangChoi/smile.png" /> + <img alt="smile_icon" src="/images/jaesangChoi/smile.png" /> </div> - <div className="push_comment_text"> + <form className="push_comment_text" onSubmit={addComment}> <input + onChange={handleComment} + value={comment} className="input_comment" type="text" placeholder="๋Œ“๊ธ€๋‹ฌ๊ธฐ..." /> - </div> + </form> <div className="push_comment_button"> - <button>๊ฒŒ์‹œ</button> + <button onClick={addComment}>๊ฒŒ์‹œ</button> </div> </div> </article>
JavaScript
get method๋Š” ๊ธฐ๋ณธ๊ฐ’์ด๋ผ์„œ ๋”ฐ๋กœ ๊ธฐ์ž…์•ˆํ•ด์ฃผ์…”๋„ ๋ฉ๋‹ˆ๋‹ค!
@@ -1,14 +1,51 @@ import React, { Component } from 'react'; +import Comment from './Comment/Comment'; import './Feeds.scss'; class Feeds extends Component { + constructor(props) { + super(props); + this.state = { + comment: '', + comments: [], + idnumber: 1, + }; + } + + componentDidMount = () => { + this.setState({ comments: this.props.comments }); + }; + + handleComment = e => { + this.setState({ + comment: e.target.value, + }); + }; + + addComment = e => { + e.preventDefault(); + + this.setState({ + comments: this.state.comments.concat({ + id: this.state.idnumber + 3, + text: this.state.comment, + }), + comment: '', + idnumber: this.state.idnumber + 1, + }); + }; + render() { + const { comments, comment } = this.state; + const { handleComment, addComment } = this; + // console.log(this.state); + return ( <div className="feeds"> <article> <div className="feeds_profile"> <div className="feeds_profile_image"> - <img alt="ํ”„๋กœํ•„" src="/images/jaesangChoi/profile1.jpeg" /> + <img alt="profile" src={this.props.profilesrc} /> </div> <p className="feeds_profile_name"> <span className="feeds_profile_main_name"> @@ -23,28 +60,28 @@ class Feeds extends Component { <img alt="sunset" className="main_feed_img" - src="https://images.unsplash.com/photo-1623659993428-0c5504a16ca5?ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw0Mnx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" + src={this.props.mainfeedsrc} /> </div> <div className="comment_icon_box"> <div className="left_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> <img - alt="์ฝ”๋ฉ˜ํŠธ์•„์ด์ฝ˜" + alt="comment_icon" src="/images/jaesangChoi/commentary.png" /> - <img alt="๊ณต์œ ์•„์ด์ฝ˜" src="/images/jaesangChoi/send.png" /> + <img alt="share_icon" src="/images/jaesangChoi/send.png" /> </div> <div className="right_icon"> - <img alt="๋ถ๋งˆํฌ์•„์ด์ฝ˜" src="/images/jaesangChoi/bookmark.png" /> + <img alt="bookmark_icon" src="/images/jaesangChoi/bookmark.png" /> </div> </div> <div className="comment_profile"> <div className="comment_profile_icon"> <img - alt="ํ”„๋กœํ•„" + alt="profile" src="/images/jaesangChoi/comment_profile.jpeg" /> </div> @@ -67,25 +104,33 @@ class Feeds extends Component { ์ข‹์•˜์ž–์•„~~~~~ </div> <div className="second_comment_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> </div> </div> <div className="third_comment">42๋ถ„ ์ „</div> + <ul className="comment_list"> + {comments.map(comment => { + return <Comment key={comment.id} text={comment.text} />; + })} + </ul> + <div className="push_comment"> <div className="push_comment_icon"> - <img alt="์Šค๋งˆ์ผ์•„์ด์ฝ˜" src="/images/jaesangChoi/smile.png" /> + <img alt="smile_icon" src="/images/jaesangChoi/smile.png" /> </div> - <div className="push_comment_text"> + <form className="push_comment_text" onSubmit={addComment}> <input + onChange={handleComment} + value={comment} className="input_comment" type="text" placeholder="๋Œ“๊ธ€๋‹ฌ๊ธฐ..." /> - </div> + </form> <div className="push_comment_button"> - <button>๊ฒŒ์‹œ</button> + <button onClick={addComment}>๊ฒŒ์‹œ</button> </div> </div> </article>
JavaScript
๋Œ“๊ธ€์€ ๋‚˜์ค‘์— ์‚ญ์ œ๋  ์ˆ˜๋„ ์žˆ์œผ๋‹ˆ๊นŒ id๋ฅผ length๋กœ ์‚ฌ์šฉํ•˜๋ฉด ์‚ญ์ œ ํ›„ ๋‹ค์‹œ ์ถ”๊ฐ€๋˜๋Š” ๊ฒฝ์šฐ ๋™์ผํ•œ id๋ฅผ ๊ฐ€์ง„ ๋Œ“๊ธ€์ด ์ƒ๊ธธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -1,14 +1,51 @@ import React, { Component } from 'react'; +import Comment from './Comment/Comment'; import './Feeds.scss'; class Feeds extends Component { + constructor(props) { + super(props); + this.state = { + comment: '', + comments: [], + idnumber: 1, + }; + } + + componentDidMount = () => { + this.setState({ comments: this.props.comments }); + }; + + handleComment = e => { + this.setState({ + comment: e.target.value, + }); + }; + + addComment = e => { + e.preventDefault(); + + this.setState({ + comments: this.state.comments.concat({ + id: this.state.idnumber + 3, + text: this.state.comment, + }), + comment: '', + idnumber: this.state.idnumber + 1, + }); + }; + render() { + const { comments, comment } = this.state; + const { handleComment, addComment } = this; + // console.log(this.state); + return ( <div className="feeds"> <article> <div className="feeds_profile"> <div className="feeds_profile_image"> - <img alt="ํ”„๋กœํ•„" src="/images/jaesangChoi/profile1.jpeg" /> + <img alt="profile" src={this.props.profilesrc} /> </div> <p className="feeds_profile_name"> <span className="feeds_profile_main_name"> @@ -23,28 +60,28 @@ class Feeds extends Component { <img alt="sunset" className="main_feed_img" - src="https://images.unsplash.com/photo-1623659993428-0c5504a16ca5?ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw0Mnx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" + src={this.props.mainfeedsrc} /> </div> <div className="comment_icon_box"> <div className="left_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> <img - alt="์ฝ”๋ฉ˜ํŠธ์•„์ด์ฝ˜" + alt="comment_icon" src="/images/jaesangChoi/commentary.png" /> - <img alt="๊ณต์œ ์•„์ด์ฝ˜" src="/images/jaesangChoi/send.png" /> + <img alt="share_icon" src="/images/jaesangChoi/send.png" /> </div> <div className="right_icon"> - <img alt="๋ถ๋งˆํฌ์•„์ด์ฝ˜" src="/images/jaesangChoi/bookmark.png" /> + <img alt="bookmark_icon" src="/images/jaesangChoi/bookmark.png" /> </div> </div> <div className="comment_profile"> <div className="comment_profile_icon"> <img - alt="ํ”„๋กœํ•„" + alt="profile" src="/images/jaesangChoi/comment_profile.jpeg" /> </div> @@ -67,25 +104,33 @@ class Feeds extends Component { ์ข‹์•˜์ž–์•„~~~~~ </div> <div className="second_comment_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> </div> </div> <div className="third_comment">42๋ถ„ ์ „</div> + <ul className="comment_list"> + {comments.map(comment => { + return <Comment key={comment.id} text={comment.text} />; + })} + </ul> + <div className="push_comment"> <div className="push_comment_icon"> - <img alt="์Šค๋งˆ์ผ์•„์ด์ฝ˜" src="/images/jaesangChoi/smile.png" /> + <img alt="smile_icon" src="/images/jaesangChoi/smile.png" /> </div> - <div className="push_comment_text"> + <form className="push_comment_text" onSubmit={addComment}> <input + onChange={handleComment} + value={comment} className="input_comment" type="text" placeholder="๋Œ“๊ธ€๋‹ฌ๊ธฐ..." /> - </div> + </form> <div className="push_comment_button"> - <button>๊ฒŒ์‹œ</button> + <button onClick={addComment}>๊ฒŒ์‹œ</button> </div> </div> </article>
JavaScript
ํ•จ์ˆ˜๋Š” return๋ฌธ ๋”ฐ๋กœ ์—†์œผ๋ฉด ๋๊นŒ์ง€ ๋‹ค ์ฝ๊ณ ๋‚˜์„œ ์•Œ์•„์„œ ์ข…๋ฃŒ๋˜๊ธฐ๋•Œ๋ฌธ์— ์ž„์˜๋กœ return ํ‚ค์›Œ๋“œ๋ฅผ ์ ์„ ํ•„์š”๋Š” ์—†์–ด๋ณด์ž…๋‹ˆ๋‹ค!
@@ -1,14 +1,51 @@ import React, { Component } from 'react'; +import Comment from './Comment/Comment'; import './Feeds.scss'; class Feeds extends Component { + constructor(props) { + super(props); + this.state = { + comment: '', + comments: [], + idnumber: 1, + }; + } + + componentDidMount = () => { + this.setState({ comments: this.props.comments }); + }; + + handleComment = e => { + this.setState({ + comment: e.target.value, + }); + }; + + addComment = e => { + e.preventDefault(); + + this.setState({ + comments: this.state.comments.concat({ + id: this.state.idnumber + 3, + text: this.state.comment, + }), + comment: '', + idnumber: this.state.idnumber + 1, + }); + }; + render() { + const { comments, comment } = this.state; + const { handleComment, addComment } = this; + // console.log(this.state); + return ( <div className="feeds"> <article> <div className="feeds_profile"> <div className="feeds_profile_image"> - <img alt="ํ”„๋กœํ•„" src="/images/jaesangChoi/profile1.jpeg" /> + <img alt="profile" src={this.props.profilesrc} /> </div> <p className="feeds_profile_name"> <span className="feeds_profile_main_name"> @@ -23,28 +60,28 @@ class Feeds extends Component { <img alt="sunset" className="main_feed_img" - src="https://images.unsplash.com/photo-1623659993428-0c5504a16ca5?ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw0Mnx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" + src={this.props.mainfeedsrc} /> </div> <div className="comment_icon_box"> <div className="left_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> <img - alt="์ฝ”๋ฉ˜ํŠธ์•„์ด์ฝ˜" + alt="comment_icon" src="/images/jaesangChoi/commentary.png" /> - <img alt="๊ณต์œ ์•„์ด์ฝ˜" src="/images/jaesangChoi/send.png" /> + <img alt="share_icon" src="/images/jaesangChoi/send.png" /> </div> <div className="right_icon"> - <img alt="๋ถ๋งˆํฌ์•„์ด์ฝ˜" src="/images/jaesangChoi/bookmark.png" /> + <img alt="bookmark_icon" src="/images/jaesangChoi/bookmark.png" /> </div> </div> <div className="comment_profile"> <div className="comment_profile_icon"> <img - alt="ํ”„๋กœํ•„" + alt="profile" src="/images/jaesangChoi/comment_profile.jpeg" /> </div> @@ -67,25 +104,33 @@ class Feeds extends Component { ์ข‹์•˜์ž–์•„~~~~~ </div> <div className="second_comment_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> </div> </div> <div className="third_comment">42๋ถ„ ์ „</div> + <ul className="comment_list"> + {comments.map(comment => { + return <Comment key={comment.id} text={comment.text} />; + })} + </ul> + <div className="push_comment"> <div className="push_comment_icon"> - <img alt="์Šค๋งˆ์ผ์•„์ด์ฝ˜" src="/images/jaesangChoi/smile.png" /> + <img alt="smile_icon" src="/images/jaesangChoi/smile.png" /> </div> - <div className="push_comment_text"> + <form className="push_comment_text" onSubmit={addComment}> <input + onChange={handleComment} + value={comment} className="input_comment" type="text" placeholder="๋Œ“๊ธ€๋‹ฌ๊ธฐ..." /> - </div> + </form> <div className="push_comment_button"> - <button>๊ฒŒ์‹œ</button> + <button onClick={addComment}>๊ฒŒ์‹œ</button> </div> </div> </article>
JavaScript
์—ฌ๊ธฐ๋Š” alt๋ฅผ ํ•œ๊ธ€๋กœ ์ ๊ณ  ๋‹ค๋ฅธ ๊ณณ์€ ์˜์–ด๋กœ ์ ์œผ์‹  ์ด์œ ๊ฐ€ ์žˆ์œผ์‹ค๊นŒ์š”?? ์˜์–ด๋กœ ์ ์–ด์ฃผ์‹œ๋Š”๊ฒŒ ์ข‹์•„๋ณด์ž…๋‹ˆ๋‹ค! ํ•œ๊ธ€์ด ๋” ์ข‹์ง€๋งŒ,, ๋งŒ๊ตญ ๊ณต์šฉ์–ด๊ฐ€ ์˜์–ด๊ธฐ ๋•Œ๋ฌธ์— ๋ณดํŽธ์„ฑ์„ ์œ„ํ•ด์„œ ๐Ÿ˜‚
@@ -1,14 +1,51 @@ import React, { Component } from 'react'; +import Comment from './Comment/Comment'; import './Feeds.scss'; class Feeds extends Component { + constructor(props) { + super(props); + this.state = { + comment: '', + comments: [], + idnumber: 1, + }; + } + + componentDidMount = () => { + this.setState({ comments: this.props.comments }); + }; + + handleComment = e => { + this.setState({ + comment: e.target.value, + }); + }; + + addComment = e => { + e.preventDefault(); + + this.setState({ + comments: this.state.comments.concat({ + id: this.state.idnumber + 3, + text: this.state.comment, + }), + comment: '', + idnumber: this.state.idnumber + 1, + }); + }; + render() { + const { comments, comment } = this.state; + const { handleComment, addComment } = this; + // console.log(this.state); + return ( <div className="feeds"> <article> <div className="feeds_profile"> <div className="feeds_profile_image"> - <img alt="ํ”„๋กœํ•„" src="/images/jaesangChoi/profile1.jpeg" /> + <img alt="profile" src={this.props.profilesrc} /> </div> <p className="feeds_profile_name"> <span className="feeds_profile_main_name"> @@ -23,28 +60,28 @@ class Feeds extends Component { <img alt="sunset" className="main_feed_img" - src="https://images.unsplash.com/photo-1623659993428-0c5504a16ca5?ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw0Mnx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" + src={this.props.mainfeedsrc} /> </div> <div className="comment_icon_box"> <div className="left_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> <img - alt="์ฝ”๋ฉ˜ํŠธ์•„์ด์ฝ˜" + alt="comment_icon" src="/images/jaesangChoi/commentary.png" /> - <img alt="๊ณต์œ ์•„์ด์ฝ˜" src="/images/jaesangChoi/send.png" /> + <img alt="share_icon" src="/images/jaesangChoi/send.png" /> </div> <div className="right_icon"> - <img alt="๋ถ๋งˆํฌ์•„์ด์ฝ˜" src="/images/jaesangChoi/bookmark.png" /> + <img alt="bookmark_icon" src="/images/jaesangChoi/bookmark.png" /> </div> </div> <div className="comment_profile"> <div className="comment_profile_icon"> <img - alt="ํ”„๋กœํ•„" + alt="profile" src="/images/jaesangChoi/comment_profile.jpeg" /> </div> @@ -67,25 +104,33 @@ class Feeds extends Component { ์ข‹์•˜์ž–์•„~~~~~ </div> <div className="second_comment_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> </div> </div> <div className="third_comment">42๋ถ„ ์ „</div> + <ul className="comment_list"> + {comments.map(comment => { + return <Comment key={comment.id} text={comment.text} />; + })} + </ul> + <div className="push_comment"> <div className="push_comment_icon"> - <img alt="์Šค๋งˆ์ผ์•„์ด์ฝ˜" src="/images/jaesangChoi/smile.png" /> + <img alt="smile_icon" src="/images/jaesangChoi/smile.png" /> </div> - <div className="push_comment_text"> + <form className="push_comment_text" onSubmit={addComment}> <input + onChange={handleComment} + value={comment} className="input_comment" type="text" placeholder="๋Œ“๊ธ€๋‹ฌ๊ธฐ..." /> - </div> + </form> <div className="push_comment_button"> - <button>๊ฒŒ์‹œ</button> + <button onClick={addComment}>๊ฒŒ์‹œ</button> </div> </div> </article>
JavaScript
t๋ผ๋Š” ๋ณ€์ˆ˜๋ช…์„ ๊ฐ€์ง€๊ณ ๋Š” ์—ฌ๊ธฐ์— ํ• ๋‹น๋œ ๊ฐ’์ด ๋ญ์ผ์ง€ ์ „ํ˜€ ์œ ์ถ”๊ฐ€ ์•ˆ๋˜๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! comments ๋ฐฐ์—ด์•ˆ์˜ ํ•˜๋‚˜ํ•˜๋‚˜์˜ ์š”์†Œ๋“ค์ด๋‹ˆ๊นŒ comment๋ผ๊ณ  ์ด๋ฆ„์ง€์–ด์ฃผ๋Š”๊ฒŒ ์ข‹์ง€ ์•Š์„๊นŒ์š”? ```suggestion {comments.map(comment => { ```