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์ ๋ด๋ถ ํด๋์ค)
+
+
+
+### ์๊ตฌ ์ฌํญ
+- [X] ๊ธฐ์กด Interceptor ์ธ์ฆ ๋ก์ง ๋ณํ
+ - ์ ๊ณต๋ Interceptor ๊ธฐ๋ฐ ์ธ์ฆ ๋ก์ง์ Filter๋ก ๋ณํ
+ - ๋ณํ๋ Filter๋ HttpServletRequest์ HttpServletResponse๋ฅผ ์ฒ๋ฆฌํ๋ฉฐ, ์ธ์ฆ ์ฌ๋ถ๋ฅผ ๊ฒฐ์
+ - ์์ฒญ์ด ์ธ์ฆ๋์ง ์์ ๊ฒฝ์ฐ, ์ ์ ํ HTTP ์ํ ์ฝ๋(์: 401 Unauthorized) ๋ฐํ
+ - ์ธ์ฆ๋ ์ฌ์ฉ์ ์ ๋ณด๋ ์์ฒญ ๊ฐ์ฒด์ ์ถ๊ฐํ์ฌ ์ดํ ํํฐ์์ ์ ๊ทผ ๊ฐ๋ฅํ๋๋ก ์ค์
+- [X] DelegatingFilterProxy ์ค์
+ - Spring Bean์ผ๋ก DelegatingFilterProxy๋ฅผ ๋ฑ๋กํ๊ณ ์ด๋ฅผ ํตํด FilterChainProxy๋ฅผ ํธ์ถํ๋๋ก ์ค์
+ - DelegatingFilterProxy๋ Servlet ์ปจํ
์ด๋์ Filter์ Spring ์ปจํ
์คํธ๋ฅผ ์ฐ๊ฒฐ
+- [X] FilterChainProxy ๊ตฌํ
+ - FilterChainProxy๋ ์์ฒญ URI์ ๋ฐ๋ผ ์ ์ ํ SecurityFilterChain์ ์ ํํ์ฌ ์คํ
+ - SecurityFilterChain์ Filter ๋ฆฌ์คํธ๋ฅผ ํฌํจํ๋ฉฐ ์์ฒญ์ ์ฒ๋ฆฌ
+- [X] SecurityFilterChain ๋ฆฌํฉํฐ๋ง
+ - ๊ฐ SecurityFilterChain์ ์ญํ ์ ๋ฐ๋ผ ๋ค๋ฅธ ํํฐ ์ธํธ๋ฅผ ๊ด๋ฆฌ
+ - ์ธ์ฆ(Authentication) ํํฐ์ ๊ถํ(Authorization) ํํฐ๋ฅผ ํฌํจํ๋๋ก ๊ตฌ์ฑ
+
+## 2๋จ๊ณ - AuthenticationManager ์ ์ฉ
+
+๋ค์ํ ์ธ์ฆ ๋ฐฉ์์ ์ฒ๋ฆฌํ๊ธฐ ์ํด AuthenticationManager๋ฅผ ํ์ฉํ์ฌ ์ธ์ฆ ๊ณผ์ ์ ์ถ์ํํ๋ค.
+๊ธฐ์กด์ ์ธ์ฆ ๋ก์ง์ ๋ถ๋ฆฌํ๊ณ , ์ธ์ฆ ๋ฐฉ์์ ์ ์ฐํ๊ฒ ํ์ฅ ๊ฐ๋ฅํ๋๋ก ๊ตฌ์กฐํํ๋ค.
+์ฃผ์ ํด๋์ค: AuthenticationManager, ProviderManager, AuthenticationProvider, DaoAuthenticationProvider
+
+
+
+### ์๊ตฌ ์ฌํญ
+
+- [X] Authentication์ UsernamePasswordAuthenticationToken ๊ตฌํ
+- [X] ์ ๊ณต๋ AuthenticationManager๋ฅผ ๊ธฐ๋ฐ์ผ๋ก ProviderManager ๊ตฌํ
+- [X] ์ ๊ณต๋ AuthenticationProvider๋ฅผ ๊ธฐ๋ฐ์ผ๋ก DaoAuthenticationProvider ๊ตฌํ
+- [X] ๊ธฐ์กด ์ธ์ฆ ํํฐ์์ ์ธ์ฆ ๋ก์ง ๋ถ๋ฆฌ ๋ฐ AuthenticationManager๋ก ํตํฉ
+
+## 3๋จ๊ณ - SecurityContextHolder ์ ์ฉ
+- ์ธ์ฆ ์ฑ๊ณต ํ ์์ฑ๋ Authentication ๊ฐ์ฒด๋ฅผ ๊ธฐ์กด์ ์ธ์
๋ฐฉ์ ๋์ ์ค๋ ๋ ๋ก์ปฌ(Thread Local)์ ๋ณด๊ดํ๋๋ก ๋ณ๊ฒฝํ๋ค.
+- ๊ฐ ํํฐ์์ ์ค๋ ๋ ๋ก์ปฌ์ ๋ณด๊ด๋ ์ธ์ฆ ์ ๋ณด๋ฅผ ์ ๊ทผํ ์ ์๋๋ก SecurityContextHolder์ SecurityContext ๊ตฌ์กฐ๋ฅผ ๊ตฌํํ๋ค.
+
+
+
+### ์๊ตฌ์ฌํญ
+-[X] SecurityContext ๋ฐ SecurityContextHolder ์์ฑ
+-[X] BasicAuthenticationFilter์์ SecurityContextHolder ํ์ฉ
+-[X] ๊ธฐ์กด ์ธ์
๋ฐฉ์์์ ์ค๋ ๋ ๋ก์ปฌ ๋ฐฉ์์ผ๋ก ์ธ์ฆ ์ ๋ณด ๊ด๋ฆฌ ๋ณ๊ฒฝ
+
+## 4๋จ๊ณ - SecurityContextHolderFilter ๊ตฌํ
+* ์ธ์
์ ๋ณด๊ด๋ ์ธ์ฆ ์ ๋ณด๋ฅผ SecurityContextHolder๋ก ์ฎ๊ธฐ๊ธฐ ์ํ SecurityContextHolderFilter๋ฅผ ๊ตฌํํ๋ค.
+
+### ์๊ตฌ ์ฌํญ
+- [X] SecurityContextRepository ์ธํฐํ์ด์ค๋ฅผ ๊ธฐ๋ฐ์ผ๋ก HttpSessionSecurityContextRepository ๊ตฌํ
+- [X] SecurityContextHolderFilter ์์ฑ ๋ฐ ํํฐ ์ฒด์ธ์ ๋ฑ๋ก
+- [X] login_after_members ํ
์คํธ๋ก ๋์ ๊ฒ์ฆ
+ | Unknown | ์๊ตฌ์ฌํญ์ ์์ฃผ ๊ผผ๊ผผํ๊ฒ ์์ฑํด ์ฃผ์
จ๋ค์! ๐ |
@@ -0,0 +1,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 => {
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.