code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -0,0 +1,13 @@ +const express = require('express'); +const router = express.Router(); +const middleware = require('../middlewares'); +const { userController } = require('../controllers'); +// Route ๋Š” ์˜ค์ง Controller ์—๋งŒ ์˜์กด ํ•ฉ๋‹ˆ๋‹ค. + +router.post( + '/signup', + [middleware.validateSignUpUserData, middleware.hashPassword], + userController.signUp, +); + +module.exports = router;
JavaScript
convention ์ˆ˜์ •ํ•˜๋ ค๋‹ค๊ฐ€ ๋†“์นœ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค... ๊ด€๋ จ๋œ ๋ถ€๋ถ„ ๋ชจ๋‘ ์ˆ˜์ •ํ•˜๊ณ  ํšŒ์›๊ฐ€์ž…๋„ ํ™•์ธํ–ˆ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
dao์™€ services๋กœ ๋ถ„๋ฆฌํ•˜๊ธฐ๋กœ ๊ฒฐ์ •ํ–ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,40 @@ +// Controller๋Š” ์˜ค์ง Service ๋ ˆ์ด์–ด์—๋งŒ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. +const { userService } = require('../services'); +const { errorGenerator } = require('../erros'); + +const signUp = async (req, res, next) => { + try { + const { + email, + hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + } = req.body; + + /* + middleware์—์„œ email, hashedPassword, phoneNumber์˜ + ์กด์žฌ์— ๋Œ€ํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ–ˆ๋Š”๋ฐ, + ์—ฌ๊ธฐ์„œ๋„ ๋˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ• ๊นŒ์š”? + */ + + const createdUser = await userService.createUser({ + email, + password: hashedPassword, + phoneNumber, + profileImageUrl, + introduction, + }); + + res.status(201).json({ + message: 'user created', + userId: createdUser.id, + }); + } catch (err) { + next(err); + } +}; + +module.exports = { + signUp, +};
JavaScript
์ œ๊ฐ€ ์ฐฉ๊ฐํ–ˆ๋„ค์š”! ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค :)
@@ -0,0 +1,20 @@ +const { errorGenerator } = require('../erros'); +const { userService } = require('../services'); + +const hashPassword = async (req, res, next) => { + try { + const { password } = req.body; + + !password && errorGenerator(400); + + req.body.hashedPassword = await userService.hashPassword(password); + + next(); + } catch (err) { + next(err); + } +}; + +module.exports = { + hashPassword, +};
JavaScript
๋ฏธ๋“ค์›จ์–ด์—์„œ ๋น„๋ฐ€๋ฒˆํ˜ธ ์•”ํ˜ธํ™”๋ฅผ ํ•˜๋Š” ๊ฑด๊ฐ€์š”? ์ด ๋ฐฉ๋ฒ•๋„ ๊ต‰์žฅํžˆ ์ฐธ์‹ ํ•œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๋งŒ์•ฝ ์„œ๋น„์Šค๊ฐ€ ์ปค์ง€๊ฒŒ ๋˜๊ฑฐ๋‚˜, ๋ชจ๋…ธ๋ฆฌํฌ๋ฅผ ์ ์šฉํ•œ๋‹ค๊ฑฐ๋‚˜, ๊ธฐํƒ€ ๋‹ค์–‘ํ•œ ๋ฐฉ์‹์œผ๋กœ ๋น„๋ฐ€๋ฒˆํ˜ธ ์•”ํ˜ธํ™”๋ฅผ ํ™œ์šฉํ•˜๊ฒŒ ๋  ๊ฒฝ์šฐ๊ฐ€ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ๋ณดํ†ต util ํ•จ์ˆ˜๋กœ ๋นผ๋‚ด์–ด ๋‹ค๋ฅธ ๊ณณ์—์„œ๋„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋„๋ก ๊ณตํ†ต ํ•จ์ˆ˜๋กœ ๋งŒ๋“œ๋Š” ๊ฒƒ์ด ์กฐ๊ธˆ ๋” ๋ณดํŽธ์ ์ด๊ธฐ๋Š” ํ•œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,31 @@ +const { errorGenerator } = require('../erros'); +const { userService } = require('../services'); + +const validateSignUpUserData = async (req, res, next) => { + try { + const { email, password, phoneNumber, profileImageUrl, introduction } = + req.body; + + const REQUIRED_INFO = { email, password, phoneNumber }; + + for (const info in REQUIRED_INFO) { + !REQUIRED_INFO[info] && errorGenerator(400, `MISSING ${info}`); + } + + !userService.validateEmail(email) && errorGenerator(400, 'INVALID EMAIL'); + + const foundUser = await userService.findUser({ email }); + foundUser && errorGenerator(409); + + !userService.validatePw(password) && + errorGenerator(400, 'INVALID PASSWORD'); + + next(); + } catch (err) { + next(err); + } +}; + +module.exports = { + validateSignUpUserData, +};
JavaScript
๋‹ค๋ฅธ POST ์—์„œ๋„ ํ•„์ˆ˜์ ์ธ ํ‚ค๊ฐ’๋“ค์„ ํ™•์ธํ•  ์ผ์ด ๋งŽ์ง€ ์•Š์„๊นŒ์š”? ๋ฒ”์šฉ์ ์œผ๋กœ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ๋Š” + ํ•„์ˆ˜ body ํ‚ค ๊ฐ’์„ ํ™•์ธํ•˜๋Š” ๊ณตํ†ต ํ•จ์ˆ˜๊ฐ€ ์žˆ์–ด๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,48 @@ +const bcrypt = require('bcrypt'); +const { userDao } = require('../dao'); + +const validateEmail = (email) => { + const validEmailRegExp = /\w@\w+\.\w/i; + return validEmailRegExp.test(email); +}; + +const validatePw = (pw) => { + const pwValidation = { + regexUppercase: /[A-Z]/g, + regexLowercase: /[a-z]/g, + regexSpecialCharacter: /[!|@|#|$|%|^|&|*]/g, + regexDigit: /[0-9]/g, + }; + const MIN_PW_LENGTH = 8; + const pwLength = pw.length; + + if (pwLength < MIN_PW_LENGTH) return false; + + for (const validType in pwValidation) { + if (!pwValidation[validType].test(pw)) { + return false; + } + } + + return true; +}; + +const hashPassword = async (password) => { + return await bcrypt.hash(password, 10); +}; + +const findUser = async (fields) => { + return await userDao.findUser(fields); +}; + +const createUser = async (userData) => { + return await userDao.createUser(userData); +}; + +module.exports = { + validateEmail, + validatePw, + hashPassword, + findUser, + createUser, +};
JavaScript
Regex ๊ฐ์ฒด๋ฅผ ํ™œ์šฉํ•ด์„œ ์กฐ๊ธˆ ๋” ๊ฐ„๋‹จํ•˜๊ฒŒ ์ž‘์„ฑํ•˜๋Š” ๊ฒƒ์€ ์–ด๋–ค๊ฐ€์š”? Regex.prototype.test ์ž์ฒด๊ฐ€ boolean ์„ ๋ฐ˜ํ™˜ํ•˜๊ฒŒ ๋˜๋‹ˆ๊นŒ์š”! +test ๋ฉ”์„œ๋“œ๊ฐ€ match ๋ณด๋‹ค ์„ฑ๋Šฅ์ƒ ์šฐ์œ„์— ์žˆ๊ธฐ๋„ ํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,20 @@ +const { errorGenerator } = require('../erros'); +const { userService } = require('../services'); + +const hashPassword = async (req, res, next) => { + try { + const { password } = req.body; + + !password && errorGenerator(400); + + req.body.hashedPassword = await userService.hashPassword(password); + + next(); + } catch (err) { + next(err); + } +}; + +module.exports = { + hashPassword, +};
JavaScript
๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,31 @@ +const { errorGenerator } = require('../erros'); +const { userService } = require('../services'); + +const validateSignUpUserData = async (req, res, next) => { + try { + const { email, password, phoneNumber, profileImageUrl, introduction } = + req.body; + + const REQUIRED_INFO = { email, password, phoneNumber }; + + for (const info in REQUIRED_INFO) { + !REQUIRED_INFO[info] && errorGenerator(400, `MISSING ${info}`); + } + + !userService.validateEmail(email) && errorGenerator(400, 'INVALID EMAIL'); + + const foundUser = await userService.findUser({ email }); + foundUser && errorGenerator(409); + + !userService.validatePw(password) && + errorGenerator(400, 'INVALID PASSWORD'); + + next(); + } catch (err) { + next(err); + } +}; + +module.exports = { + validateSignUpUserData, +};
JavaScript
์˜ค...! ๋งค์šฐ ์œ ์šฉํ•œ ํ•จ์ˆ˜๊ฐ€ ๋  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,31 @@ +const { errorGenerator } = require('../erros'); +const { userService } = require('../services'); + +const validateSignUpUserData = async (req, res, next) => { + try { + const { email, password, phoneNumber, profileImageUrl, introduction } = + req.body; + + const REQUIRED_INFO = { email, password, phoneNumber }; + + for (const info in REQUIRED_INFO) { + !REQUIRED_INFO[info] && errorGenerator(400, `MISSING ${info}`); + } + + !userService.validateEmail(email) && errorGenerator(400, 'INVALID EMAIL'); + + const foundUser = await userService.findUser({ email }); + foundUser && errorGenerator(409); + + !userService.validatePw(password) && + errorGenerator(400, 'INVALID PASSWORD'); + + next(); + } catch (err) { + next(err); + } +}; + +module.exports = { + validateSignUpUserData, +};
JavaScript
์˜๊ฒฌ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค :)
@@ -0,0 +1,93 @@ +const context = describe; + +describe('์˜ํ™”๋ชฉ๋ก API ํ…Œ์ŠคํŠธ', () => { + context('์ธ๊ธฐ ์˜ํ™”๋ชฉ๋ก 1ํŽ˜์ด์ง€๋ฅผ ์กฐํšŒํ•˜๋ฉด', () => { + it('20๊ฐœ์˜ ๋ชฉ๋ก์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.', () => { + const baseUrl = 'https://api.themoviedb.org/3/movie/popular'; + const param = new URLSearchParams({ + api_key: Cypress.env('API_KEY'), + language: 'ko-KR', + page: 1, + }); + + cy.request('GET', `${baseUrl}?${param}`).as('popularMovies'); + + cy.get('@popularMovies').its('status').should('eq', 200); + cy.get('@popularMovies').its('body.results').should('have.length', 20); + }); + }); +}); + +describe('์˜ํ™”๋ชฉ๋ก e2e ํ…Œ์ŠคํŠธ', () => { + beforeEach(() => { + const baseUrl = 'https://api.themoviedb.org/3/movie/popular'; + const param = new URLSearchParams({ + api_key: Cypress.env('API_KEY'), + language: 'ko-KR', + page: 1, + }); + + cy.intercept( + { + method: 'GET', + url: `${baseUrl}?${param}`, + }, + { fixture: 'movie-popular.json' } + ).as('popularMovies'); + + cy.visit('http://localhost:8080'); + }); + + context('์˜ํ™” ๋ชฉ๋ก ์กฐํšŒ ์‹œ', () => { + it('800ms ๋™์•ˆ Skeleton UI๊ฐ€ ๋…ธ์ถœ๋˜์—ˆ๋‹ค๊ฐ€ ์‚ฌ๋ผ์ง„๋‹ค.', () => { + cy.wait('@popularMovies'); + cy.get('.skeleton').should('have.length', 60); + cy.wait(800); + cy.get('.skeleton').should('have.length', 0); + }); + }); + + context('ํŽ˜์ด์ง€ ์ง„์ž… ์‹œ ์ธ๊ธฐ์˜ํ™” ๋ชฉ๋ก 1ํŽ˜์ด์ง€๋ฅผ ์กฐํšŒํ•˜๋ฉด', () => { + it('20๊ฐœ์˜ .item-card๊ฐ€ ๋…ธ์ถœ๋œ๋‹ค.', () => { + cy.get('.item-card').should('have.length', 20); + }); + }); + + context('๋”๋ณด๊ธฐ ๋ฒ„ํŠผ์„ ํด๋ฆญํ•˜๋ฉด', () => { + it('40๊ฐœ์˜ item-card ๋…ธ์ถœ๋œ๋‹ค.', () => { + cy.get('.btn').click(); + cy.get('.item-card').should('have.length', 40); + }); + }); +}); + +describe('์งง์€ ์˜ํ™”๋ชฉ๋ก e2e ํ…Œ์ŠคํŠธ', () => { + beforeEach(() => { + const baseUrl = 'https://api.themoviedb.org/3/movie/popular'; + const param = new URLSearchParams({ + api_key: Cypress.env('API_KEY'), + language: 'ko-KR', + page: 1, + }); + + cy.intercept( + { + method: 'GET', + url: `${baseUrl}?${param}`, + }, + { fixture: 'movie-popular-short.json' } + ).as('popularMovies'); + + cy.visit('http://localhost:8080'); + }); + + context('total_pages ๊ฐ€ 1์ธ ์ธ๊ธฐ์˜ํ™” ๋ชฉ๋ก 1ํŽ˜์ด์ง€๋ฅผ ์กฐํšŒํ•˜๋ฉด', () => { + it('18๊ฐœ์˜ .item-card๊ฐ€ ๋…ธ์ถœ๋œ๋‹ค.', () => { + cy.get('.item-card').should('have.length', 18); + }); + + it('๋” ๋ณด๊ธฐ ๋ฒ„ํŠผ์ด ๋…ธ์ถœ๋˜์ง€ ์•Š๋Š”๋‹ค.', () => { + cy.contains('๋”๋ณด๊ธฐ').should('not.exist'); + }); + }); +});
JavaScript
ํ˜น์‹œ 18๊ฐœ์ธ ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,10 @@ +์˜ํ™” ๋ชฉ๋ก API +- ์ธ๊ธฐ ์˜ํ™”๋ชฉ๋ก 1ํŽ˜์ด์ง€๋ฅผ ์กฐํšŒํ•˜๋ฉด 20๊ฐœ์˜ ๋ชฉ๋ก์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค. + +ํŽ˜์ด์ง€ +- ํŽ˜์ด์ง€๋ฅผ ์ฆ๊ฐ€ํ•  ์ˆ˜ ์žˆ๋‹ค. + +UI +- ๋”๋ณด๊ธฐ ๋ฒ„ํŠผ์„ ๋ˆ„๋ฅด๋ฉด ๋‹ค์Œ ์˜ํ™” ๋ชฉ๋ก์„ ๋ถˆ๋Ÿฌ์˜จ๋‹ค. +- ์˜ํ™” ๋ชฉ๋ก์˜ ํŽ˜์ด์ง€ ๋์— ๋„๋‹ฌํ•œ ๊ฒฝ์šฐ์—๋Š” ๋”๋ณด๊ธฐ ๋ฒ„ํŠผ์„ ํ™”๋ฉด์— ์ถœ๋ ฅํ•˜์ง€ ์•Š๋Š”๋‹ค. +- ์˜ํ™” ๋ชฉ๋ก ์•„์ดํ…œ์€ Skeleton UI๋ฅผ ๊ฐ€์ง„๋‹ค.
Unknown
ํŽ˜์ด์ง€๋ฅผ ์ดˆ๊ธฐํ™”ํ•  ์ˆ˜ ์žˆ๋Š” ๊ธฐ๋Šฅ์ด ์žˆ์„๊นŒ์š”? โ†’ ์•„๋ž˜์˜ ์ฝ”๋ฉ˜ํŠธ๋“ค๊ณผ ๋ชฉ์ ์€ ์ด์–ด์ง‘๋‹ˆ๋‹ค!
@@ -0,0 +1,18 @@ +const DEFAULT_SEARCH_PARAMS = { + api_key: process.env.API_KEY, + language: 'ko-KR', +}; +const MOVIE_BASE_URL = 'https://api.themoviedb.org/3/movie'; + +export async function getPopularMovie(page) { + const param = new URLSearchParams({ + ...DEFAULT_SEARCH_PARAMS, + page, + }); + + const response = await fetch(`${MOVIE_BASE_URL}/popular?${param}`); + if (response.ok) { + return response.json(); + } + return { results: [] }; +}
JavaScript
์กฐ๊ธˆ ํŠน์ดํ•œ ๋ฐฉ์‹์ธ ๊ฒƒ ๊ฐ™๊ธดํ•œ๋ฐ์š”! ์ด๋ ‡๊ฒŒ ๊ฐ์ฒด๋กœ ๋ฌถ์–ด์„œ export ํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ์œผ์‹ ๊ฐ€์š”?
@@ -0,0 +1,12 @@ +import PageHandler from './PageHandler'; +import { getPopularMovie } from '../api/movie'; + +export async function getNextPopularMovieList() { + const { page, done } = PageHandler.next(); + const { results } = await getPopularMovie(page); + return { + page, + done, + nextMovieList: results, + }; +}
JavaScript
์•„์ง ๊ตฌํ˜„๋˜์ง€ ์•Š์€ ๊ธฐ๋Šฅ์— ๋Œ€ํ•œ ํ•จ์ˆ˜๋ฅผ ๋จผ์ € ์ƒ์„ฑํ•ด๋‘์‹  ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?!
@@ -0,0 +1,12 @@ +import PageHandler from './PageHandler'; +import { getPopularMovie } from '../api/movie'; + +export async function getNextPopularMovieList() { + const { page, done } = PageHandler.next(); + const { results } = await getPopularMovie(page); + return { + page, + done, + nextMovieList: results, + }; +}
JavaScript
ํ•ธ๋“ค๋Ÿฌ ํ•จ์ˆ˜์—์„œ UI๋ฅผ ์กฐ์ž‘ํ•ด์ฃผ๊ณ  ์žˆ๋„ค์š”! ์ฒ˜์Œ์—” `if (PageHandler.getCurrentPage() !== total_pages)` ์กฐ๊ฑด์ด UI ์™€ ๊ด€๋ จ์ด ์žˆ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ๋Š”๋ฐ ๊ฐ๊ฐ ๋ชฉ์ ์ด ๋‹ค๋ฅด๋„ค์š”. ์—ฌ๊ธฐ์„œ ์ด ํ•ธ๋“ค๋Ÿฌ ํ•จ์ˆ˜์— ๋Œ€ํ•ด์„œ ๋‘ ๊ฐ€์ง€๋ฅผ ๊ณ ๋ฏผํ•ด๋ณด๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”! 1. `onClickMoreButton` ๋ผ๋Š” ์ด๋ฆ„์ด ํ•ด๋‹น ํ•จ์ˆ˜๊ฐ€ ๋ฌด์—‡์„ ํ•˜๋Š”์ง€ ๋“œ๋Ÿฌ๋‚ผ ์ˆ˜ ์žˆ๋Š”๊ฐ€? 2. UI ์กฐ์ž‘๊ณผ ๋„๋ฉ”์ธ ๋กœ์ง์„ ํ•จ๊ป˜ ๋‘๋Š” ๊ฒŒ ๋งž์„๊นŒ?
@@ -0,0 +1,42 @@ +const MOVIE_TOTAL_PAGE_LIMIT = 500; + +const INITIAL_VALUE = { + page: 1, + totalPages: MOVIE_TOTAL_PAGE_LIMIT, +}; + +function PageEventHandler() { + let attr = { ...INITIAL_VALUE }; + + return { + next() { + if (!this.hasNextPage()) { + return { + page: attr.page, + done: true, + }; + } + attr.page = attr.page + 1; + + return { + page: attr.page, + done: !this.hasNextPage(), + }; + }, + getCurrentPage() { + return attr.page; + }, + setTotalPages(totalPages) { + if (totalPages > MOVIE_TOTAL_PAGE_LIMIT) { + return; + } + attr.totalPages = totalPages; + }, + hasNextPage() { + return attr.page < attr.totalPages; + }, + }; +} + +const PageHandler = PageEventHandler(); +export default PageHandler;
JavaScript
๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ๊ธฐ๋Šฅ๋“ค์— ๋Œ€ํ•œ ๊ตฌํ˜„๋“ค์ด ์žˆ๋Š” ๊ฒƒ ๊ฐ™์€๋ฐ์š”! ์ œ๊ฑฐํ•˜์ง€ ์•Š๊ณ  ๋‚จ๊ฒจ ๋†“์œผ์‹  ์ด์œ ๊ฐ€ ์žˆ์œผ์‹ค๊นŒ์š”?
@@ -0,0 +1,12 @@ +import PageHandler from './PageHandler'; +import { getPopularMovie } from '../api/movie'; + +export async function getNextPopularMovieList() { + const { page, done } = PageHandler.next(); + const { results } = await getPopularMovie(page); + return { + page, + done, + nextMovieList: results, + }; +}
JavaScript
์กฐ๊ธˆ ๋” ์˜๋„๋ฅผ ์ „๋‹ฌ๋“œ๋ฆฌ์ž๋ฉด! `onClickMoreButton`์€ ํด๋ฆญ + ํŠน์ •๋ฒ„ํŠผ + ํ•ธ๋“ค๋Ÿฌ๋ผ๋Š” ๊ฒƒ๋งŒ ๋“œ๋Ÿฌ๋‚˜์ง€, ์ด ํ•จ์ˆ˜๊ฐ€ ์‹ค์ œ๋กœ ์–ด๋–ค ํ–‰๋™์„ ํ•˜๋Š” ์ง€๋Š” ์ „ํ˜€ ์•Œ๋ ค ์ฃผ์ง€ ๋ชปํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,93 @@ +const context = describe; + +describe('์˜ํ™”๋ชฉ๋ก API ํ…Œ์ŠคํŠธ', () => { + context('์ธ๊ธฐ ์˜ํ™”๋ชฉ๋ก 1ํŽ˜์ด์ง€๋ฅผ ์กฐํšŒํ•˜๋ฉด', () => { + it('20๊ฐœ์˜ ๋ชฉ๋ก์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.', () => { + const baseUrl = 'https://api.themoviedb.org/3/movie/popular'; + const param = new URLSearchParams({ + api_key: Cypress.env('API_KEY'), + language: 'ko-KR', + page: 1, + }); + + cy.request('GET', `${baseUrl}?${param}`).as('popularMovies'); + + cy.get('@popularMovies').its('status').should('eq', 200); + cy.get('@popularMovies').its('body.results').should('have.length', 20); + }); + }); +}); + +describe('์˜ํ™”๋ชฉ๋ก e2e ํ…Œ์ŠคํŠธ', () => { + beforeEach(() => { + const baseUrl = 'https://api.themoviedb.org/3/movie/popular'; + const param = new URLSearchParams({ + api_key: Cypress.env('API_KEY'), + language: 'ko-KR', + page: 1, + }); + + cy.intercept( + { + method: 'GET', + url: `${baseUrl}?${param}`, + }, + { fixture: 'movie-popular.json' } + ).as('popularMovies'); + + cy.visit('http://localhost:8080'); + }); + + context('์˜ํ™” ๋ชฉ๋ก ์กฐํšŒ ์‹œ', () => { + it('800ms ๋™์•ˆ Skeleton UI๊ฐ€ ๋…ธ์ถœ๋˜์—ˆ๋‹ค๊ฐ€ ์‚ฌ๋ผ์ง„๋‹ค.', () => { + cy.wait('@popularMovies'); + cy.get('.skeleton').should('have.length', 60); + cy.wait(800); + cy.get('.skeleton').should('have.length', 0); + }); + }); + + context('ํŽ˜์ด์ง€ ์ง„์ž… ์‹œ ์ธ๊ธฐ์˜ํ™” ๋ชฉ๋ก 1ํŽ˜์ด์ง€๋ฅผ ์กฐํšŒํ•˜๋ฉด', () => { + it('20๊ฐœ์˜ .item-card๊ฐ€ ๋…ธ์ถœ๋œ๋‹ค.', () => { + cy.get('.item-card').should('have.length', 20); + }); + }); + + context('๋”๋ณด๊ธฐ ๋ฒ„ํŠผ์„ ํด๋ฆญํ•˜๋ฉด', () => { + it('40๊ฐœ์˜ item-card ๋…ธ์ถœ๋œ๋‹ค.', () => { + cy.get('.btn').click(); + cy.get('.item-card').should('have.length', 40); + }); + }); +}); + +describe('์งง์€ ์˜ํ™”๋ชฉ๋ก e2e ํ…Œ์ŠคํŠธ', () => { + beforeEach(() => { + const baseUrl = 'https://api.themoviedb.org/3/movie/popular'; + const param = new URLSearchParams({ + api_key: Cypress.env('API_KEY'), + language: 'ko-KR', + page: 1, + }); + + cy.intercept( + { + method: 'GET', + url: `${baseUrl}?${param}`, + }, + { fixture: 'movie-popular-short.json' } + ).as('popularMovies'); + + cy.visit('http://localhost:8080'); + }); + + context('total_pages ๊ฐ€ 1์ธ ์ธ๊ธฐ์˜ํ™” ๋ชฉ๋ก 1ํŽ˜์ด์ง€๋ฅผ ์กฐํšŒํ•˜๋ฉด', () => { + it('18๊ฐœ์˜ .item-card๊ฐ€ ๋…ธ์ถœ๋œ๋‹ค.', () => { + cy.get('.item-card').should('have.length', 18); + }); + + it('๋” ๋ณด๊ธฐ ๋ฒ„ํŠผ์ด ๋…ธ์ถœ๋˜์ง€ ์•Š๋Š”๋‹ค.', () => { + cy.contains('๋”๋ณด๊ธฐ').should('not.exist'); + }); + }); +});
JavaScript
์ธ๊ธฐ ์˜ํ™”๋ชฉ๋ก ๋ฐ์ดํ„ฐ๊ฐ€ 18๊ฐœ๋ฐ–์— ์—†์„ ๋•Œ 20๊ฐœ๋ฅผ ๊ทธ๋ฆฌ์ง€ ์•Š๊ณ  ๊ฐœ์ˆ˜๋ฅผ ์˜ฌ๋ฐ”๋ฅด๊ฒŒ ํ‘œ์‹œํ•˜๋Š”์ง€ ํ…Œ์ŠคํŠธํ•˜๊ธฐ ์œ„ํ•ด ์ถ”๊ฐ€ํ•ด๋ณด์•˜์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,18 @@ +const DEFAULT_SEARCH_PARAMS = { + api_key: process.env.API_KEY, + language: 'ko-KR', +}; +const MOVIE_BASE_URL = 'https://api.themoviedb.org/3/movie'; + +export async function getPopularMovie(page) { + const param = new URLSearchParams({ + ...DEFAULT_SEARCH_PARAMS, + page, + }); + + const response = await fetch(`${MOVIE_BASE_URL}/popular?${param}`); + if (response.ok) { + return response.json(); + } + return { results: [] }; +}
JavaScript
์—ฌ๋Ÿฌ๊ฐœ์˜ ํ•จ์ˆ˜๋ฅผ ๋ฌถ์–ด์„œ ๋‚ด๋ณด๋‚ด๊ธฐ ์œ„ํ•ด์„œ ์œ„์™€๊ฐ™์€ ์ข…์ข… ์‚ฌ์šฉํ•ด์™”์—ˆ๋Š”๋ฐ์š”! ์—ฌ๊ธฐ์„œ๋Š” ํ•˜๋‚˜์˜ ํ•จ์ˆ˜๋งŒ ๋‚ด๋ณด๋‚ด๊ธฐ์— ์ œ๊ฑฐํ•ด๋ณด์•˜์Šต๋‹ˆ๋‹ค..! ํ˜น์‹œ ์—ฌ๋Ÿฌ๊ฐœ์˜ ํ•จ์ˆ˜๋ฅผ export ํ•ด์•ผํ•  ๋•Œ ์–ด๋–ค ๋ฐฉ์‹์„ ์‚ฌ์šฉํ•˜์‹œ๊ณ  ์„ ํ˜ธํ•˜์‹œ๋Š”์ง€ ์—ฌ์ญˆ์–ด๋ด๋„ ๋ ๊นŒ์š”?
@@ -0,0 +1,12 @@ +import PageHandler from './PageHandler'; +import { getPopularMovie } from '../api/movie'; + +export async function getNextPopularMovieList() { + const { page, done } = PageHandler.next(); + const { results } = await getPopularMovie(page); + return { + page, + done, + nextMovieList: results, + }; +}
JavaScript
figma๋ฅผ ๋ณด๊ณ  modal ์‚ฌ์šฉ๋ถ€๋ถ„์ด ์žˆ์–ด ๋ฏธ๋ฆฌ ์ž‘์„ฑํ•ด๋‘” ๊ฒƒ์ธ๋ฐ ๋ง์”€ํ•ด์ฃผ์‹  ๊ฒƒ์ฒ˜๋Ÿผ ์œ ์ง€๋ณด์ˆ˜์— ์–ด๋ ค์›€์„ ์ค„ ์ˆ˜ ์žˆ๊ฒ ๋„ค์š”..! ๋ช…์‹ฌํ•˜๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค! ํ•ด๋‹น ๋ถ€๋ถ„์€ ์ œ๊ฑฐํ•˜์˜€์Šต๋‹ˆ๋‹ค. ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค! ๐Ÿ™‡
@@ -0,0 +1,12 @@ +import PageHandler from './PageHandler'; +import { getPopularMovie } from '../api/movie'; + +export async function getNextPopularMovieList() { + const { page, done } = PageHandler.next(); + const { results } = await getPopularMovie(page); + return { + page, + done, + nextMovieList: results, + }; +}
JavaScript
`onClickMoreButton`์„ `getNextPopularMovieList`๋กœ ๋ณ€๊ฒฝํ•˜๋ฉด์„œ ์—ญํ• ์„ ๋ถ„๋ฆฌํ•ด๋ณด์•˜์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,42 @@ +const MOVIE_TOTAL_PAGE_LIMIT = 500; + +const INITIAL_VALUE = { + page: 1, + totalPages: MOVIE_TOTAL_PAGE_LIMIT, +}; + +function PageEventHandler() { + let attr = { ...INITIAL_VALUE }; + + return { + next() { + if (!this.hasNextPage()) { + return { + page: attr.page, + done: true, + }; + } + attr.page = attr.page + 1; + + return { + page: attr.page, + done: !this.hasNextPage(), + }; + }, + getCurrentPage() { + return attr.page; + }, + setTotalPages(totalPages) { + if (totalPages > MOVIE_TOTAL_PAGE_LIMIT) { + return; + } + attr.totalPages = totalPages; + }, + hasNextPage() { + return attr.page < attr.totalPages; + }, + }; +} + +const PageHandler = PageEventHandler(); +export default PageHandler;
JavaScript
์ œ๊ฑฐํ•˜์˜€์Šต๋‹ˆ๋‹ค! ์ด์œ ๋Š” ์•ž์„œ ๋ง์”€๋“œ๋ฆฐ ์ด์œ ์™€ ๋™์ผํ•ฉ๋‹ˆ๋‹ค! ๊ผผ๊ผผํžˆ ๋ฆฌ๋ทฐํ•ด์ฃผ์…”์„œ ๊ฐ์‚ฌ๋“œ๋ฆฝ๋‹ˆ๋‹ค ๐Ÿ™‡
@@ -0,0 +1,12 @@ +import PageHandler from './PageHandler'; +import { getPopularMovie } from '../api/movie'; + +export async function getNextPopularMovieList() { + const { page, done } = PageHandler.next(); + const { results } = await getPopularMovie(page); + return { + page, + done, + nextMovieList: results, + }; +}
JavaScript
์Œ... ์ด ๋ถ€๋ถ„์€ ์ œ๊ฐ€ ์˜๋„ํ•œ ๋ฐ”์™€๋Š” ์กฐ๊ธˆ ๋‹ค๋ฅด๊ฒŒ ๋ณ€๊ฒฝ๋œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ์ œ๊ฐ€ ์˜์‚ฌ ์ฝ”๋“œ๋ฅผ ์„ž์–ด๊ฐ€๋ฉฐ ์–ด๋А ์ •๋„ ๋ณ€๊ฒฝํ•ด๋ณผ๊ฒŒ์š”!
@@ -0,0 +1,18 @@ +export class LoadingHandler { + #loading; + constructor(initialValue) { + this.#loading = initialValue; + } + + start() { + this.#loading = true; + } + + end() { + this.#loading = false; + } + + isLoading() { + return this.#loading; + } +}
JavaScript
์‚ฌ์šฉ์ฒ˜๋ฅผ ๋ณด๋ฉด, ๋กœ๋”ฉ ์ƒํƒœ ์ž์ฒด๋ฅผ ํ™œ์šฉํ•˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ํ•œ ๋ฒˆ ๋ฐ–์— ์—†๊ณ , start(), end() ์‹คํ–‰๊ณผ ํ•จ๊ป˜ DOM ์กฐ์ž‘ ๋กœ์ง์ด ํ•จ๊ป˜ ์˜ค๋Š” ๊ฒƒ ๊ฐ™์•„์š”! ์—ฌ๊ธฐ์„œ DOM ์กฐ์ž‘๋„ ๊ฐ™์ด ํ•ด์ฃผ๊ณ , ์ž…๋ ฅ์œผ๋กœ ์กฐ์ž‘ํ•  ์š”์†Œ๋ฅผ ๊ฐ™์ด ๋ฐ›์œผ๋ฉด ๋” ์‘์ง‘์„ฑ์ด ๋†’์€ ์ฝ”๋“œ๊ฐ€ ๋  ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,18 @@ +const DEFAULT_SEARCH_PARAMS = { + api_key: process.env.API_KEY, + language: 'ko-KR', +}; +const MOVIE_BASE_URL = 'https://api.themoviedb.org/3/movie'; + +export async function getPopularMovie(page) { + const param = new URLSearchParams({ + ...DEFAULT_SEARCH_PARAMS, + page, + }); + + const response = await fetch(`${MOVIE_BASE_URL}/popular?${param}`); + if (response.ok) { + return response.json(); + } + return { results: [] }; +}
JavaScript
์—ฌ๋Ÿฌ๊ฐœ์˜ ํ•จ์ˆ˜๋ฅผ ๋ฌถ์–ด์„œ ๋‚ด๋ณด๋‚ด๊ธฐ ์œ„ํ•จ์ด๋‹ค -> ์ปจ๋ฒค์…˜๋งŒ ๋งž๋‹ค๋ฉด ์–ด๋–ค ๋ฐฉํ–ฅ์ด๋˜ ์ƒ๊ด€ ์—†๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค! ๋‹ค๋งŒ, ์ €๋Š” ํ•˜๋‚˜์˜ ํ•จ์ˆ˜์ธ ์ƒํ™ฉ์—์„œ ํ•จ์ˆ˜๊ฐ€ ๋” ์ถ”๊ฐ€๋˜์ง€ ์•Š์•˜๋Š”๋ฐ, ๋” ์ถ”๊ฐ€๋  ์˜ˆ์ •์ธ๋ฐ ์ด๋ ‡๊ฒŒ ํ•˜์‹  ๊ฒƒ ๊ฐ™์•„์„œ ๋‚จ๊ธด ์ฝ”๋ฉ˜ํŠธ์ด๊ธดํ•ฉ๋‹ˆ๋‹ค! (๋ณธ๋ฌธ์˜ ์ฝ”๋ฉ˜ํŠธ์™€ ๋™์ผํ•œ ๋‚ด์šฉ์ž…๋‹ˆ๋‹ค ใ…Žใ…Ž)
@@ -1,7 +1,128 @@ +import { useNavigate } from 'react-router-dom'; +import { useState } from 'react'; import './Login.scss'; function Login() { - return <></>; + // const [idState, setIdState] = useState(''); + // const [passwordValue, setPasswordValue] = useState(''); + // const [disabled, setDisabled] = useState(true); + // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' }); + + const navigate = useNavigate(); + const [loginValues, setLoginValues] = useState({ + id: '', + password: '', + }); + + const handleInputValue = e => { + const { name, value } = e.target; + setLoginValues({ ...loginValues, [name]: value }); + }; + + // const { type, value } = event.target; + + // function handleLogin(event) { + // if (type === 'text') { + // setIdState(value); + // } else if (type === 'password') { + // setPasswordValue(value); + // } + // handleButton(); + // } + + // const checkId = idValue => { + // return idValue.includes('@') ? true : false; + // }; + + // const checkPw = pwValue => { + // return pwValue.length >= 5 ? true : false; + // }; + + // const handleButton = () => { + // const isValidId = checkId(state); + // const isValidPw = checkPw(passwordValue); + + // if (isValidId && isValidPw) { + // buttonColor(true); + // } else { + // buttonColor(false); + // } + // }; + + // const buttonColor = btnValid => { + // setDisabled(!btnValid); + // setStyle({ + // opacity: btnValid ? 1 : 0.5, + // cursor: btnValid ? 'pointer' : 'default', + // }); + // }; + + const goToMain = () => { + fetch('http://10.58.4.238:8000/users/login', { + method: 'POST', + body: JSON.stringify({ + email: loginValues.id, + password: loginValues.password, + // name: '๋ž˜์˜', + // phone_number: '010-1111-111', + }), + }) + .then(response => response.json()) + .then(result => { + // console.log(result); + if (result.token) { + //localStorage.setItem('token', result.token); + alert('ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค!'); + navigate('/main-han'); + } else if (result.message === 'INVALID_USER') { + alert('ID์™€ PW๋ฅผ ํ™•์ธํ•ด์ฃผ์„ธ์š”.'); + } + }); + }; + + const isInputValid = + loginValues.id.includes('@') && + loginValues.id.length >= 6 && + loginValues.password.length >= 6; + // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6); + // console.log(loginValues.password.length >= 6); + // console.log(isInputValid); + + return ( + <div className="login"> + <form className="loginBox"> + <h1>Westagram</h1> + <input + id="id" + name="id" + className="userId" + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + onChange={handleInputValue} + /> + <input + id="password" + name="password" + className="userPassword" + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + onChange={handleInputValue} + /> + <button + type="button" + className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`} + onClick={goToMain} + disabled={!isInputValid} + //style={style} + > + ๋กœ๊ทธ์ธ + </button> + <div className="findPassword"> + <a href="#">๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</a> + </div> + </form> + </div> + ); } export default Login;
JavaScript
```suggestion className={`loginBtn ${ idValue.indexOf('@') > -1 && pwValue.length >= 5 ? 'loginBtnLive' : '' }`} ``` className์˜ ๋™์  ์‚ฌ์šฉ์„ ์ ์šฉํ•˜๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š” ์ธ๋ผ์ธ ์Šคํƒ€์ผ์˜ ์šฐ์„  ์ˆœ์œ„๊ฐ€ ๋†’์•„์„œ, ํŒ€์›์ด class๋ฅผ ์ˆ˜์ •ํ–ˆ์„ ๋•Œ class๊ฐ€ ์ ์šฉ์ด ์•ˆ๋˜๋Š” ๋ฌธ์ œ๊ฐ€ ์žˆ๋‹ค๊ณ  ํ•ด์š”. ์กฐ๊ฑด ์—ฐ์‚ฐ์ž๋ฅผ ํ™œ์šฉํ•ด์„œ className์„ ๋™์ ์œผ๋กœ ์“ธ ์ˆ˜ ์žˆ์Œ className={์›๋ž˜ ํด๋ž˜์Šค +ํ™œ์„ฑํ™” ํด๋ž˜์Šค <-- ์กฐ๊ฑด ์—ฐ์‚ฐ์ž๋กœ ํด๋ž˜์Šค ์ถ”๊ฐ€ ์—ฌ๋ถ€ ๊ฒฐ์ •}
@@ -1,7 +1,128 @@ +import { useNavigate } from 'react-router-dom'; +import { useState } from 'react'; import './Login.scss'; function Login() { - return <></>; + // const [idState, setIdState] = useState(''); + // const [passwordValue, setPasswordValue] = useState(''); + // const [disabled, setDisabled] = useState(true); + // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' }); + + const navigate = useNavigate(); + const [loginValues, setLoginValues] = useState({ + id: '', + password: '', + }); + + const handleInputValue = e => { + const { name, value } = e.target; + setLoginValues({ ...loginValues, [name]: value }); + }; + + // const { type, value } = event.target; + + // function handleLogin(event) { + // if (type === 'text') { + // setIdState(value); + // } else if (type === 'password') { + // setPasswordValue(value); + // } + // handleButton(); + // } + + // const checkId = idValue => { + // return idValue.includes('@') ? true : false; + // }; + + // const checkPw = pwValue => { + // return pwValue.length >= 5 ? true : false; + // }; + + // const handleButton = () => { + // const isValidId = checkId(state); + // const isValidPw = checkPw(passwordValue); + + // if (isValidId && isValidPw) { + // buttonColor(true); + // } else { + // buttonColor(false); + // } + // }; + + // const buttonColor = btnValid => { + // setDisabled(!btnValid); + // setStyle({ + // opacity: btnValid ? 1 : 0.5, + // cursor: btnValid ? 'pointer' : 'default', + // }); + // }; + + const goToMain = () => { + fetch('http://10.58.4.238:8000/users/login', { + method: 'POST', + body: JSON.stringify({ + email: loginValues.id, + password: loginValues.password, + // name: '๋ž˜์˜', + // phone_number: '010-1111-111', + }), + }) + .then(response => response.json()) + .then(result => { + // console.log(result); + if (result.token) { + //localStorage.setItem('token', result.token); + alert('ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค!'); + navigate('/main-han'); + } else if (result.message === 'INVALID_USER') { + alert('ID์™€ PW๋ฅผ ํ™•์ธํ•ด์ฃผ์„ธ์š”.'); + } + }); + }; + + const isInputValid = + loginValues.id.includes('@') && + loginValues.id.length >= 6 && + loginValues.password.length >= 6; + // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6); + // console.log(loginValues.password.length >= 6); + // console.log(isInputValid); + + return ( + <div className="login"> + <form className="loginBox"> + <h1>Westagram</h1> + <input + id="id" + name="id" + className="userId" + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + onChange={handleInputValue} + /> + <input + id="password" + name="password" + className="userPassword" + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + onChange={handleInputValue} + /> + <button + type="button" + className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`} + onClick={goToMain} + disabled={!isInputValid} + //style={style} + > + ๋กœ๊ทธ์ธ + </button> + <div className="findPassword"> + <a href="#">๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</a> + </div> + </form> + </div> + ); } export default Login;
JavaScript
className ๋™์  ์‚ฌ์šฉ์„ ํ•˜๊ฒŒ ๋˜๋ฉด style ์Šคํ…Œ์ดํŠธ๊ฐ€ ํ•„์š”์—†๊ฒŒ ๋œ๋‹ค๊ณ  ํ•ด์š”! disabled๋„ state๋กœ ๋‚จ๊ฒจ๋‘˜์ง€ ๊ณ ๋ฏผํ•ด๋ณด๋ผ๊ณ  ํ•˜์‹ญ๋‹ˆ๋‹ค (from ๋ฉ˜ํ† ๋‹˜..)
@@ -1,7 +1,128 @@ +import { useNavigate } from 'react-router-dom'; +import { useState } from 'react'; import './Login.scss'; function Login() { - return <></>; + // const [idState, setIdState] = useState(''); + // const [passwordValue, setPasswordValue] = useState(''); + // const [disabled, setDisabled] = useState(true); + // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' }); + + const navigate = useNavigate(); + const [loginValues, setLoginValues] = useState({ + id: '', + password: '', + }); + + const handleInputValue = e => { + const { name, value } = e.target; + setLoginValues({ ...loginValues, [name]: value }); + }; + + // const { type, value } = event.target; + + // function handleLogin(event) { + // if (type === 'text') { + // setIdState(value); + // } else if (type === 'password') { + // setPasswordValue(value); + // } + // handleButton(); + // } + + // const checkId = idValue => { + // return idValue.includes('@') ? true : false; + // }; + + // const checkPw = pwValue => { + // return pwValue.length >= 5 ? true : false; + // }; + + // const handleButton = () => { + // const isValidId = checkId(state); + // const isValidPw = checkPw(passwordValue); + + // if (isValidId && isValidPw) { + // buttonColor(true); + // } else { + // buttonColor(false); + // } + // }; + + // const buttonColor = btnValid => { + // setDisabled(!btnValid); + // setStyle({ + // opacity: btnValid ? 1 : 0.5, + // cursor: btnValid ? 'pointer' : 'default', + // }); + // }; + + const goToMain = () => { + fetch('http://10.58.4.238:8000/users/login', { + method: 'POST', + body: JSON.stringify({ + email: loginValues.id, + password: loginValues.password, + // name: '๋ž˜์˜', + // phone_number: '010-1111-111', + }), + }) + .then(response => response.json()) + .then(result => { + // console.log(result); + if (result.token) { + //localStorage.setItem('token', result.token); + alert('ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค!'); + navigate('/main-han'); + } else if (result.message === 'INVALID_USER') { + alert('ID์™€ PW๋ฅผ ํ™•์ธํ•ด์ฃผ์„ธ์š”.'); + } + }); + }; + + const isInputValid = + loginValues.id.includes('@') && + loginValues.id.length >= 6 && + loginValues.password.length >= 6; + // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6); + // console.log(loginValues.password.length >= 6); + // console.log(isInputValid); + + return ( + <div className="login"> + <form className="loginBox"> + <h1>Westagram</h1> + <input + id="id" + name="id" + className="userId" + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + onChange={handleInputValue} + /> + <input + id="password" + name="password" + className="userPassword" + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + onChange={handleInputValue} + /> + <button + type="button" + className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`} + onClick={goToMain} + disabled={!isInputValid} + //style={style} + > + ๋กœ๊ทธ์ธ + </button> + <div className="findPassword"> + <a href="#">๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</a> + </div> + </form> + </div> + ); } export default Login;
JavaScript
className ๋™์  ์‚ฌ์šฉ์„ ํ•˜๊ฒŒ ๋˜๋ฉด ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ ๊ด€๋ จ ํ•จ์ˆ˜๋ฅผ ๋‹ค ์ง€์›Œ๋„ ๋  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -1,7 +1,128 @@ +import { useNavigate } from 'react-router-dom'; +import { useState } from 'react'; import './Login.scss'; function Login() { - return <></>; + // const [idState, setIdState] = useState(''); + // const [passwordValue, setPasswordValue] = useState(''); + // const [disabled, setDisabled] = useState(true); + // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' }); + + const navigate = useNavigate(); + const [loginValues, setLoginValues] = useState({ + id: '', + password: '', + }); + + const handleInputValue = e => { + const { name, value } = e.target; + setLoginValues({ ...loginValues, [name]: value }); + }; + + // const { type, value } = event.target; + + // function handleLogin(event) { + // if (type === 'text') { + // setIdState(value); + // } else if (type === 'password') { + // setPasswordValue(value); + // } + // handleButton(); + // } + + // const checkId = idValue => { + // return idValue.includes('@') ? true : false; + // }; + + // const checkPw = pwValue => { + // return pwValue.length >= 5 ? true : false; + // }; + + // const handleButton = () => { + // const isValidId = checkId(state); + // const isValidPw = checkPw(passwordValue); + + // if (isValidId && isValidPw) { + // buttonColor(true); + // } else { + // buttonColor(false); + // } + // }; + + // const buttonColor = btnValid => { + // setDisabled(!btnValid); + // setStyle({ + // opacity: btnValid ? 1 : 0.5, + // cursor: btnValid ? 'pointer' : 'default', + // }); + // }; + + const goToMain = () => { + fetch('http://10.58.4.238:8000/users/login', { + method: 'POST', + body: JSON.stringify({ + email: loginValues.id, + password: loginValues.password, + // name: '๋ž˜์˜', + // phone_number: '010-1111-111', + }), + }) + .then(response => response.json()) + .then(result => { + // console.log(result); + if (result.token) { + //localStorage.setItem('token', result.token); + alert('ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค!'); + navigate('/main-han'); + } else if (result.message === 'INVALID_USER') { + alert('ID์™€ PW๋ฅผ ํ™•์ธํ•ด์ฃผ์„ธ์š”.'); + } + }); + }; + + const isInputValid = + loginValues.id.includes('@') && + loginValues.id.length >= 6 && + loginValues.password.length >= 6; + // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6); + // console.log(loginValues.password.length >= 6); + // console.log(isInputValid); + + return ( + <div className="login"> + <form className="loginBox"> + <h1>Westagram</h1> + <input + id="id" + name="id" + className="userId" + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + onChange={handleInputValue} + /> + <input + id="password" + name="password" + className="userPassword" + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + onChange={handleInputValue} + /> + <button + type="button" + className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`} + onClick={goToMain} + disabled={!isInputValid} + //style={style} + > + ๋กœ๊ทธ์ธ + </button> + <div className="findPassword"> + <a href="#">๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</a> + </div> + </form> + </div> + ); } export default Login;
JavaScript
```suggestion import { useState } from 'react'; import { useNavigate } from 'react-router-dom'; import './Login.scss'; ``` scss๋ฅผ ๋ฐ‘์œผ๋กœ ๋‚ด๋ ค์ฃผ๋ฉด ์ข‹์„๊ฑฐ๊ฐ™๋„ค์š”
@@ -1,7 +1,128 @@ +import { useNavigate } from 'react-router-dom'; +import { useState } from 'react'; import './Login.scss'; function Login() { - return <></>; + // const [idState, setIdState] = useState(''); + // const [passwordValue, setPasswordValue] = useState(''); + // const [disabled, setDisabled] = useState(true); + // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' }); + + const navigate = useNavigate(); + const [loginValues, setLoginValues] = useState({ + id: '', + password: '', + }); + + const handleInputValue = e => { + const { name, value } = e.target; + setLoginValues({ ...loginValues, [name]: value }); + }; + + // const { type, value } = event.target; + + // function handleLogin(event) { + // if (type === 'text') { + // setIdState(value); + // } else if (type === 'password') { + // setPasswordValue(value); + // } + // handleButton(); + // } + + // const checkId = idValue => { + // return idValue.includes('@') ? true : false; + // }; + + // const checkPw = pwValue => { + // return pwValue.length >= 5 ? true : false; + // }; + + // const handleButton = () => { + // const isValidId = checkId(state); + // const isValidPw = checkPw(passwordValue); + + // if (isValidId && isValidPw) { + // buttonColor(true); + // } else { + // buttonColor(false); + // } + // }; + + // const buttonColor = btnValid => { + // setDisabled(!btnValid); + // setStyle({ + // opacity: btnValid ? 1 : 0.5, + // cursor: btnValid ? 'pointer' : 'default', + // }); + // }; + + const goToMain = () => { + fetch('http://10.58.4.238:8000/users/login', { + method: 'POST', + body: JSON.stringify({ + email: loginValues.id, + password: loginValues.password, + // name: '๋ž˜์˜', + // phone_number: '010-1111-111', + }), + }) + .then(response => response.json()) + .then(result => { + // console.log(result); + if (result.token) { + //localStorage.setItem('token', result.token); + alert('ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค!'); + navigate('/main-han'); + } else if (result.message === 'INVALID_USER') { + alert('ID์™€ PW๋ฅผ ํ™•์ธํ•ด์ฃผ์„ธ์š”.'); + } + }); + }; + + const isInputValid = + loginValues.id.includes('@') && + loginValues.id.length >= 6 && + loginValues.password.length >= 6; + // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6); + // console.log(loginValues.password.length >= 6); + // console.log(isInputValid); + + return ( + <div className="login"> + <form className="loginBox"> + <h1>Westagram</h1> + <input + id="id" + name="id" + className="userId" + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + onChange={handleInputValue} + /> + <input + id="password" + name="password" + className="userPassword" + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + onChange={handleInputValue} + /> + <button + type="button" + className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`} + onClick={goToMain} + disabled={!isInputValid} + //style={style} + > + ๋กœ๊ทธ์ธ + </button> + <div className="findPassword"> + <a href="#">๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</a> + </div> + </form> + </div> + ); } export default Login;
JavaScript
ํ›… ๋ฐ‘์œผ๋กœ ๋ถ™์—ฌ์ฃผ๋Š”๊ฒŒ ์ข‹์ง€ ์•Š์„๊นŒ์š”?
@@ -1,8 +1,43 @@ -import './Main.scss'; +import { useState, useEffect } from 'react'; +import Nav from '../../../components/Nav/Nav'; +import Feed from './Feed'; +import MainRight from './MainRight'; import '../../../styles/variables.scss'; +import './Main.scss'; function Main() { - return <></>; + const [articles, setArticles] = useState([]); + + useEffect(() => { + fetch('http://localhost:3000/data/younghyunHan/feedData.json') + .then(res => res.json()) + .then(data => { + setArticles(data); + }); + }, []); + + return ( + <div className="main"> + <Nav /> + <main> + <div className="feeds"> + {articles.map((content, index) => { + return ( + <div key={index}> + <Feed + userName={content.userName} + feedImg={content.feedImg} + userMan={content.userMan} + profileLogo={content.profileLogo} + /> + </div> + ); + })} + </div> + <MainRight /> + </main> + </div> + ); } export default Main;
JavaScript
์ปดํฌ๋„ŒํŠธ ์ด๋ฆ„์„ Feed ๋กœ ๋ฐ”๊ฟ”๋ณด๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”!! ์ด๋ฆ„์— ์˜๋ฏธ๋ฅผ ๋” ๋‹ด์•„์ฃผ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค
@@ -1,8 +1,43 @@ -import './Main.scss'; +import { useState, useEffect } from 'react'; +import Nav from '../../../components/Nav/Nav'; +import Feed from './Feed'; +import MainRight from './MainRight'; import '../../../styles/variables.scss'; +import './Main.scss'; function Main() { - return <></>; + const [articles, setArticles] = useState([]); + + useEffect(() => { + fetch('http://localhost:3000/data/younghyunHan/feedData.json') + .then(res => res.json()) + .then(data => { + setArticles(data); + }); + }, []); + + return ( + <div className="main"> + <Nav /> + <main> + <div className="feeds"> + {articles.map((content, index) => { + return ( + <div key={index}> + <Feed + userName={content.userName} + feedImg={content.feedImg} + userMan={content.userMan} + profileLogo={content.profileLogo} + /> + </div> + ); + })} + </div> + <MainRight /> + </main> + </div> + ); } export default Main;
JavaScript
mainRight๋„ ์ปดํฌ๋„ŒํŠธ๋กœ ๋งŒ๋“ค์–ด์ฃผ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š” ์ด๋ ‡๊ฒŒ ํ•ด์ฃผ๋ฉด main.js ๋‚ด์šฉ, scss ๋‚ด์šฉ๋„ ๋” ๊ฐ„๋‹จํ•ด์งˆ ๊ฒƒ ๊ฐ™์Œ! ```suggestion <MainRight /> ```
@@ -1,8 +1,43 @@ -import './Main.scss'; +import { useState, useEffect } from 'react'; +import Nav from '../../../components/Nav/Nav'; +import Feed from './Feed'; +import MainRight from './MainRight'; import '../../../styles/variables.scss'; +import './Main.scss'; function Main() { - return <></>; + const [articles, setArticles] = useState([]); + + useEffect(() => { + fetch('http://localhost:3000/data/younghyunHan/feedData.json') + .then(res => res.json()) + .then(data => { + setArticles(data); + }); + }, []); + + return ( + <div className="main"> + <Nav /> + <main> + <div className="feeds"> + {articles.map((content, index) => { + return ( + <div key={index}> + <Feed + userName={content.userName} + feedImg={content.feedImg} + userMan={content.userMan} + profileLogo={content.profileLogo} + /> + </div> + ); + })} + </div> + <MainRight /> + </main> + </div> + ); } export default Main;
JavaScript
```suggestion <Footer /> ``` ์ปดํฌ๋„ŒํŠธ๋กœ ๋ถ„๋ฆฌํ•ด์ฃผ๊ณ , footer ์‹œ๋ฉ˜ํ‹ฑ ํƒœ๊ทธ๋ฅผ ์‚ฌ์šฉํ•ด๋ณด๋ฉด ์ข‹์„ ๋“ฏ!
@@ -1,8 +1,43 @@ -import './Main.scss'; +import { useState, useEffect } from 'react'; +import Nav from '../../../components/Nav/Nav'; +import Feed from './Feed'; +import MainRight from './MainRight'; import '../../../styles/variables.scss'; +import './Main.scss'; function Main() { - return <></>; + const [articles, setArticles] = useState([]); + + useEffect(() => { + fetch('http://localhost:3000/data/younghyunHan/feedData.json') + .then(res => res.json()) + .then(data => { + setArticles(data); + }); + }, []); + + return ( + <div className="main"> + <Nav /> + <main> + <div className="feeds"> + {articles.map((content, index) => { + return ( + <div key={index}> + <Feed + userName={content.userName} + feedImg={content.feedImg} + userMan={content.userMan} + profileLogo={content.profileLogo} + /> + </div> + ); + })} + </div> + <MainRight /> + </main> + </div> + ); } export default Main;
JavaScript
๊ฐ ๋ฉ”๋‰ด๋ฅผ JS ํŒŒ์ผ์— ์ €์žฅํ•˜๊ณ , map ๋ฉ”์†Œ๋“œ๋กœ ์ถœ๋ ฅํ•ด์ฃผ๋Š” ๋ฐฉ์‹์œผ๋กœ ์ˆ˜์ •ํ•ด๋ณด๋ฉด ์ข‹์„ ๋“ฏํ•ด์šฉ
@@ -0,0 +1,16 @@ +.main { + background-color: #fafafa; + + main { + display: flex; + justify-content: center; + align-items: flex-start; + margin: 0px 8px 8px 8px; + + .feeds { + width: 750px; + padding-top: 80px; + padding-bottom: 30px; + } + } +}
Unknown
์ด๋Ÿฐ ์„ ํƒ์ž ํ™œ์šฉ์œผ๋กœ ์Šคํฌ๋กค ๊ฐ์ถ”์‹  ๋ถ€๋ถ„ ์ข‹๋„ค์š”..
@@ -1,8 +1,43 @@ -import './Main.scss'; +import { useState, useEffect } from 'react'; +import Nav from '../../../components/Nav/Nav'; +import Feed from './Feed'; +import MainRight from './MainRight'; import '../../../styles/variables.scss'; +import './Main.scss'; function Main() { - return <></>; + const [articles, setArticles] = useState([]); + + useEffect(() => { + fetch('http://localhost:3000/data/younghyunHan/feedData.json') + .then(res => res.json()) + .then(data => { + setArticles(data); + }); + }, []); + + return ( + <div className="main"> + <Nav /> + <main> + <div className="feeds"> + {articles.map((content, index) => { + return ( + <div key={index}> + <Feed + userName={content.userName} + feedImg={content.feedImg} + userMan={content.userMan} + profileLogo={content.profileLogo} + /> + </div> + ); + })} + </div> + <MainRight /> + </main> + </div> + ); } export default Main;
JavaScript
feedcontainer ์•ˆ feed
@@ -1,7 +1,49 @@ import './Nav.scss'; +import '../../styles/variables.scss'; +import { Link } from 'react-router-dom'; function Nav() { - return <></>; + return ( + <div className="nav"> + <nav className="navbar"> + <div className="navbarLeft1"> + <div className="navbarLeft1Inner"> + <Link to="/" className="navbarItem logoImg"> + <img alt="logoIcon" className="navIcon" src="/images/logo.png" /> + </Link> + <Link to="/" className="navbarItem logoFont"> + Westagram + </Link> + </div> + </div> + <div className="navbarLeft2"> + <div className="searchWrapper navbarItem"> + <img alt="searchIcon" src="/images/search.png" /> + <input placeholder="๊ฒ€์ƒ‰" /> + </div> + </div> + <div className="navbarRight"> + <Link to="/" className="navbarItem"> + <img + alt="exploreIcon" + className="navIcon" + src="/images/explore.png" + /> + </Link> + <Link to="/" className="navbarItem"> + <img alt="heartIcon" className="navIcon" src="/images/heart.png" /> + </Link> + <Link to="/" className="navbarItem"> + <img + alt="profileIcon" + className="navIcon" + src="/images/profile.png" + /> + </Link> + </div> + </nav> + </div> + ); } export default Nav;
JavaScript
๊ณตํ†ต ํŒŒ์ผ
@@ -1,7 +1,128 @@ +import { useNavigate } from 'react-router-dom'; +import { useState } from 'react'; import './Login.scss'; function Login() { - return <></>; + // const [idState, setIdState] = useState(''); + // const [passwordValue, setPasswordValue] = useState(''); + // const [disabled, setDisabled] = useState(true); + // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' }); + + const navigate = useNavigate(); + const [loginValues, setLoginValues] = useState({ + id: '', + password: '', + }); + + const handleInputValue = e => { + const { name, value } = e.target; + setLoginValues({ ...loginValues, [name]: value }); + }; + + // const { type, value } = event.target; + + // function handleLogin(event) { + // if (type === 'text') { + // setIdState(value); + // } else if (type === 'password') { + // setPasswordValue(value); + // } + // handleButton(); + // } + + // const checkId = idValue => { + // return idValue.includes('@') ? true : false; + // }; + + // const checkPw = pwValue => { + // return pwValue.length >= 5 ? true : false; + // }; + + // const handleButton = () => { + // const isValidId = checkId(state); + // const isValidPw = checkPw(passwordValue); + + // if (isValidId && isValidPw) { + // buttonColor(true); + // } else { + // buttonColor(false); + // } + // }; + + // const buttonColor = btnValid => { + // setDisabled(!btnValid); + // setStyle({ + // opacity: btnValid ? 1 : 0.5, + // cursor: btnValid ? 'pointer' : 'default', + // }); + // }; + + const goToMain = () => { + fetch('http://10.58.4.238:8000/users/login', { + method: 'POST', + body: JSON.stringify({ + email: loginValues.id, + password: loginValues.password, + // name: '๋ž˜์˜', + // phone_number: '010-1111-111', + }), + }) + .then(response => response.json()) + .then(result => { + // console.log(result); + if (result.token) { + //localStorage.setItem('token', result.token); + alert('ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค!'); + navigate('/main-han'); + } else if (result.message === 'INVALID_USER') { + alert('ID์™€ PW๋ฅผ ํ™•์ธํ•ด์ฃผ์„ธ์š”.'); + } + }); + }; + + const isInputValid = + loginValues.id.includes('@') && + loginValues.id.length >= 6 && + loginValues.password.length >= 6; + // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6); + // console.log(loginValues.password.length >= 6); + // console.log(isInputValid); + + return ( + <div className="login"> + <form className="loginBox"> + <h1>Westagram</h1> + <input + id="id" + name="id" + className="userId" + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + onChange={handleInputValue} + /> + <input + id="password" + name="password" + className="userPassword" + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + onChange={handleInputValue} + /> + <button + type="button" + className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`} + onClick={goToMain} + disabled={!isInputValid} + //style={style} + > + ๋กœ๊ทธ์ธ + </button> + <div className="findPassword"> + <a href="#">๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</a> + </div> + </form> + </div> + ); } export default Login;
JavaScript
state๋ผ๋Š” ๋ช…์นญ์ด ๋ฌด์Šจ ๋ฐ์ดํ„ฐ๋ฅผ ๊ด€๋ฆฌํ•˜๋Š”์ง€ ์•Œ ์ˆ˜ ์—†์Œ. ๋ช…ํ™•ํ•œ ๋ช…์นญ์œผ๋กœ ์ˆ˜์ •
@@ -1,7 +1,128 @@ +import { useNavigate } from 'react-router-dom'; +import { useState } from 'react'; import './Login.scss'; function Login() { - return <></>; + // const [idState, setIdState] = useState(''); + // const [passwordValue, setPasswordValue] = useState(''); + // const [disabled, setDisabled] = useState(true); + // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' }); + + const navigate = useNavigate(); + const [loginValues, setLoginValues] = useState({ + id: '', + password: '', + }); + + const handleInputValue = e => { + const { name, value } = e.target; + setLoginValues({ ...loginValues, [name]: value }); + }; + + // const { type, value } = event.target; + + // function handleLogin(event) { + // if (type === 'text') { + // setIdState(value); + // } else if (type === 'password') { + // setPasswordValue(value); + // } + // handleButton(); + // } + + // const checkId = idValue => { + // return idValue.includes('@') ? true : false; + // }; + + // const checkPw = pwValue => { + // return pwValue.length >= 5 ? true : false; + // }; + + // const handleButton = () => { + // const isValidId = checkId(state); + // const isValidPw = checkPw(passwordValue); + + // if (isValidId && isValidPw) { + // buttonColor(true); + // } else { + // buttonColor(false); + // } + // }; + + // const buttonColor = btnValid => { + // setDisabled(!btnValid); + // setStyle({ + // opacity: btnValid ? 1 : 0.5, + // cursor: btnValid ? 'pointer' : 'default', + // }); + // }; + + const goToMain = () => { + fetch('http://10.58.4.238:8000/users/login', { + method: 'POST', + body: JSON.stringify({ + email: loginValues.id, + password: loginValues.password, + // name: '๋ž˜์˜', + // phone_number: '010-1111-111', + }), + }) + .then(response => response.json()) + .then(result => { + // console.log(result); + if (result.token) { + //localStorage.setItem('token', result.token); + alert('ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค!'); + navigate('/main-han'); + } else if (result.message === 'INVALID_USER') { + alert('ID์™€ PW๋ฅผ ํ™•์ธํ•ด์ฃผ์„ธ์š”.'); + } + }); + }; + + const isInputValid = + loginValues.id.includes('@') && + loginValues.id.length >= 6 && + loginValues.password.length >= 6; + // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6); + // console.log(loginValues.password.length >= 6); + // console.log(isInputValid); + + return ( + <div className="login"> + <form className="loginBox"> + <h1>Westagram</h1> + <input + id="id" + name="id" + className="userId" + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + onChange={handleInputValue} + /> + <input + id="password" + name="password" + className="userPassword" + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + onChange={handleInputValue} + /> + <button + type="button" + className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`} + onClick={goToMain} + disabled={!isInputValid} + //style={style} + > + ๋กœ๊ทธ์ธ + </button> + <div className="findPassword"> + <a href="#">๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</a> + </div> + </form> + </div> + ); } export default Login;
JavaScript
disabled, style ๋“ฑ์€ state๋กœ ๋งŒ๋“ค ํ•„์š” ์—†์Œ. [๋ฆฌ์•กํŠธ๋กœ ์‚ฌ๊ณ ํ•˜๊ธฐ](https://ko.reactjs.org/docs/thinking-in-react.html) ์ฐธ๊ณ  1. ๋ถ€๋ชจ๋กœ๋ถ€ํ„ฐ props๋ฅผ ํ†ตํ•ด ์ „๋‹ฌ๋ฉ๋‹ˆ๊นŒ? ๊ทธ๋Ÿฌ๋ฉด ํ™•์‹คํžˆ state๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค. 2. ์‹œ๊ฐ„์ด ์ง€๋‚˜๋„ ๋ณ€ํ•˜์ง€ ์•Š๋‚˜์š”? ๊ทธ๋Ÿฌ๋ฉด ํ™•์‹คํžˆ state๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค. 3. ์ปดํฌ๋„ŒํŠธ ์•ˆ์˜ ๋‹ค๋ฅธ state๋‚˜ props๋ฅผ ๊ฐ€์ง€๊ณ  ๊ณ„์‚ฐ ๊ฐ€๋Šฅํ•œ๊ฐ€์š”? ๊ทธ๋ ‡๋‹ค๋ฉด state๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค.
@@ -1,7 +1,128 @@ +import { useNavigate } from 'react-router-dom'; +import { useState } from 'react'; import './Login.scss'; function Login() { - return <></>; + // const [idState, setIdState] = useState(''); + // const [passwordValue, setPasswordValue] = useState(''); + // const [disabled, setDisabled] = useState(true); + // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' }); + + const navigate = useNavigate(); + const [loginValues, setLoginValues] = useState({ + id: '', + password: '', + }); + + const handleInputValue = e => { + const { name, value } = e.target; + setLoginValues({ ...loginValues, [name]: value }); + }; + + // const { type, value } = event.target; + + // function handleLogin(event) { + // if (type === 'text') { + // setIdState(value); + // } else if (type === 'password') { + // setPasswordValue(value); + // } + // handleButton(); + // } + + // const checkId = idValue => { + // return idValue.includes('@') ? true : false; + // }; + + // const checkPw = pwValue => { + // return pwValue.length >= 5 ? true : false; + // }; + + // const handleButton = () => { + // const isValidId = checkId(state); + // const isValidPw = checkPw(passwordValue); + + // if (isValidId && isValidPw) { + // buttonColor(true); + // } else { + // buttonColor(false); + // } + // }; + + // const buttonColor = btnValid => { + // setDisabled(!btnValid); + // setStyle({ + // opacity: btnValid ? 1 : 0.5, + // cursor: btnValid ? 'pointer' : 'default', + // }); + // }; + + const goToMain = () => { + fetch('http://10.58.4.238:8000/users/login', { + method: 'POST', + body: JSON.stringify({ + email: loginValues.id, + password: loginValues.password, + // name: '๋ž˜์˜', + // phone_number: '010-1111-111', + }), + }) + .then(response => response.json()) + .then(result => { + // console.log(result); + if (result.token) { + //localStorage.setItem('token', result.token); + alert('ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค!'); + navigate('/main-han'); + } else if (result.message === 'INVALID_USER') { + alert('ID์™€ PW๋ฅผ ํ™•์ธํ•ด์ฃผ์„ธ์š”.'); + } + }); + }; + + const isInputValid = + loginValues.id.includes('@') && + loginValues.id.length >= 6 && + loginValues.password.length >= 6; + // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6); + // console.log(loginValues.password.length >= 6); + // console.log(isInputValid); + + return ( + <div className="login"> + <form className="loginBox"> + <h1>Westagram</h1> + <input + id="id" + name="id" + className="userId" + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + onChange={handleInputValue} + /> + <input + id="password" + name="password" + className="userPassword" + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + onChange={handleInputValue} + /> + <button + type="button" + className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`} + onClick={goToMain} + disabled={!isInputValid} + //style={style} + > + ๋กœ๊ทธ์ธ + </button> + <div className="findPassword"> + <a href="#">๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</a> + </div> + </form> + </div> + ); } export default Login;
JavaScript
- ๊ธฐ๋Šฅ์„ ํ•จ์ˆ˜๋กœ ๋ถ„๋ฆฌํ•˜๋Š” ๋ถ€๋ถ„์€ ์ข‹์Œ - ์‚ผํ•ญ์—ฐ์‚ฐ์ž๋กœ ์‚ฌ์šฉํ•  ํ•„์š” ์—†์ด, ์กฐ๊ฑด ์ž์ฒด๋กœ boolean์ด ๋  ์ˆ˜ ์žˆ์Œ ```suggestion const checkId = idValue => { return idValue.includes('@'); }; const checkPw = pwValue => { return pwValue.length >= 5; }; ``` - ์ถ”๊ฐ€์ ์œผ๋กœ, ```js const isInputValid = idValue.includes('@') && pwValue.length >= 5 ``` ์ด๋Ÿฐ ์‹์œผ๋กœ ํ•œ๊บผ๋ฒˆ์— ๋ณ€์ˆ˜๋กœ ๋งŒ๋“ค์–ด ์ฒ˜๋ฆฌํ•  ์ˆ˜๋„ ์žˆ์Œ
@@ -1,7 +1,128 @@ +import { useNavigate } from 'react-router-dom'; +import { useState } from 'react'; import './Login.scss'; function Login() { - return <></>; + // const [idState, setIdState] = useState(''); + // const [passwordValue, setPasswordValue] = useState(''); + // const [disabled, setDisabled] = useState(true); + // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' }); + + const navigate = useNavigate(); + const [loginValues, setLoginValues] = useState({ + id: '', + password: '', + }); + + const handleInputValue = e => { + const { name, value } = e.target; + setLoginValues({ ...loginValues, [name]: value }); + }; + + // const { type, value } = event.target; + + // function handleLogin(event) { + // if (type === 'text') { + // setIdState(value); + // } else if (type === 'password') { + // setPasswordValue(value); + // } + // handleButton(); + // } + + // const checkId = idValue => { + // return idValue.includes('@') ? true : false; + // }; + + // const checkPw = pwValue => { + // return pwValue.length >= 5 ? true : false; + // }; + + // const handleButton = () => { + // const isValidId = checkId(state); + // const isValidPw = checkPw(passwordValue); + + // if (isValidId && isValidPw) { + // buttonColor(true); + // } else { + // buttonColor(false); + // } + // }; + + // const buttonColor = btnValid => { + // setDisabled(!btnValid); + // setStyle({ + // opacity: btnValid ? 1 : 0.5, + // cursor: btnValid ? 'pointer' : 'default', + // }); + // }; + + const goToMain = () => { + fetch('http://10.58.4.238:8000/users/login', { + method: 'POST', + body: JSON.stringify({ + email: loginValues.id, + password: loginValues.password, + // name: '๋ž˜์˜', + // phone_number: '010-1111-111', + }), + }) + .then(response => response.json()) + .then(result => { + // console.log(result); + if (result.token) { + //localStorage.setItem('token', result.token); + alert('ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค!'); + navigate('/main-han'); + } else if (result.message === 'INVALID_USER') { + alert('ID์™€ PW๋ฅผ ํ™•์ธํ•ด์ฃผ์„ธ์š”.'); + } + }); + }; + + const isInputValid = + loginValues.id.includes('@') && + loginValues.id.length >= 6 && + loginValues.password.length >= 6; + // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6); + // console.log(loginValues.password.length >= 6); + // console.log(isInputValid); + + return ( + <div className="login"> + <form className="loginBox"> + <h1>Westagram</h1> + <input + id="id" + name="id" + className="userId" + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + onChange={handleInputValue} + /> + <input + id="password" + name="password" + className="userPassword" + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + onChange={handleInputValue} + /> + <button + type="button" + className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`} + onClick={goToMain} + disabled={!isInputValid} + //style={style} + > + ๋กœ๊ทธ์ธ + </button> + <div className="findPassword"> + <a href="#">๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</a> + </div> + </form> + </div> + ); } export default Login;
JavaScript
๋ช…์นญ๋งŒ ๋ดค์„ ๋•Œ๋Š” id ๋ถ€๋ถ„๋งŒ ๊ด€๋ฆฌํ•˜๋Š” ํ•จ์ˆ˜์ธ ๊ฒƒ ๊ฐ™์€๋ฐ, ๋™์ž‘์„ ๋ณด๋ฉด ์•„๋‹˜. ์ˆ˜์ •
@@ -1,7 +1,128 @@ +import { useNavigate } from 'react-router-dom'; +import { useState } from 'react'; import './Login.scss'; function Login() { - return <></>; + // const [idState, setIdState] = useState(''); + // const [passwordValue, setPasswordValue] = useState(''); + // const [disabled, setDisabled] = useState(true); + // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' }); + + const navigate = useNavigate(); + const [loginValues, setLoginValues] = useState({ + id: '', + password: '', + }); + + const handleInputValue = e => { + const { name, value } = e.target; + setLoginValues({ ...loginValues, [name]: value }); + }; + + // const { type, value } = event.target; + + // function handleLogin(event) { + // if (type === 'text') { + // setIdState(value); + // } else if (type === 'password') { + // setPasswordValue(value); + // } + // handleButton(); + // } + + // const checkId = idValue => { + // return idValue.includes('@') ? true : false; + // }; + + // const checkPw = pwValue => { + // return pwValue.length >= 5 ? true : false; + // }; + + // const handleButton = () => { + // const isValidId = checkId(state); + // const isValidPw = checkPw(passwordValue); + + // if (isValidId && isValidPw) { + // buttonColor(true); + // } else { + // buttonColor(false); + // } + // }; + + // const buttonColor = btnValid => { + // setDisabled(!btnValid); + // setStyle({ + // opacity: btnValid ? 1 : 0.5, + // cursor: btnValid ? 'pointer' : 'default', + // }); + // }; + + const goToMain = () => { + fetch('http://10.58.4.238:8000/users/login', { + method: 'POST', + body: JSON.stringify({ + email: loginValues.id, + password: loginValues.password, + // name: '๋ž˜์˜', + // phone_number: '010-1111-111', + }), + }) + .then(response => response.json()) + .then(result => { + // console.log(result); + if (result.token) { + //localStorage.setItem('token', result.token); + alert('ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค!'); + navigate('/main-han'); + } else if (result.message === 'INVALID_USER') { + alert('ID์™€ PW๋ฅผ ํ™•์ธํ•ด์ฃผ์„ธ์š”.'); + } + }); + }; + + const isInputValid = + loginValues.id.includes('@') && + loginValues.id.length >= 6 && + loginValues.password.length >= 6; + // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6); + // console.log(loginValues.password.length >= 6); + // console.log(isInputValid); + + return ( + <div className="login"> + <form className="loginBox"> + <h1>Westagram</h1> + <input + id="id" + name="id" + className="userId" + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + onChange={handleInputValue} + /> + <input + id="password" + name="password" + className="userPassword" + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + onChange={handleInputValue} + /> + <button + type="button" + className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`} + onClick={goToMain} + disabled={!isInputValid} + //style={style} + > + ๋กœ๊ทธ์ธ + </button> + <div className="findPassword"> + <a href="#">๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</a> + </div> + </form> + </div> + ); } export default Login;
JavaScript
๊ตฌ์กฐ๋ถ„ํ•ดํ• ๋‹น! ```suggestion const { type, value } = event.target; if (type === 'text') { setState(value); } else if (type === 'password') { setPasswordValue(value); } ```
@@ -1,7 +1,128 @@ +import { useNavigate } from 'react-router-dom'; +import { useState } from 'react'; import './Login.scss'; function Login() { - return <></>; + // const [idState, setIdState] = useState(''); + // const [passwordValue, setPasswordValue] = useState(''); + // const [disabled, setDisabled] = useState(true); + // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' }); + + const navigate = useNavigate(); + const [loginValues, setLoginValues] = useState({ + id: '', + password: '', + }); + + const handleInputValue = e => { + const { name, value } = e.target; + setLoginValues({ ...loginValues, [name]: value }); + }; + + // const { type, value } = event.target; + + // function handleLogin(event) { + // if (type === 'text') { + // setIdState(value); + // } else if (type === 'password') { + // setPasswordValue(value); + // } + // handleButton(); + // } + + // const checkId = idValue => { + // return idValue.includes('@') ? true : false; + // }; + + // const checkPw = pwValue => { + // return pwValue.length >= 5 ? true : false; + // }; + + // const handleButton = () => { + // const isValidId = checkId(state); + // const isValidPw = checkPw(passwordValue); + + // if (isValidId && isValidPw) { + // buttonColor(true); + // } else { + // buttonColor(false); + // } + // }; + + // const buttonColor = btnValid => { + // setDisabled(!btnValid); + // setStyle({ + // opacity: btnValid ? 1 : 0.5, + // cursor: btnValid ? 'pointer' : 'default', + // }); + // }; + + const goToMain = () => { + fetch('http://10.58.4.238:8000/users/login', { + method: 'POST', + body: JSON.stringify({ + email: loginValues.id, + password: loginValues.password, + // name: '๋ž˜์˜', + // phone_number: '010-1111-111', + }), + }) + .then(response => response.json()) + .then(result => { + // console.log(result); + if (result.token) { + //localStorage.setItem('token', result.token); + alert('ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค!'); + navigate('/main-han'); + } else if (result.message === 'INVALID_USER') { + alert('ID์™€ PW๋ฅผ ํ™•์ธํ•ด์ฃผ์„ธ์š”.'); + } + }); + }; + + const isInputValid = + loginValues.id.includes('@') && + loginValues.id.length >= 6 && + loginValues.password.length >= 6; + // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6); + // console.log(loginValues.password.length >= 6); + // console.log(isInputValid); + + return ( + <div className="login"> + <form className="loginBox"> + <h1>Westagram</h1> + <input + id="id" + name="id" + className="userId" + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + onChange={handleInputValue} + /> + <input + id="password" + name="password" + className="userPassword" + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + onChange={handleInputValue} + /> + <button + type="button" + className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`} + onClick={goToMain} + disabled={!isInputValid} + //style={style} + > + ๋กœ๊ทธ์ธ + </button> + <div className="findPassword"> + <a href="#">๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</a> + </div> + </form> + </div> + ); } export default Login;
JavaScript
JS๋กœ ๊ตฌํ˜„ํ•˜๋˜ ๋ฐฉ์‹ ๊ทธ๋Œ€๋กœ ํ•˜์…จ๋Š”๋ฐ, ๊ธฐ์กด state๋กœ ๊ณ„์‚ฐ์ด ๊ฐ€๋Šฅํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๋ถˆํ•„์š”ํ•œ state
@@ -1,7 +1,128 @@ +import { useNavigate } from 'react-router-dom'; +import { useState } from 'react'; import './Login.scss'; function Login() { - return <></>; + // const [idState, setIdState] = useState(''); + // const [passwordValue, setPasswordValue] = useState(''); + // const [disabled, setDisabled] = useState(true); + // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' }); + + const navigate = useNavigate(); + const [loginValues, setLoginValues] = useState({ + id: '', + password: '', + }); + + const handleInputValue = e => { + const { name, value } = e.target; + setLoginValues({ ...loginValues, [name]: value }); + }; + + // const { type, value } = event.target; + + // function handleLogin(event) { + // if (type === 'text') { + // setIdState(value); + // } else if (type === 'password') { + // setPasswordValue(value); + // } + // handleButton(); + // } + + // const checkId = idValue => { + // return idValue.includes('@') ? true : false; + // }; + + // const checkPw = pwValue => { + // return pwValue.length >= 5 ? true : false; + // }; + + // const handleButton = () => { + // const isValidId = checkId(state); + // const isValidPw = checkPw(passwordValue); + + // if (isValidId && isValidPw) { + // buttonColor(true); + // } else { + // buttonColor(false); + // } + // }; + + // const buttonColor = btnValid => { + // setDisabled(!btnValid); + // setStyle({ + // opacity: btnValid ? 1 : 0.5, + // cursor: btnValid ? 'pointer' : 'default', + // }); + // }; + + const goToMain = () => { + fetch('http://10.58.4.238:8000/users/login', { + method: 'POST', + body: JSON.stringify({ + email: loginValues.id, + password: loginValues.password, + // name: '๋ž˜์˜', + // phone_number: '010-1111-111', + }), + }) + .then(response => response.json()) + .then(result => { + // console.log(result); + if (result.token) { + //localStorage.setItem('token', result.token); + alert('ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค!'); + navigate('/main-han'); + } else if (result.message === 'INVALID_USER') { + alert('ID์™€ PW๋ฅผ ํ™•์ธํ•ด์ฃผ์„ธ์š”.'); + } + }); + }; + + const isInputValid = + loginValues.id.includes('@') && + loginValues.id.length >= 6 && + loginValues.password.length >= 6; + // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6); + // console.log(loginValues.password.length >= 6); + // console.log(isInputValid); + + return ( + <div className="login"> + <form className="loginBox"> + <h1>Westagram</h1> + <input + id="id" + name="id" + className="userId" + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + onChange={handleInputValue} + /> + <input + id="password" + name="password" + className="userPassword" + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + onChange={handleInputValue} + /> + <button + type="button" + className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`} + onClick={goToMain} + disabled={!isInputValid} + //style={style} + > + ๋กœ๊ทธ์ธ + </button> + <div className="findPassword"> + <a href="#">๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</a> + </div> + </form> + </div> + ); } export default Login;
JavaScript
๊น€ํ˜œ์ง„ ๋ฉ˜ํ† ๋‹˜ ๋ฆฌ๋ทฐ ๋ฐ˜์˜ํ•˜๊ธฐ
@@ -1,7 +1,128 @@ +import { useNavigate } from 'react-router-dom'; +import { useState } from 'react'; import './Login.scss'; function Login() { - return <></>; + // const [idState, setIdState] = useState(''); + // const [passwordValue, setPasswordValue] = useState(''); + // const [disabled, setDisabled] = useState(true); + // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' }); + + const navigate = useNavigate(); + const [loginValues, setLoginValues] = useState({ + id: '', + password: '', + }); + + const handleInputValue = e => { + const { name, value } = e.target; + setLoginValues({ ...loginValues, [name]: value }); + }; + + // const { type, value } = event.target; + + // function handleLogin(event) { + // if (type === 'text') { + // setIdState(value); + // } else if (type === 'password') { + // setPasswordValue(value); + // } + // handleButton(); + // } + + // const checkId = idValue => { + // return idValue.includes('@') ? true : false; + // }; + + // const checkPw = pwValue => { + // return pwValue.length >= 5 ? true : false; + // }; + + // const handleButton = () => { + // const isValidId = checkId(state); + // const isValidPw = checkPw(passwordValue); + + // if (isValidId && isValidPw) { + // buttonColor(true); + // } else { + // buttonColor(false); + // } + // }; + + // const buttonColor = btnValid => { + // setDisabled(!btnValid); + // setStyle({ + // opacity: btnValid ? 1 : 0.5, + // cursor: btnValid ? 'pointer' : 'default', + // }); + // }; + + const goToMain = () => { + fetch('http://10.58.4.238:8000/users/login', { + method: 'POST', + body: JSON.stringify({ + email: loginValues.id, + password: loginValues.password, + // name: '๋ž˜์˜', + // phone_number: '010-1111-111', + }), + }) + .then(response => response.json()) + .then(result => { + // console.log(result); + if (result.token) { + //localStorage.setItem('token', result.token); + alert('ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค!'); + navigate('/main-han'); + } else if (result.message === 'INVALID_USER') { + alert('ID์™€ PW๋ฅผ ํ™•์ธํ•ด์ฃผ์„ธ์š”.'); + } + }); + }; + + const isInputValid = + loginValues.id.includes('@') && + loginValues.id.length >= 6 && + loginValues.password.length >= 6; + // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6); + // console.log(loginValues.password.length >= 6); + // console.log(isInputValid); + + return ( + <div className="login"> + <form className="loginBox"> + <h1>Westagram</h1> + <input + id="id" + name="id" + className="userId" + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + onChange={handleInputValue} + /> + <input + id="password" + name="password" + className="userPassword" + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + onChange={handleInputValue} + /> + <button + type="button" + className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`} + onClick={goToMain} + disabled={!isInputValid} + //style={style} + > + ๋กœ๊ทธ์ธ + </button> + <div className="findPassword"> + <a href="#">๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</a> + </div> + </form> + </div> + ); } export default Login;
JavaScript
+์‚ผํ•ญ์—ฐ์‚ฐ์ž์˜ ์กฐ๊ฑด์€ ์œ„ ๋ฆฌ๋ทฐ์ฒ˜๋Ÿผ ๋ณ€์ˆ˜๋กœ ๋งŒ๋“ค์–ด์„œ ์‚ฌ์šฉํ•˜๊ธฐ
@@ -0,0 +1,14 @@ +import './Comment.scss'; + +function Comment({ userName, content }) { + return ( + <div className="comment"> + <p> + <strong className="commentMan">{userName}</strong> + {content} + </p> + </div> + ); +} + +export default Comment;
JavaScript
๋งค๊ฐœ๋ณ€์ˆ˜ ์ž๋ฆฌ์—์„œ ๊ตฌ์กฐ๋ถ„ํ•ดํ• ๋‹น ๊ตณ
@@ -0,0 +1,102 @@ +import { useState, useEffect } from 'react'; +import './Feed.scss'; +import Comment from './Comment'; + +function Feed(props) { + const [comment, setComment] = useState(''); + const [addCommentList, setAddCommentList] = useState([]); + const [cmtContList, setCmtContList] = useState([]); + const userName = 'test01'; + + const onChange = event => { + setComment(event.target.value); + }; + + const addComment = event => { + event.preventDefault(); + setAddCommentList([ + ...addCommentList, + { + name: userName, + content: comment, + }, + ]); + setComment(''); + }; + + useEffect(() => { + fetch('http://localhost:3000/data/younghyunHan/commentData.json') + .then(res => res.json()) + .then(data => { + setCmtContList(data); + }); + }, []); + + return ( + <article className="feed"> + <div className="feedTop"> + <div className="feedTopOne"> + <div className="profileLogo"> + <img className="profileLogoImg" src={props.profileLogo} /> + </div> + <div className="profileName"> + <div className="profileNameOne">{props.userName}</div> + <span className="profileNameTwo">Wecode - ์œ„์ฝ”๋“œ</span> + </div> + </div> + <i className="fas fa-ellipsis-h" /> + </div> + <img alt="ํ”ผ๋“œ ์ด๋ฏธ์ง€" className="feedImg" src={props.feedImg} /> + <div className="feedThree"> + <div> + <i className="far fa-heart" /> + <i className="far fa-comment" /> + <i className="fas fa-upload" /> + </div> + <i className="far fa-bookmark" /> + </div> + <div className="feedFour"> + <img alt="์ข‹์•„์š” ๋ˆ„๋ฅธ ์‚ฌ๋žŒ" className="man" src={props.userMan} /> + <span className="feedFourWord">seungyoun_iain</span> + &nbsp;์™ธ&nbsp; + <span className="feedFourWordTwo">4๋ช…</span>์ด ์ข‹์•„ํ•ฉ๋‹ˆ๋‹ค. + </div> + <div className="feedFive"> + <span className="feedFiveWord">wecode_bootcamp</span>"์œ„์ฝ”๋“œ๋Š” ๋‹จ์ˆœ + ๊ต์œก์—…์ฒด๊ฐ€ ์•„๋‹Œ ๊ฐœ๋ฐœ์ž ์ปค๋ฎค๋‹ˆํ‹ฐ์ž…๋‹ˆ๋‹ค. Wecode์—์„œ ๋ฐฐ์šฐ๊ณ  ์ €๋Š” ์ด 5๊ฐœ + ํšŒ์‚ฌ์—์„œ ์˜คํผ๋ฅผ ๋ฐ›์•˜์Šต๋‹ˆ๋‹ค. + </div> + <div className="comment"> + {cmtContList.map(content => { + return ( + <Comment + key={content.id} + userName={content.userName} + content={content.content} + /> + ); + })} + {addCommentList.map((content, index) => { + return ( + <div key={index}> + <Comment content={content.content} userName={content.name} /> + </div> + ); + })} + </div> + <span className="postTime">54๋ถ„ ์ „</span> + <form className="commentSection" onSubmit={addComment}> + <input + type="text" + placeholder="๋Œ“๊ธ€ ๋‹ฌ๊ธฐ..." + className="comment" + onChange={onChange} + value={comment} + /> + <button className="postButton">๊ฒŒ์‹œ</button> + </form> + </article> + ); +} + +export default Feed;
JavaScript
- ์žฌํ• ๋‹น๋˜์ง€ ์•Š๋Š” ๋ณ€์ˆ˜๋Š” const๋กœ ์„ ์–ธํ•˜๊ธฐ - ์ด ๋ถ€๋ถ„์€ ๋ณ€์ˆ˜ ์„ ์–ธ๋ณด๋‹จ ๊ตฌ์กฐ๋ถ„ํ•ดํ• ๋‹น ์ ์šฉํ•˜๊ธฐ
@@ -0,0 +1,102 @@ +import { useState, useEffect } from 'react'; +import './Feed.scss'; +import Comment from './Comment'; + +function Feed(props) { + const [comment, setComment] = useState(''); + const [addCommentList, setAddCommentList] = useState([]); + const [cmtContList, setCmtContList] = useState([]); + const userName = 'test01'; + + const onChange = event => { + setComment(event.target.value); + }; + + const addComment = event => { + event.preventDefault(); + setAddCommentList([ + ...addCommentList, + { + name: userName, + content: comment, + }, + ]); + setComment(''); + }; + + useEffect(() => { + fetch('http://localhost:3000/data/younghyunHan/commentData.json') + .then(res => res.json()) + .then(data => { + setCmtContList(data); + }); + }, []); + + return ( + <article className="feed"> + <div className="feedTop"> + <div className="feedTopOne"> + <div className="profileLogo"> + <img className="profileLogoImg" src={props.profileLogo} /> + </div> + <div className="profileName"> + <div className="profileNameOne">{props.userName}</div> + <span className="profileNameTwo">Wecode - ์œ„์ฝ”๋“œ</span> + </div> + </div> + <i className="fas fa-ellipsis-h" /> + </div> + <img alt="ํ”ผ๋“œ ์ด๋ฏธ์ง€" className="feedImg" src={props.feedImg} /> + <div className="feedThree"> + <div> + <i className="far fa-heart" /> + <i className="far fa-comment" /> + <i className="fas fa-upload" /> + </div> + <i className="far fa-bookmark" /> + </div> + <div className="feedFour"> + <img alt="์ข‹์•„์š” ๋ˆ„๋ฅธ ์‚ฌ๋žŒ" className="man" src={props.userMan} /> + <span className="feedFourWord">seungyoun_iain</span> + &nbsp;์™ธ&nbsp; + <span className="feedFourWordTwo">4๋ช…</span>์ด ์ข‹์•„ํ•ฉ๋‹ˆ๋‹ค. + </div> + <div className="feedFive"> + <span className="feedFiveWord">wecode_bootcamp</span>"์œ„์ฝ”๋“œ๋Š” ๋‹จ์ˆœ + ๊ต์œก์—…์ฒด๊ฐ€ ์•„๋‹Œ ๊ฐœ๋ฐœ์ž ์ปค๋ฎค๋‹ˆํ‹ฐ์ž…๋‹ˆ๋‹ค. Wecode์—์„œ ๋ฐฐ์šฐ๊ณ  ์ €๋Š” ์ด 5๊ฐœ + ํšŒ์‚ฌ์—์„œ ์˜คํผ๋ฅผ ๋ฐ›์•˜์Šต๋‹ˆ๋‹ค. + </div> + <div className="comment"> + {cmtContList.map(content => { + return ( + <Comment + key={content.id} + userName={content.userName} + content={content.content} + /> + ); + })} + {addCommentList.map((content, index) => { + return ( + <div key={index}> + <Comment content={content.content} userName={content.name} /> + </div> + ); + })} + </div> + <span className="postTime">54๋ถ„ ์ „</span> + <form className="commentSection" onSubmit={addComment}> + <input + type="text" + placeholder="๋Œ“๊ธ€ ๋‹ฌ๊ธฐ..." + className="comment" + onChange={onChange} + value={comment} + /> + <button className="postButton">๊ฒŒ์‹œ</button> + </form> + </article> + ); +} + +export default Feed;
JavaScript
- input์˜ value๊ฐ€ ๋“ค์–ด์˜ค๋Š” ๋ถ€๋ถ„์ธ๋ฐ, ์ดˆ๊ธฐ๊ฐ’์ด string์ด ์•„๋‹Œ ๋ฐฐ์—ด์ด ๋“ค์–ด์žˆ์Œ - cmtContents๋ผ๋Š” ๋ณ€์ˆ˜๋ช…๊ณผ ๋ฐฐ์—ด์ธ ์ดˆ๊ธฐ๊ฐ’์˜ ์กฐํ•ฉ์ด ๋ฐฐ์—ด ๋ฐ์ดํ„ฐ๋ฅผ ์—ฐ์ƒ์‹œํ‚ด - ๋ช…ํ™•ํ•˜์ง€๋งŒ ๊ฐ„๊ฒฐํ•œ state๋ช…์œผ๋กœ ์ˆ˜์ •. ex) `comment` / `commentList`
@@ -0,0 +1,102 @@ +import { useState, useEffect } from 'react'; +import './Feed.scss'; +import Comment from './Comment'; + +function Feed(props) { + const [comment, setComment] = useState(''); + const [addCommentList, setAddCommentList] = useState([]); + const [cmtContList, setCmtContList] = useState([]); + const userName = 'test01'; + + const onChange = event => { + setComment(event.target.value); + }; + + const addComment = event => { + event.preventDefault(); + setAddCommentList([ + ...addCommentList, + { + name: userName, + content: comment, + }, + ]); + setComment(''); + }; + + useEffect(() => { + fetch('http://localhost:3000/data/younghyunHan/commentData.json') + .then(res => res.json()) + .then(data => { + setCmtContList(data); + }); + }, []); + + return ( + <article className="feed"> + <div className="feedTop"> + <div className="feedTopOne"> + <div className="profileLogo"> + <img className="profileLogoImg" src={props.profileLogo} /> + </div> + <div className="profileName"> + <div className="profileNameOne">{props.userName}</div> + <span className="profileNameTwo">Wecode - ์œ„์ฝ”๋“œ</span> + </div> + </div> + <i className="fas fa-ellipsis-h" /> + </div> + <img alt="ํ”ผ๋“œ ์ด๋ฏธ์ง€" className="feedImg" src={props.feedImg} /> + <div className="feedThree"> + <div> + <i className="far fa-heart" /> + <i className="far fa-comment" /> + <i className="fas fa-upload" /> + </div> + <i className="far fa-bookmark" /> + </div> + <div className="feedFour"> + <img alt="์ข‹์•„์š” ๋ˆ„๋ฅธ ์‚ฌ๋žŒ" className="man" src={props.userMan} /> + <span className="feedFourWord">seungyoun_iain</span> + &nbsp;์™ธ&nbsp; + <span className="feedFourWordTwo">4๋ช…</span>์ด ์ข‹์•„ํ•ฉ๋‹ˆ๋‹ค. + </div> + <div className="feedFive"> + <span className="feedFiveWord">wecode_bootcamp</span>"์œ„์ฝ”๋“œ๋Š” ๋‹จ์ˆœ + ๊ต์œก์—…์ฒด๊ฐ€ ์•„๋‹Œ ๊ฐœ๋ฐœ์ž ์ปค๋ฎค๋‹ˆํ‹ฐ์ž…๋‹ˆ๋‹ค. Wecode์—์„œ ๋ฐฐ์šฐ๊ณ  ์ €๋Š” ์ด 5๊ฐœ + ํšŒ์‚ฌ์—์„œ ์˜คํผ๋ฅผ ๋ฐ›์•˜์Šต๋‹ˆ๋‹ค. + </div> + <div className="comment"> + {cmtContList.map(content => { + return ( + <Comment + key={content.id} + userName={content.userName} + content={content.content} + /> + ); + })} + {addCommentList.map((content, index) => { + return ( + <div key={index}> + <Comment content={content.content} userName={content.name} /> + </div> + ); + })} + </div> + <span className="postTime">54๋ถ„ ์ „</span> + <form className="commentSection" onSubmit={addComment}> + <input + type="text" + placeholder="๋Œ“๊ธ€ ๋‹ฌ๊ธฐ..." + className="comment" + onChange={onChange} + value={comment} + /> + <button className="postButton">๊ฒŒ์‹œ</button> + </form> + </article> + ); +} + +export default Feed;
JavaScript
ํ•จ์ˆ˜๋ช… ์ˆ˜์ •! - comment๋ฅผ ์ถ”๊ฐ€ํ•˜๋Š” ์—ญํ• ์„ ํ•˜๋Š” ํ•จ์ˆ˜ - ์—”ํ„ฐํ‚ค๋ฅผ ์ณค์„ ๋•Œ ์œ„ ํ•จ์ˆ˜๋ฅผ ์‹คํ–‰์‹œํ‚ค๋Š” ํ•จ์ˆ˜ ๋กœ ๋ถ„ํ• ํ•˜๋ฉด ์ข‹์„ ๋“ฏ
@@ -0,0 +1,102 @@ +import { useState, useEffect } from 'react'; +import './Feed.scss'; +import Comment from './Comment'; + +function Feed(props) { + const [comment, setComment] = useState(''); + const [addCommentList, setAddCommentList] = useState([]); + const [cmtContList, setCmtContList] = useState([]); + const userName = 'test01'; + + const onChange = event => { + setComment(event.target.value); + }; + + const addComment = event => { + event.preventDefault(); + setAddCommentList([ + ...addCommentList, + { + name: userName, + content: comment, + }, + ]); + setComment(''); + }; + + useEffect(() => { + fetch('http://localhost:3000/data/younghyunHan/commentData.json') + .then(res => res.json()) + .then(data => { + setCmtContList(data); + }); + }, []); + + return ( + <article className="feed"> + <div className="feedTop"> + <div className="feedTopOne"> + <div className="profileLogo"> + <img className="profileLogoImg" src={props.profileLogo} /> + </div> + <div className="profileName"> + <div className="profileNameOne">{props.userName}</div> + <span className="profileNameTwo">Wecode - ์œ„์ฝ”๋“œ</span> + </div> + </div> + <i className="fas fa-ellipsis-h" /> + </div> + <img alt="ํ”ผ๋“œ ์ด๋ฏธ์ง€" className="feedImg" src={props.feedImg} /> + <div className="feedThree"> + <div> + <i className="far fa-heart" /> + <i className="far fa-comment" /> + <i className="fas fa-upload" /> + </div> + <i className="far fa-bookmark" /> + </div> + <div className="feedFour"> + <img alt="์ข‹์•„์š” ๋ˆ„๋ฅธ ์‚ฌ๋žŒ" className="man" src={props.userMan} /> + <span className="feedFourWord">seungyoun_iain</span> + &nbsp;์™ธ&nbsp; + <span className="feedFourWordTwo">4๋ช…</span>์ด ์ข‹์•„ํ•ฉ๋‹ˆ๋‹ค. + </div> + <div className="feedFive"> + <span className="feedFiveWord">wecode_bootcamp</span>"์œ„์ฝ”๋“œ๋Š” ๋‹จ์ˆœ + ๊ต์œก์—…์ฒด๊ฐ€ ์•„๋‹Œ ๊ฐœ๋ฐœ์ž ์ปค๋ฎค๋‹ˆํ‹ฐ์ž…๋‹ˆ๋‹ค. Wecode์—์„œ ๋ฐฐ์šฐ๊ณ  ์ €๋Š” ์ด 5๊ฐœ + ํšŒ์‚ฌ์—์„œ ์˜คํผ๋ฅผ ๋ฐ›์•˜์Šต๋‹ˆ๋‹ค. + </div> + <div className="comment"> + {cmtContList.map(content => { + return ( + <Comment + key={content.id} + userName={content.userName} + content={content.content} + /> + ); + })} + {addCommentList.map((content, index) => { + return ( + <div key={index}> + <Comment content={content.content} userName={content.name} /> + </div> + ); + })} + </div> + <span className="postTime">54๋ถ„ ์ „</span> + <form className="commentSection" onSubmit={addComment}> + <input + type="text" + placeholder="๋Œ“๊ธ€ ๋‹ฌ๊ธฐ..." + className="comment" + onChange={onChange} + value={comment} + /> + <button className="postButton">๊ฒŒ์‹œ</button> + </form> + </article> + ); +} + +export default Feed;
JavaScript
๋™์ผํ•œ ์Šคํƒ€์ผ์„ ๊ฐ€์ง€๋Š” ๋ถ€๋ถ„์ธ๋ฐ, one two three ์ด๋Ÿฐ ์‹์œผ๋กœ ๋‚˜ํƒ€๋‚ผ ํ•„์š” ์—†์ด ๋‚ด์šฉ์„ ํฌ๊ด„ํ•˜๋Š” ๋ช…์นญ์˜ ๋™์ผํ•œ className์œผ๋กœ ์‚ฌ์šฉ
@@ -0,0 +1,132 @@ +.feed { + background-color: white; + margin-bottom: 50px; + + .feedTop { + display: flex; + justify-content: space-between; + position: relative; + padding: 10px; + + .feedTopOne { + display: flex; + align-items: center; + + .profileLogo { + display: flex; + align-items: center; + justify-content: center; + height: 35px; + width: 35px; + margin-right: 10px; + color: white; + background-color: black; + border-radius: 50%; + font-size: 7px; + font-weight: bold; + overflow: hidden; // ๋ถ€๋ชจ div๋งŒํผ ์ด๋ฏธ์ง€ ์ž๋ฆ„ + + .profileLogoImg { + width: 100%; + height: 100%; + object-fit: cover; // ๊ฐ€๋กœ, ์„ธ๋กœ ๋น„์œจ์ด ์•ˆ ๋งž์œผ๋ฉด ๋”ฑ ๋งž๊ฒŒ ์•ˆ ์ฐŒ๊ทธ๋Ÿฌ์ง€๊ฒŒ ๋งž์ถฐ์คŒ. + } + } + + .profileNameOne { + margin-bottom: 0px; + font-size: 15px; + font-weight: bold; + } + + .profileNameTwo { + color: #a3a49a; + font-size: 12px; + font-weight: bold; + } + } + + .fa-ellipsis-h { + position: absolute; + right: 20px; + top: 20px; + } + } + + .feedImg { + width: 100%; + height: 500px; + } + + .feedThree { + display: flex; + justify-content: space-between; + align-items: center; + padding: 10px; + font-size: 25px; + + .fa-heart, + .fa-comment { + margin-right: 10px; + } + } + + .feedFour { + display: flex; + align-items: center; + padding: 0px 10px 10px 10px; + + .man { + width: 20px; + height: 20px; + margin-right: 10px; + border-radius: 50%; + } // ์œ„ ์ฝ”๋“œ ์ฒ˜๋Ÿผ ํ•˜๋ ค๋ฉด div๋กœ ์ด๋ฏธ์ง€ ํ•œ๋ฒˆ ๋” ๊ฐ์จ์„œ ๊ทธ div์— overflow:hidden ์ฃผ๊ณ  + // imgํŒŒ์ผ์— width: 100%, height: 100%, object-fit: cover์ฃผ๋ฉด ๋จ + + .feedFourWord, + .feedFourWordTwo { + font-weight: bold; + } + } + + .feedFive { + padding: 0px 10px 3px 10px; + + .feedFiveWord { + font-weight: bold; + } + } + + .comment { + padding-top: 5px; + padding-left: 5px; + padding-bottom: 5px; + } + + .postTime { + display: inline-block; + padding: 10px 10px 15px 10px; + color: #9c9c9c; + } + + .commentSection { + position: relative; + + .comment { + width: 100%; + padding: 15px 10px; + border: 1px solid #f3f3f3; + } + + .postButton { + position: absolute; + bottom: 13px; + right: 20px; + color: #c5e1fc; + background-color: white; + border: 1px solid white; + font-size: 15px; + } + } +}
Unknown
- article ํƒœ๊ทธ๊ฐ€ ์•„๋‹ˆ๋ผ feed๋ผ๋Š” className์œผ๋กœ nestingํ•˜๊ธฐ - ์ตœ์ƒ์œ„ div๋ฅผ article๋กœ ๋ฐ”๊พธ๊ณ  1 depth ์ค„์ด๋ฉด ๋  ๋“ฏ
@@ -0,0 +1,66 @@ +package blackjack.controller; + +import blackjack.domain.card.Deck; +import blackjack.domain.participant.Dealer; +import blackjack.domain.participant.Player; +import blackjack.domain.participant.PlayersFactory; +import blackjack.domain.result.GameResult; +import blackjack.dto.DrawCardRequestDto; +import blackjack.dto.PlayersNameInputDto; +import blackjack.view.InputView; +import blackjack.view.OutputView; + +import java.util.List; + +public class BlackJackController { + private final InputView inputView = new InputView(); + private final OutputView outputView = new OutputView(); + + public void run() { + PlayersNameInputDto namesInput = inputView.getPlayersName(); + Dealer dealer = new Dealer(); + Deck deck = new Deck(); + List<Player> players = PlayersFactory.createPlayers(namesInput.getPlayersName()); + + drawTowCards(dealer, players, deck); + drawCardToPlayers(players, deck); + drawCardToDealer(dealer, deck); + outputView.printCardsResult(dealer, players); + outputView.printGameResult(GameResult.of(dealer, players)); + } + + private void drawTowCards(Dealer dealer, List<Player> players, Deck deck) { + for (Player player : players) { + player.receiveCard(deck.drawCard()); + player.receiveCard(deck.drawCard()); + } + dealer.receiveCard(deck.drawCard()); + dealer.receiveCard(deck.drawCard()); + outputView.printFirstCardsGiven(players, dealer); + outputView.printDealerCard(dealer); + outputView.printPlayersCard(players); + } + + private void drawCardToPlayers(List<Player> players, Deck deck) { + for (Player player : players) { + drawCardToPlayer(player, deck); + } + } + + private void drawCardToPlayer(Player player, Deck deck) { + DrawCardRequestDto drawCardRequest = inputView.getPlayersResponse(player); + while (player.drawable() && drawCardRequest.isYes()) { + player.receiveCard(deck.drawCard()); + + outputView.printCards(player); + drawCardRequest = inputView.getPlayersResponse(player); + } + } + + private void drawCardToDealer(Dealer dealer, Deck deck) { + while (dealer.drawable()) { + dealer.receiveCard(deck.drawCard()); + outputView.printDealerCardGiven(); + } + } +}
Java
Controller๋ฅผ Entry-point๋กœ์จ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ๋Š”๋ฐ, ํ˜„์žฌ์™€ ๊ฐ™์ด ํ•ด๋‹น ๊ฐ’๋“ค์„ ์ด๋ฅผ ๋ฉค๋ฒ„๋ณ€์ˆ˜๋กœ ๊ฐ€์ง€๊ฒŒ ๋˜๋ฉด ํ•ด๋‹น ๊ฒŒ์ž„์„ ์—ฌ๋Ÿฌ๋ช…์ด ๋™์‹œ์— ์š”์ฒญํ•˜๋Š” ๊ฒฝ์šฐ ๋ฐ์ดํ„ฐ ๋ถ€์ •ํ•ฉ์ด ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ์–ด์š”. ๋ฉค๋ฒ„๋ณ€์ˆ˜๋ฅผ ์ง€์—ญ๋ณ€์ˆ˜๋กœ ๊ฐ€์ ธ๊ฐ€๋Š” ๊ฒƒ์ด ์ข‹์•„ ๋ณด์—ฌ์š”๐Ÿ™‚
@@ -0,0 +1,66 @@ +package blackjack.controller; + +import blackjack.domain.card.Deck; +import blackjack.domain.participant.Dealer; +import blackjack.domain.participant.Player; +import blackjack.domain.participant.PlayersFactory; +import blackjack.domain.result.GameResult; +import blackjack.dto.DrawCardRequestDto; +import blackjack.dto.PlayersNameInputDto; +import blackjack.view.InputView; +import blackjack.view.OutputView; + +import java.util.List; + +public class BlackJackController { + private final InputView inputView = new InputView(); + private final OutputView outputView = new OutputView(); + + public void run() { + PlayersNameInputDto namesInput = inputView.getPlayersName(); + Dealer dealer = new Dealer(); + Deck deck = new Deck(); + List<Player> players = PlayersFactory.createPlayers(namesInput.getPlayersName()); + + drawTowCards(dealer, players, deck); + drawCardToPlayers(players, deck); + drawCardToDealer(dealer, deck); + outputView.printCardsResult(dealer, players); + outputView.printGameResult(GameResult.of(dealer, players)); + } + + private void drawTowCards(Dealer dealer, List<Player> players, Deck deck) { + for (Player player : players) { + player.receiveCard(deck.drawCard()); + player.receiveCard(deck.drawCard()); + } + dealer.receiveCard(deck.drawCard()); + dealer.receiveCard(deck.drawCard()); + outputView.printFirstCardsGiven(players, dealer); + outputView.printDealerCard(dealer); + outputView.printPlayersCard(players); + } + + private void drawCardToPlayers(List<Player> players, Deck deck) { + for (Player player : players) { + drawCardToPlayer(player, deck); + } + } + + private void drawCardToPlayer(Player player, Deck deck) { + DrawCardRequestDto drawCardRequest = inputView.getPlayersResponse(player); + while (player.drawable() && drawCardRequest.isYes()) { + player.receiveCard(deck.drawCard()); + + outputView.printCards(player); + drawCardRequest = inputView.getPlayersResponse(player); + } + } + + private void drawCardToDealer(Dealer dealer, Deck deck) { + while (dealer.drawable()) { + dealer.receiveCard(deck.drawCard()); + outputView.printDealerCardGiven(); + } + } +}
Java
๋ฉ”์†Œ๋“œ ๋ถ„๋ฆฌ๊ฐ€ ์ž˜ ๋˜์–ด ์žˆ์–ด์„œ, ๊ฐ€๋…์„ฑ์ด ์ข‹๋„ค์š”๐Ÿ™‚
@@ -0,0 +1,66 @@ +package blackjack.controller; + +import blackjack.domain.card.Deck; +import blackjack.domain.participant.Dealer; +import blackjack.domain.participant.Player; +import blackjack.domain.participant.PlayersFactory; +import blackjack.domain.result.GameResult; +import blackjack.dto.DrawCardRequestDto; +import blackjack.dto.PlayersNameInputDto; +import blackjack.view.InputView; +import blackjack.view.OutputView; + +import java.util.List; + +public class BlackJackController { + private final InputView inputView = new InputView(); + private final OutputView outputView = new OutputView(); + + public void run() { + PlayersNameInputDto namesInput = inputView.getPlayersName(); + Dealer dealer = new Dealer(); + Deck deck = new Deck(); + List<Player> players = PlayersFactory.createPlayers(namesInput.getPlayersName()); + + drawTowCards(dealer, players, deck); + drawCardToPlayers(players, deck); + drawCardToDealer(dealer, deck); + outputView.printCardsResult(dealer, players); + outputView.printGameResult(GameResult.of(dealer, players)); + } + + private void drawTowCards(Dealer dealer, List<Player> players, Deck deck) { + for (Player player : players) { + player.receiveCard(deck.drawCard()); + player.receiveCard(deck.drawCard()); + } + dealer.receiveCard(deck.drawCard()); + dealer.receiveCard(deck.drawCard()); + outputView.printFirstCardsGiven(players, dealer); + outputView.printDealerCard(dealer); + outputView.printPlayersCard(players); + } + + private void drawCardToPlayers(List<Player> players, Deck deck) { + for (Player player : players) { + drawCardToPlayer(player, deck); + } + } + + private void drawCardToPlayer(Player player, Deck deck) { + DrawCardRequestDto drawCardRequest = inputView.getPlayersResponse(player); + while (player.drawable() && drawCardRequest.isYes()) { + player.receiveCard(deck.drawCard()); + + outputView.printCards(player); + drawCardRequest = inputView.getPlayersResponse(player); + } + } + + private void drawCardToDealer(Dealer dealer, Deck deck) { + while (dealer.drawable()) { + dealer.receiveCard(deck.drawCard()); + outputView.printDealerCardGiven(); + } + } +}
Java
DTO๋„ ์ž์‹ ์ด ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ๋ฐ์ดํ„ฐ์— ๋Œ€ํ•ด์„œ, ์–ด๋–ค ํ–‰์œ„/ํŒ๋‹จ์„ ํ•  ์ˆ˜ ์žˆ๋‹ค๊ณ  ์ƒ๊ฐํ•ด์š”. ์ž…๋ ฅ๋ฐ›์€ ๊ฐ’์ด Y/N์ธ์ง€ ํŒ๋‹จํ•˜๋Š” ๋กœ์ง์€ DTO๋กœ ๊ฐ€๋„ ๋œ๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. ๋‹ค๋งŒ ํ•ด๋‹น ๋กœ์ง์ด ์—ฌ๋Ÿฌ ๊ณณ์—์„œ ์‚ฌ์šฉ๋˜๊ฑฐ๋‚˜, ์ด๋ฅผ ํ•˜๋‚˜์˜ ๋„๋ฉ”์ธ ํ–‰์œ„๋กœ ์ •์˜ํ•œ๋‹ค๋ฉด DTO -> Domain์œผ๋กœ ์ „ํ™˜ํ•œ ๋‹ค์Œ ๋„๋ฉ”์ธ์—์„œ ํŒ๋‹จํ•˜๋Š” ๊ฒƒ๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”. ํ˜„์žฌ๋Š” ํ•ด๋‹น ๋ถ€๋ถ„์— ๋Œ€ํ•œ ๋„๋ฉ”์ธ ๋กœ์ง์ด Controller์— ๋‚˜์™€ ์žˆ๊ธฐ์— ์›ํ•˜์‹œ๋Š” ํ˜•ํƒœ๋กœ ํฌ์žฅํ•ด์ฃผ์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค๐Ÿ™‚ ์ถ”๊ฐ€๋กœ ๋„ค์ด๋ฐ์€ ํŒ€๋ฐ”ํŒ€์ด๊ณ  ์‚ฌ๋ฐ”์‚ฌ์ง€๋งŒ, ๊ฐœ์ธ์ ์œผ๋กœ ํ”„๋กœ๊ทธ๋žจ์—๊ฒŒ ๋„˜์–ด์˜จ Input์„ ๋‹ด๋Š” DTO๋Š” Request/์šฐ๋ฆฌ ํ”„๋กœ๊ทธ๋žจ์—์„œ ๋ฐ˜ํ™˜ํ•ด์ฃผ๋Š”DTO๋Š” Response๋กœ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ์–ด์š”. response๋กœ ์ž‘์„ฑํ•ด์ฃผ์‹  ๋งฅ๋ฝ์€ ์•Œ๊ฒ ์œผ๋‚˜, Client-Server๊ฐ€ ํ•ญ์ƒ ์œ ๋™์ ์œผ๋กœ ๋‹ฌ๋ผ์งˆ ์ˆ˜ ์žˆ๋‹ค๋ฉด DTO๊ฐ€ ๋งŽ์•„์กŒ์„ ๋•Œ ํ—ท๊ฐˆ๋ฆด ์ˆ˜ ์žˆ๋‹ค๊ณ  ์ƒ๊ฐํ•ด์š”๐Ÿ™‚ (์ถ”๊ฐ€๋กœ DTO๋Š” > Dto๋กœ ์ ๊ณ  ์žˆ๊ธดํ•ฉ๋‹ˆ๋‹ค - ์ทจํ–ฅ)
@@ -0,0 +1,17 @@ +package blackjack.utils; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class StringUtil { + private static final String COMMA = ","; + private static final String RESPONSE_RESTRICT_MESSAGE = "y ํ˜น์€ n ๋งŒ ์ž…๋ ฅํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค."; + + public static List<String> splitByComma(String input) { + List<String> names = Arrays.asList(input.split(COMMA)); + return names.stream() + .map(String::trim) + .collect(Collectors.toList()); + } +}
Java
`Utils์„ฑ ํด๋ž˜์Šค`๋Š” ์ผ๋ฐ˜์ ์œผ๋กœ ์ •๋ง ์œ ํ‹ธ๋ฆฌํ‹ฐํ•œ ๊ฒƒ๋“ค๋งŒ ๊ธฐ๋Šฅ์„ ๋‹ด๋Š” ๊ฒƒ์ด ์ผ๋ฐ˜์ ์ด์—์š”. ํ˜„์žฌ ์œ ํ‹ธ๋กœ์ง์ด Y/N์ด๋ผ๋Š” ์–ด๋–ค ๋ฃฐ์— ๋Œ€ํ•ด์„œ ๋„ˆ๋ฌด ๋งŽ์ด ์•Œ๊ณ  ์žˆ๋Š” ์ƒํƒœ์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค ๋„๋ฉ”์ธ ํ˜น์€ DTO์˜ ๋กœ์ง์œผ๋กœ ๋ณ€๊ฒฝํ•˜๋Š” ๊ฒƒ์ด ์ข‹์•„๋ณด์ด๊ณ , Util์—์„œ ์‚ฌ์šฉํ•˜์‹ ๋‹ค๋ฉด ๊ฒ€์ฆ ๋Œ€์ƒ์ด ๋˜๋Š” Y/N๋„ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ๋ฐ›๋Š”๋‹ค๋ฉด ์กฐ๊ธˆ ๋” ๋ฒ”์šฉ์ ์œผ๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ๋ฉ”์†Œ๋“œ๊ฐ€ ๋  ๊ฒƒ ๊ฐ™์•„์š”.
@@ -0,0 +1,32 @@ +package blackjack.domain.card; + +import blackjack.domain.card.strategy.DrawStrategy; +import blackjack.domain.card.strategy.RandomDrawStrategy; +import lombok.Getter; + +import java.util.LinkedList; +import java.util.List; + +public class Deck { + + private static final String ALERT_NO_CARD_LEFT = "์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์นด๋“œ๋ฅผ ๋ชจ๋‘ ์†Œ์ง„ํ•˜์˜€์Šต๋‹ˆ๋‹ค."; + + @Getter + private final List<Card> deck; + + public Deck() { + this.deck = new LinkedList<>(DeckFactory.createDeck()); + } + + public Card drawCard() { + if (deck.isEmpty()) { + throw new RuntimeException(ALERT_NO_CARD_LEFT); + } + return deck.remove(generateNextDrawCardIndex(new RandomDrawStrategy())); + } + + private int generateNextDrawCardIndex(DrawStrategy drawStrategy) { + return drawStrategy.getNextIndex(deck); + } + +}
Java
LinkedList๋กœ ์„ ์–ธํ•˜์‹  ์ด์œ ๋Š” ์นด๋“œ๋ฅผ ํ•œ์žฅ์”ฉ ์‚ญ์ œํ•  ๋•Œ ArrayList๊ฐ€ ๋น„ํšจ์œจ์ ์ด๋ผ์„œ ๊ทธ๋ ‡๊ฒŒ ํ•˜์‹ ๊ฑธ๊นŒ์š”? ๐Ÿ‘
@@ -0,0 +1,32 @@ +package blackjack.domain.card; + +import blackjack.domain.card.strategy.DrawStrategy; +import blackjack.domain.card.strategy.RandomDrawStrategy; +import lombok.Getter; + +import java.util.LinkedList; +import java.util.List; + +public class Deck { + + private static final String ALERT_NO_CARD_LEFT = "์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์นด๋“œ๋ฅผ ๋ชจ๋‘ ์†Œ์ง„ํ•˜์˜€์Šต๋‹ˆ๋‹ค."; + + @Getter + private final List<Card> deck; + + public Deck() { + this.deck = new LinkedList<>(DeckFactory.createDeck()); + } + + public Card drawCard() { + if (deck.isEmpty()) { + throw new RuntimeException(ALERT_NO_CARD_LEFT); + } + return deck.remove(generateNextDrawCardIndex(new RandomDrawStrategy())); + } + + private int generateNextDrawCardIndex(DrawStrategy drawStrategy) { + return drawStrategy.getNextIndex(deck); + } + +}
Java
ํ˜„์žฌ๋Š” ๊ฒฝ๊ธฐ๋„์ค‘์— ์นด๋“œ๊ฐ€ ๋ชจ๋‘ ์†Œ์ง„๋˜๋ฉด, ํ”„๋กœ๊ทธ๋žจ์ด ์ข…๋ฃŒ๋˜๋Š” ๊ตฌ์กฐ์ธ๋ฐ์š”. ์ผ๋ฐ˜์ ์œผ๋กœ ๊ฒฝ๊ธฐ๋ฅผ ํ•˜๋‹ค, ์นด๋“œ๊ฐ€ ๋ชจ๋‘ ์†Œ์ง„๋œ๋‹ค๊ณ  ๊ทธ ๊ฒŒ์ž„์ด ๋ฌดํšจ๊ฐ€ ๋˜์ง€ ์•Š๋“ฏ์ด ์กฐ๊ธˆ ๋” ๊ตฌ์ฒด์ ์ธ ๋ฐฉ๋ฒ•/๊ตฌํ˜„์„ ๊ณ ๋ฏผํ•ด๋ณด๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”. (๊ตฌํ˜„์€ ํ•˜์ง€ ์•Š์œผ์…”๋„ ๋ฉ๋‹ˆ๋‹ค) ๋„๋ฉ”์ธ์— ๋Œ€ํ•ด์„œ ์กฐ๊ธˆ ๋” ๋Šฅ๋™์ ์œผ๋กœ ์ดํ•ดํ•˜๋ฉด ์–ด๋–จ๊นŒ ๋ผ๋Š” ์˜๋ฏธ์—์„œ ๋“œ๋ฆฐ ํ”ผ๋“œ๋ฐฑ์ž…๋‹ˆ๋‹ค. (์ฐธ๊ณ ๋กœ ๋ธ”๋ž™์žญ์—์„œ๋Š” ์ฐธ๊ฐ€ ์ธ์›์„ ์ œํ•œํ•˜๊ณ  ์žˆ๋”๋ผ๊ตฌ์š”๐Ÿ™‚)
@@ -0,0 +1,32 @@ +package blackjack.domain.card; + +import blackjack.domain.card.strategy.DrawStrategy; +import blackjack.domain.card.strategy.RandomDrawStrategy; +import lombok.Getter; + +import java.util.LinkedList; +import java.util.List; + +public class Deck { + + private static final String ALERT_NO_CARD_LEFT = "์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์นด๋“œ๋ฅผ ๋ชจ๋‘ ์†Œ์ง„ํ•˜์˜€์Šต๋‹ˆ๋‹ค."; + + @Getter + private final List<Card> deck; + + public Deck() { + this.deck = new LinkedList<>(DeckFactory.createDeck()); + } + + public Card drawCard() { + if (deck.isEmpty()) { + throw new RuntimeException(ALERT_NO_CARD_LEFT); + } + return deck.remove(generateNextDrawCardIndex(new RandomDrawStrategy())); + } + + private int generateNextDrawCardIndex(DrawStrategy drawStrategy) { + return drawStrategy.getNextIndex(deck); + } + +}
Java
Randomํ•œ ๊ฐ’์„ ํ…Œ์ŠคํŠธํ•˜๊ธฐ ์œ„ํ•ด์„œ, ๋ ˆ์ด์‹ฑ์นด์—์„œ ํ–ˆ๋˜ ๋ฐฉ์‹์œผ๋กœ ์ด๋ฅผ ์™ธ๋ถ€์—์„œ ์ฃผ์ž…๋ฐ›๋Š” ํ˜•ํƒœ๋กœ ํ•˜๋ฉด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,39 @@ +package blackjack.domain.card; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class DeckFactory { + + private static final List<Card> cardsDeck; + + static { + cardsDeck = createCardsDeck(); + } + + private static List<Card> createCardsDeck() { + List<Card> cards = new ArrayList<>(); + + for (Denomination denomination : Denomination.values()) { + cards.addAll(createCards(denomination)); + } + return cards; + } + + private static List<Card> createCards(Denomination denomination) { + List<Card> cards = new ArrayList<>(); + + for (Type type : Type.values()) { + cards.add(new Card(denomination, type)); + } + + return cards; + } + + public static List<Card> createDeck() { + return Collections.unmodifiableList(cardsDeck); + } +} + +
Java
์Šคํƒœํ‹ฑํ•˜๊ฒŒ ์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜์ด ์‹œ์ž‘๋จ๊ณผ ๋™์‹œ์— ์ƒ๊ธด๋‹ค๋Š” ๊ฒƒ์„ ๋ช…์‹œ์ ์œผ๋กœ ํ•˜๊ธฐ ์œ„ํ•ด์„œ static { } ํ˜•ํƒœ๋กœ ์ดˆ๊ธฐํ™”๋ฅผ ํ•  ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค๐Ÿ™‚
@@ -0,0 +1,39 @@ +package blackjack.domain.card; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class DeckFactory { + + private static final List<Card> cardsDeck; + + static { + cardsDeck = createCardsDeck(); + } + + private static List<Card> createCardsDeck() { + List<Card> cards = new ArrayList<>(); + + for (Denomination denomination : Denomination.values()) { + cards.addAll(createCards(denomination)); + } + return cards; + } + + private static List<Card> createCards(Denomination denomination) { + List<Card> cards = new ArrayList<>(); + + for (Type type : Type.values()) { + cards.add(new Card(denomination, type)); + } + + return cards; + } + + public static List<Card> createDeck() { + return Collections.unmodifiableList(cardsDeck); + } +} + +
Java
๋ฉ”์†Œ๋“œ์˜ ๋„ค์ด๋ฐ์œผ๋กœ ๋ดค์„ ๋•Œ `Deck` ์„ ๋งŒ๋“ค ๊ฒƒ ๊ฐ™์€๋ฐ, List<Card> ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ณ  ์žˆ๋Š” ๋ถ€๋ถ„์ด ์ง๊ด€์ ์œผ๋กœ ์ดํ•ด๋˜์ง€ ์•Š๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์ถ”๊ฐ€๋กœ ์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜์ด ๋œธ๊ณผ ๋™์‹œ์— `cardDecks`๋ฅผ ๋งŒ๋“ค๊ณ  ์žˆ์–ด์„œ, ์‚ฌ์šฉํ•œ๋‹ค๋ฉด getter ํ˜•ํƒœ๋กœ ์‚ฌ์šฉํ•ด์•ผํ•˜์ง€ ์•Š์„๊นŒ ์‹ถ๋„ค์š”. ํ˜น์‹œ ์ด ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ์‚ฌ๋žŒ ์ž…์žฅ์—์„œ๋Š” `์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜์—์„œ ํ•ด๋‹น ๊ฐ’(List<Card>)์€ ํ•ญ์ƒ ๊ณ ์ •๋˜์–ด ์žˆ๋‹ค๋ผ๋Š”๊ฑธ ๋ชฐ๋ผ๋„ ๋˜๊ณ  ํ•„์š”ํ•  ๋•Œ ๋‹ฌ๋ผํ•˜๋ฉด ๋œ๋‹ค` ๋А๋‚Œ์œผ๋กœ ์ž‘์„ฑํ•˜์‹ ๊ฑธ๊นŒ์š”? > ์š” ๊ฒฝ์šฐ์—๋„ ์‚ฌ์šฉ์ž ์ž…์žฅ์—์„  ํ•ญ์ƒ ๋ฑ์„ ๋งŒ๋“ค๊ฑฐ๋ผ ์˜ˆ์ƒํ•˜๊ณ  ๋กœ์ง์„ ์ง„ํ–‰ํ•  ์ˆ˜ ์žˆ์–ด์„œ ์œ„ํ—˜ํ•  ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,38 @@ +package blackjack.domain.card; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class CardTest { + + @DisplayName("์นด๋“œ ๊ฐ์ฒด์˜ ์ˆซ์ž์™€ ์ข…๋ฅ˜๊ฐ’์ด ๊ฐ™์œผ๋ฉด ๊ฐ™์€ ๊ฐ์ฒด๋กœ ํŒ๋‹จํ•œ๋‹ค") + @Test + void equalsTest() { + //given, when, then + assertThat(new Card(Denomination.TWO, Type.DIAMOND)) + .isEqualTo(new Card(Denomination.TWO, Type.DIAMOND)); + + } + + @DisplayName("์นด๋“œ ๊ฐ์ฒด์˜ ์ˆซ์ž์™€ ์ข…๋ฅ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค") + @Test + void printCardTwoDiamond() { + //given + Card card = new Card(Denomination.TWO, Type.DIAMOND); + + //when, then + assertThat(card).hasToString("2๋‹ค์ด์•„๋ชฌ๋“œ"); + } + + @DisplayName("์นด๋“œ ๊ฐ์ฒด์˜ ์ˆซ์ž์™€ ์ข…๋ฅ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค") + @Test + void printCardAceHeart() { + //given + Card card = new Card(Denomination.ACE, Type.HEART); + + //when, then + assertThat(card.toString()).isEqualTo("Aํ•˜ํŠธ"); + } +}
Java
`assertThat(card).hasToString("2๋‹ค์ด์•„๋ชฌ๋“œ")` ์ด๋Ÿฐ ๋ฌธ๋ฒ•๋„ ์žˆ์Šต๋‹ˆ๋‹ค๐Ÿ™‚
@@ -0,0 +1,102 @@ +package blackjack.domain.participant; + +import blackjack.domain.card.Card; +import blackjack.domain.card.Denomination; +import lombok.Getter; +import org.apache.commons.lang3.StringUtils; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +@Getter +public abstract class Participant { + private static final int DIFFERENCE_OF_ACE_SCORE = 10; + private static final int BLACKJACK = 21; + private static final int ZERO = 0; + private static final String CHECK_NULL_OR_EMPTY = "์ด๋ฆ„์ด ๋นˆ ์นธ ํ˜น์€ null ๊ฐ’์ด ์•„๋‹Œ์ง€ ํ™•์ธํ•ด์ฃผ์„ธ์š”."; + private static final String CHECK_CONTAINING_ONLY_LETTERS_AND_DIGITS = "์ด๋ฆ„์€ ํŠน์ˆ˜๋ฌธ์ž๋ฅผ ํฌํ•จํ•˜์ง€ ์•Š์€ ๋ฌธ์ž์™€ ์ˆซ์ž๋กœ ์ง€์ •ํ•ด์ฃผ์„ธ์š”."; + + private final String name; + private final List<Card> cards; + + protected Participant(String name) { + validateName(name); + + this.name = name; + this.cards = new ArrayList<>(); + } + + private void validateName(String name) { + validateNullOrEmpty(name); + validateAlphaNumeric(name); + } + + private void validateNullOrEmpty(String name) { + if (StringUtils.isBlank(name)) { + throw new IllegalArgumentException(CHECK_NULL_OR_EMPTY); + } + } + + private void validateAlphaNumeric(String name) { + if (!StringUtils.isAlphanumericSpace(name)) { + throw new IllegalArgumentException(CHECK_CONTAINING_ONLY_LETTERS_AND_DIGITS); + } + } + + protected abstract boolean drawable(); + + public void receiveCard(Card card) { + cards.add(card); + } + + public int getCardsSum() { + int scoreOfAceAsEleven = sumOfCardsScore(); + int aceCount = getAceCount(); + + while (canCountAceAsOne(scoreOfAceAsEleven, aceCount)) { + scoreOfAceAsEleven = scoreOfAceAsOne(scoreOfAceAsEleven); + aceCount--; + } + + return scoreOfAceAsEleven; + } + + private int scoreOfAceAsOne(int scoreOfAceAsEleven) { + return scoreOfAceAsEleven - DIFFERENCE_OF_ACE_SCORE; + } + + private boolean canCountAceAsOne(int scoreOfAceAsEleven, int aceCount) { + return scoreOfAceAsEleven > BLACKJACK && aceCount > ZERO; + } + + private int getAceCount() { + return (int) cards.stream() + .filter(Card::isAce) + .count(); + } + + private int sumOfCardsScore() { + return cards.stream() + .map(Card::getDenomination) + .mapToInt(Denomination::getScore) + .sum(); + } + + public boolean isBust() { + return getCardsSum() > BLACKJACK; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Participant that = (Participant) o; + return Objects.equals(name, that.name) && Objects.equals(cards, that.cards); + } + + @Override + public int hashCode() { + return Objects.hash(name, cards); + } +}
Java
ACE์˜ ์ˆ˜๋ฅผ ๊ฒฐ์ •ํ•  ๋•Œ, 1 ๋˜๋Š” 11์ด ๋˜๋Š” ๋กœ์ง์€ Denomination์˜ ์—ญํ• ์ด ์•„๋‹๊นŒ์š”?
@@ -0,0 +1,27 @@ +package blackjack.domain.participant; + +import lombok.Getter; + +@Getter +public class Player extends Participant { + + private static final int PLAYER_DRAW_THRESHOLD = 21; + private static final String DEALER_NAME = "๋”œ๋Ÿฌ"; + private static final String CHECK_SAME_NAME_AS_DEALER = "์ด๋ฆ„์€ ๋”œ๋Ÿฌ์™€ ๊ฐ™์„ ์ˆ˜ ์—†์œผ๋‹ˆ ๋‹ค๋ฅธ ์ด๋ฆ„์„ ์ง€์ •ํ•ด์ฃผ์„ธ์š”."; + + public Player(String name) { + super(name); + validateDealerNameDuplicated(name); + } + + private void validateDealerNameDuplicated(String name) { + if (name.equals(DEALER_NAME)) { + throw new IllegalArgumentException(CHECK_SAME_NAME_AS_DEALER); + } + } + + @Override + public boolean drawable() { + return getCardsSum() < PLAYER_DRAW_THRESHOLD; + } +}
Java
์žฌ๋ฐŒ๋Š” ์ œ์•ฝ์‚ฌํ•ญ์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค๐Ÿ™‚
@@ -0,0 +1,27 @@ +package blackjack.domain.participant; + +import lombok.Getter; + +@Getter +public class Player extends Participant { + + private static final int PLAYER_DRAW_THRESHOLD = 21; + private static final String DEALER_NAME = "๋”œ๋Ÿฌ"; + private static final String CHECK_SAME_NAME_AS_DEALER = "์ด๋ฆ„์€ ๋”œ๋Ÿฌ์™€ ๊ฐ™์„ ์ˆ˜ ์—†์œผ๋‹ˆ ๋‹ค๋ฅธ ์ด๋ฆ„์„ ์ง€์ •ํ•ด์ฃผ์„ธ์š”."; + + public Player(String name) { + super(name); + validateDealerNameDuplicated(name); + } + + private void validateDealerNameDuplicated(String name) { + if (name.equals(DEALER_NAME)) { + throw new IllegalArgumentException(CHECK_SAME_NAME_AS_DEALER); + } + } + + @Override + public boolean drawable() { + return getCardsSum() < PLAYER_DRAW_THRESHOLD; + } +}
Java
ํ˜„์žฌ ์‚ฌ์šฉํ•˜์‹  ์ด์œ ๋Š” OutputView ๋กœ์ง์„ ๋‹จ์ˆœํ•˜๊ฒŒ ํ•˜๊ธฐ ์œ„ํ•จ์ธ ๊ฒƒ ๊ฐ™์•„์š”. ํ™”๋ฉด์— ๋ณด์—ฌ์ฃผ๋Š” ํ˜•ํƒœ๊ฐ€ ๋‹ฌ๋ผ์กŒ์„ ๋•Œ, ๋„๋ฉ”์ธ์„ ์ˆ˜์ •ํ•ด์•ผ ํ•œ๋‹ค๋ฉด ์˜์กด๊ด€๊ณ„๊ฐ€ ์ž˜ ๋ชป ์„ค๊ณ„๋œ๊ฑฐ๋ผ๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,27 @@ +package blackjack.domain.participant; + +import lombok.Getter; + +@Getter +public class Player extends Participant { + + private static final int PLAYER_DRAW_THRESHOLD = 21; + private static final String DEALER_NAME = "๋”œ๋Ÿฌ"; + private static final String CHECK_SAME_NAME_AS_DEALER = "์ด๋ฆ„์€ ๋”œ๋Ÿฌ์™€ ๊ฐ™์„ ์ˆ˜ ์—†์œผ๋‹ˆ ๋‹ค๋ฅธ ์ด๋ฆ„์„ ์ง€์ •ํ•ด์ฃผ์„ธ์š”."; + + public Player(String name) { + super(name); + validateDealerNameDuplicated(name); + } + + private void validateDealerNameDuplicated(String name) { + if (name.equals(DEALER_NAME)) { + throw new IllegalArgumentException(CHECK_SAME_NAME_AS_DEALER); + } + } + + @Override + public boolean drawable() { + return getCardsSum() < PLAYER_DRAW_THRESHOLD; + } +}
Java
ํ•ด๋‹น ๋ฉ”์†Œ๋“œ๋Š” ์ด๊ฒผ๋‹ค๊ฐ€, ์•„๋‹ˆ๋ผ `๊ฒฝ๊ธฐ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ˜ํ™˜ํ•ด์ฃผ๋Š” ๋ฉ”์†Œ๋“œ`๋‹ˆ๊นŒ ์ด๋ฆ„์„ ๋ณ€๊ฒฝํ•ด์ฃผ์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์ถ”๊ฐ€๋กœ `Rule`์ด ์‚ฌ์šฉ์ž์™€ ๋”œ๋Ÿฌ๋ฅผ ๋ชจ๋‘ ๋ฐ›์•„ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ˜ํ™˜ํ•ด์ฃผ๋Š”๊ฒŒ ์—ญํ• ์ด ์ ์ ˆํ•˜์ง€ ์•Š์„๊นŒ์š”? (ํ˜„์žฌ์˜ rule.compare๊ณผ getWinningResult๋ฅผ ํ•ฉ์นœ ๋ฉ”์†Œ๋“œ๋ฅผ Rule์—์„œ ์ œ๊ณตํ•˜๋ฉด ์–ด๋–จ๊นŒ์š”?)
@@ -0,0 +1,27 @@ +package blackjack.domain.participant; + +import lombok.Getter; + +@Getter +public class Player extends Participant { + + private static final int PLAYER_DRAW_THRESHOLD = 21; + private static final String DEALER_NAME = "๋”œ๋Ÿฌ"; + private static final String CHECK_SAME_NAME_AS_DEALER = "์ด๋ฆ„์€ ๋”œ๋Ÿฌ์™€ ๊ฐ™์„ ์ˆ˜ ์—†์œผ๋‹ˆ ๋‹ค๋ฅธ ์ด๋ฆ„์„ ์ง€์ •ํ•ด์ฃผ์„ธ์š”."; + + public Player(String name) { + super(name); + validateDealerNameDuplicated(name); + } + + private void validateDealerNameDuplicated(String name) { + if (name.equals(DEALER_NAME)) { + throw new IllegalArgumentException(CHECK_SAME_NAME_AS_DEALER); + } + } + + @Override + public boolean drawable() { + return getCardsSum() < PLAYER_DRAW_THRESHOLD; + } +}
Java
`๋กœ์ง์ƒ ์—†์„ ์ˆ˜๊ฐ€ ์—†๋‹ค` ๋ผ๋Š” ์ƒ๊ฐ์œผ๋กœ `get`์„ ์‚ฌ์šฉํ•ด์ฃผ์‹  ๊ฒƒ ๊ฐ™์•„์š”. ๋‹ค๋งŒ ์š”๊ฒŒ ์—†๋Š” ๊ฒฝ์šฐ์—๋Š” `NullPoint`๊ฐ€ ๋‚ ํ…๋ฐ์š”. ์ด ๋ฉ”์‹œ์ง€๋ฅผ ๋ณด๊ณ  ์–ด๋–ค ์˜๋ฏธ์ธ์ง€ ์ฐพ๊ธฐ๊ฐ€ ์–ด๋ ค์šธ ๊ฒƒ ๊ฐ™์•„์š”. ์š”๋ ‡๊ฒŒ ์• ๋งคํ•œ ๊ฒฝ์šฐ์— ์ €๋Š” orElseThrow๋ฅผ ํ•œ๋‹ค๊ฑฐ๋‚˜, ๋กœ๊ทธ๋ฅผ ํ†ตํ•ด์„œ ํ”„๋กœ๊ทธ๋žจ ์ž์ฒด๊ฐ€ ์ž˜๋ชป๋˜์—ˆ์Œ์„ ์•Œ๋ ค์ฃผ๋Š” ํ˜•ํƒœ๋กœ ๋‚จ๊ธฐ๋Š” ํŽธ์ด์—์š”.
@@ -0,0 +1,50 @@ +package blackjack.domain.result; + +import blackjack.domain.participant.Dealer; +import blackjack.domain.participant.Player; +import lombok.Getter; + +import java.util.Arrays; +import java.util.function.BiFunction; + +public enum Rule{ + // ์นด๋“œ ๊ฐ’์˜ ํ•ฉ์ด 21์„ ๋„˜์œผ๋ฉด ์ŠนํŒจ ๊ฒฐ์ • (ํ”Œ๋ ˆ์ด์–ด ๊ธฐ์ค€์œผ๋กœ ์„ ์–ธ) + PLAYER_BUST(((player, dealer) -> player.isBust()), WinningResult.LOSE, 1), + DEALER_BUST(((player, dealer) -> dealer.isBust()), WinningResult.WIN, 2), + + // ์นด๋“œ ๊ฐ’์˜ ํ•ฉ์ด 21์„ ๋„˜์ง€ ์•Š์œผ๋ฉด์„œ, ๊ฐ’์ด ๋” ํฐ์ชฝ์ด ์ŠนํŒจ๊ฒฐ์ •(์ด๋ฏธ ์—ฌ๊ธฐ์„œ ๊ฒฐ์ •, BlackJack ์ฒดํฌ ํ•„์š”์—†์Œ) + PLAYER_HIGHER(((player, dealer) -> player.getCardsSum() > dealer.getCardsSum()), WinningResult.WIN, 3), + DEALER_HIGHER(((player, dealer) -> player.getCardsSum() < dealer.getCardsSum()), WinningResult.LOSE, 4), + + // ๋ฌด์Šน๋ถ€ ๊ฒฐ์ • + TIES(((player, dealer) -> player.getCardsSum() == dealer.getCardsSum()), WinningResult.TIE, 5); + + private BiFunction<Player, Dealer, Boolean> compare; + private WinningResult winningResult; + @Getter + private int verificationOrder; + + Rule(BiFunction<Player, Dealer, Boolean> compare, WinningResult winningResult, int verificationOrder) { + this.compare = compare; + this.winningResult = winningResult; + this.verificationOrder = verificationOrder; + } + + public Boolean findMatchingRule(Player player, Dealer dealer) { + return compare.apply(player, dealer); + } + + public WinningResult getWinningResult() { + return winningResult; + } + + public static WinningResult resultPlayerVersusDealer(Player player, Dealer dealer) { + + return Arrays.stream(Rule.values()) + .sorted(new RuleComparator()) + .filter(rule -> rule.findMatchingRule(player, dealer)) + .findFirst() + .orElseThrow(() -> new RuntimeException("์ผ์น˜ํ•˜๋Š” ๊ฒฐ๊ณผ๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")) + .getWinningResult(); + } +}
Java
์š” ๋กœ์ง๋“ค์ด ์ˆœ์„œ์— ๋”ฐ๋ผ ์˜ํ–ฅ์„ ๋ฐ›์„ ๊ฒƒ ๊ฐ™์•„์š”. `์›๋ž˜๋Š” ํ”Œ๋ ˆ์ด์–ด๊ฐ€ ๋ฒ„์ŠคํŠธ์ธ ๊ฒฝ์šฐ ํ•ญ์ƒ ํŒจ๋ฐฐ๋กœ ๊ฐ„์ฃผ๋˜๋Š”๋ฐ ๋ฌด์Šน๋ถ€ Enum์„ ๋งจ ์œ„๋กœ ์˜ฌ๋ฆฌ๋ฉด, ๋น„๊ธด๊ฑฐ๋กœ ๊ฐ„์ฃผ๋˜๋Š” ํ˜•์‹`์œผ๋กœ์—ฌ! ๊ทธ๋ ‡๋‹ค๋ฉด ๊ธฐ์กด `Enum์˜ ์ˆœ์„œ๊ฐ€ ์ค‘์š”ํ•˜๋‹ค`๋Š” ๊ฒƒ์„ ๋ช…์‹œ์ ์œผ๋กœ ๋“œ๋Ÿฌ๋‚ด๊ฑฐ๋‚˜, ๋‹ค๋ฅธ ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•ด์ค˜์•ผ ๋‹ค๋ฅธ ์‚ฌ๋žŒ์ด ์‹ค์ˆ˜ํ•  ์—ฌ์ง€๋ฅผ ์ค„์ผ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”ใ…Žใ…Ž(์—ฌ๊ธด ๊ฐ€์žฅ ์ค‘์š”ํ•œ ๋กœ์ง์ด๋‹ˆ๊นŒ ๋”๋”์šฑ์ด์š”!)
@@ -0,0 +1,50 @@ +package blackjack.domain.result; + +import blackjack.domain.participant.Dealer; +import blackjack.domain.participant.Player; +import lombok.Getter; + +import java.util.Arrays; +import java.util.function.BiFunction; + +public enum Rule{ + // ์นด๋“œ ๊ฐ’์˜ ํ•ฉ์ด 21์„ ๋„˜์œผ๋ฉด ์ŠนํŒจ ๊ฒฐ์ • (ํ”Œ๋ ˆ์ด์–ด ๊ธฐ์ค€์œผ๋กœ ์„ ์–ธ) + PLAYER_BUST(((player, dealer) -> player.isBust()), WinningResult.LOSE, 1), + DEALER_BUST(((player, dealer) -> dealer.isBust()), WinningResult.WIN, 2), + + // ์นด๋“œ ๊ฐ’์˜ ํ•ฉ์ด 21์„ ๋„˜์ง€ ์•Š์œผ๋ฉด์„œ, ๊ฐ’์ด ๋” ํฐ์ชฝ์ด ์ŠนํŒจ๊ฒฐ์ •(์ด๋ฏธ ์—ฌ๊ธฐ์„œ ๊ฒฐ์ •, BlackJack ์ฒดํฌ ํ•„์š”์—†์Œ) + PLAYER_HIGHER(((player, dealer) -> player.getCardsSum() > dealer.getCardsSum()), WinningResult.WIN, 3), + DEALER_HIGHER(((player, dealer) -> player.getCardsSum() < dealer.getCardsSum()), WinningResult.LOSE, 4), + + // ๋ฌด์Šน๋ถ€ ๊ฒฐ์ • + TIES(((player, dealer) -> player.getCardsSum() == dealer.getCardsSum()), WinningResult.TIE, 5); + + private BiFunction<Player, Dealer, Boolean> compare; + private WinningResult winningResult; + @Getter + private int verificationOrder; + + Rule(BiFunction<Player, Dealer, Boolean> compare, WinningResult winningResult, int verificationOrder) { + this.compare = compare; + this.winningResult = winningResult; + this.verificationOrder = verificationOrder; + } + + public Boolean findMatchingRule(Player player, Dealer dealer) { + return compare.apply(player, dealer); + } + + public WinningResult getWinningResult() { + return winningResult; + } + + public static WinningResult resultPlayerVersusDealer(Player player, Dealer dealer) { + + return Arrays.stream(Rule.values()) + .sorted(new RuleComparator()) + .filter(rule -> rule.findMatchingRule(player, dealer)) + .findFirst() + .orElseThrow(() -> new RuntimeException("์ผ์น˜ํ•˜๋Š” ๊ฒฐ๊ณผ๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")) + .getWinningResult(); + } +}
Java
์นœ์ ˆํ•œ ์ฃผ์„ ์ข‹๋„ค์š”. ํ•ด๋‹น ๋ฉ”์†Œ๋“œ๋Š” participant์—๊ฒŒ ๊ฐ’์„ ๋น„๊ตํ•˜๋Š” ํ˜•ํƒœ๋กœ ๋ฆฌํŒฉํ† ๋งํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”
@@ -0,0 +1,50 @@ +package blackjack.domain.result; + +import blackjack.domain.participant.Dealer; +import blackjack.domain.participant.Player; +import lombok.Getter; + +import java.util.Arrays; +import java.util.function.BiFunction; + +public enum Rule{ + // ์นด๋“œ ๊ฐ’์˜ ํ•ฉ์ด 21์„ ๋„˜์œผ๋ฉด ์ŠนํŒจ ๊ฒฐ์ • (ํ”Œ๋ ˆ์ด์–ด ๊ธฐ์ค€์œผ๋กœ ์„ ์–ธ) + PLAYER_BUST(((player, dealer) -> player.isBust()), WinningResult.LOSE, 1), + DEALER_BUST(((player, dealer) -> dealer.isBust()), WinningResult.WIN, 2), + + // ์นด๋“œ ๊ฐ’์˜ ํ•ฉ์ด 21์„ ๋„˜์ง€ ์•Š์œผ๋ฉด์„œ, ๊ฐ’์ด ๋” ํฐ์ชฝ์ด ์ŠนํŒจ๊ฒฐ์ •(์ด๋ฏธ ์—ฌ๊ธฐ์„œ ๊ฒฐ์ •, BlackJack ์ฒดํฌ ํ•„์š”์—†์Œ) + PLAYER_HIGHER(((player, dealer) -> player.getCardsSum() > dealer.getCardsSum()), WinningResult.WIN, 3), + DEALER_HIGHER(((player, dealer) -> player.getCardsSum() < dealer.getCardsSum()), WinningResult.LOSE, 4), + + // ๋ฌด์Šน๋ถ€ ๊ฒฐ์ • + TIES(((player, dealer) -> player.getCardsSum() == dealer.getCardsSum()), WinningResult.TIE, 5); + + private BiFunction<Player, Dealer, Boolean> compare; + private WinningResult winningResult; + @Getter + private int verificationOrder; + + Rule(BiFunction<Player, Dealer, Boolean> compare, WinningResult winningResult, int verificationOrder) { + this.compare = compare; + this.winningResult = winningResult; + this.verificationOrder = verificationOrder; + } + + public Boolean findMatchingRule(Player player, Dealer dealer) { + return compare.apply(player, dealer); + } + + public WinningResult getWinningResult() { + return winningResult; + } + + public static WinningResult resultPlayerVersusDealer(Player player, Dealer dealer) { + + return Arrays.stream(Rule.values()) + .sorted(new RuleComparator()) + .filter(rule -> rule.findMatchingRule(player, dealer)) + .findFirst() + .orElseThrow(() -> new RuntimeException("์ผ์น˜ํ•˜๋Š” ๊ฒฐ๊ณผ๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")) + .getWinningResult(); + } +}
Java
ํ•ด๋‹น ๋ฉ”์†Œ๋“œ๋Š” ๋น„๊ตํ•˜๋Š” ๋ฉ”์†Œ๋“œ๊ฐ€ ์•„๋‹ˆ๋ผ, ์–ด๋–ค Rule์ธ์ง€๋ฅผ ์ฐพ๋Š”๊ฑฐ์— ๊ฐ€๊น๋„ค์š”. ์š”๊ฒƒ๋„ ๋ฉ”์†Œ๋“œ ์ด๋ฆ„ ์ˆ˜์ •ํ•ด์ฃผ์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”.
@@ -0,0 +1,27 @@ +package blackjack.domain.result; + +import lombok.Getter; + +@Getter +public enum WinningResult { + + WIN("์Šน"), + LOSE("ํŒจ"), + TIE("๋ฌด์Šน๋ถ€"); + + private final String result; + + WinningResult(String result) { + this.result = result; + } + + public WinningResult reverse() { + if (this == WIN) { + return LOSE; + } + if (this == LOSE) { + return WIN; + } + return TIE; + } +}
Java
์š”๊ฑฐ ์ œ๊ฐ€ ์ „์— ํ•  ๋•Œ, ์•ˆ ๋๋˜๊ฑด๋ฐ WinningResult๊ฐ€ WinningResult ๋ฉค๋ฒ„๋ณ€์ˆ˜๋ฅผ ๊ฐ€์ง€๊ณ , ๋ฐ˜๋Œ€๋กœ ์„ ์–ธํ•˜๋ฉด ์•ˆ๋˜๋”๋ผ๊ตฌ์š”. ์™œ ์•ˆ๋˜๋Š”์ง€ ๋ฐ”๋กœ ์ดํ•ด๊ฐ€์‹œ๋ฉด Enum์„ ์ž˜ ์ดํ•ดํ•˜๊ณ  ๊ณ„์‹  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹คใ…‹ใ…‹ใ…‹ ```java WIN("์Šน", LOST) // ์š”๋Ÿฐ์‹์œผ๋กœ์—ฌ ```
@@ -0,0 +1,66 @@ +package blackjack.controller; + +import blackjack.domain.card.Deck; +import blackjack.domain.participant.Dealer; +import blackjack.domain.participant.Player; +import blackjack.domain.participant.PlayersFactory; +import blackjack.domain.result.GameResult; +import blackjack.dto.DrawCardRequestDto; +import blackjack.dto.PlayersNameInputDto; +import blackjack.view.InputView; +import blackjack.view.OutputView; + +import java.util.List; + +public class BlackJackController { + private final InputView inputView = new InputView(); + private final OutputView outputView = new OutputView(); + + public void run() { + PlayersNameInputDto namesInput = inputView.getPlayersName(); + Dealer dealer = new Dealer(); + Deck deck = new Deck(); + List<Player> players = PlayersFactory.createPlayers(namesInput.getPlayersName()); + + drawTowCards(dealer, players, deck); + drawCardToPlayers(players, deck); + drawCardToDealer(dealer, deck); + outputView.printCardsResult(dealer, players); + outputView.printGameResult(GameResult.of(dealer, players)); + } + + private void drawTowCards(Dealer dealer, List<Player> players, Deck deck) { + for (Player player : players) { + player.receiveCard(deck.drawCard()); + player.receiveCard(deck.drawCard()); + } + dealer.receiveCard(deck.drawCard()); + dealer.receiveCard(deck.drawCard()); + outputView.printFirstCardsGiven(players, dealer); + outputView.printDealerCard(dealer); + outputView.printPlayersCard(players); + } + + private void drawCardToPlayers(List<Player> players, Deck deck) { + for (Player player : players) { + drawCardToPlayer(player, deck); + } + } + + private void drawCardToPlayer(Player player, Deck deck) { + DrawCardRequestDto drawCardRequest = inputView.getPlayersResponse(player); + while (player.drawable() && drawCardRequest.isYes()) { + player.receiveCard(deck.drawCard()); + + outputView.printCards(player); + drawCardRequest = inputView.getPlayersResponse(player); + } + } + + private void drawCardToDealer(Dealer dealer, Deck deck) { + while (dealer.drawable()) { + dealer.receiveCard(deck.drawCard()); + outputView.printDealerCardGiven(); + } + } +}
Java
์—ฌ๋Ÿฌ๋ช…์ด ๋™์‹œ์— ์š”์ฒญํ•˜๋Š” ๊ฒฝ์šฐ๋ฅผ ๊ณ ๋ คํ•˜์ง€ ์•Š์•˜๋„ค์š”. ์„œ๋น„์Šค ๊ฐœ๋ฐœ์ž๋กœ์„œ ํ•ญ์ƒ ์ƒ๊ฐํ•ด์•ผ ํ•  ๋ถ€๋ถ„์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. view๋ฅผ ์ œ์™ธํ•œ ํด๋ž˜์Šค๋ณ€์ˆ˜๋“ค์„ ๋กœ์ปฌ๋ณ€์ˆ˜๋กœ ์ˆ˜์ •ํ–ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,66 @@ +package blackjack.controller; + +import blackjack.domain.card.Deck; +import blackjack.domain.participant.Dealer; +import blackjack.domain.participant.Player; +import blackjack.domain.participant.PlayersFactory; +import blackjack.domain.result.GameResult; +import blackjack.dto.DrawCardRequestDto; +import blackjack.dto.PlayersNameInputDto; +import blackjack.view.InputView; +import blackjack.view.OutputView; + +import java.util.List; + +public class BlackJackController { + private final InputView inputView = new InputView(); + private final OutputView outputView = new OutputView(); + + public void run() { + PlayersNameInputDto namesInput = inputView.getPlayersName(); + Dealer dealer = new Dealer(); + Deck deck = new Deck(); + List<Player> players = PlayersFactory.createPlayers(namesInput.getPlayersName()); + + drawTowCards(dealer, players, deck); + drawCardToPlayers(players, deck); + drawCardToDealer(dealer, deck); + outputView.printCardsResult(dealer, players); + outputView.printGameResult(GameResult.of(dealer, players)); + } + + private void drawTowCards(Dealer dealer, List<Player> players, Deck deck) { + for (Player player : players) { + player.receiveCard(deck.drawCard()); + player.receiveCard(deck.drawCard()); + } + dealer.receiveCard(deck.drawCard()); + dealer.receiveCard(deck.drawCard()); + outputView.printFirstCardsGiven(players, dealer); + outputView.printDealerCard(dealer); + outputView.printPlayersCard(players); + } + + private void drawCardToPlayers(List<Player> players, Deck deck) { + for (Player player : players) { + drawCardToPlayer(player, deck); + } + } + + private void drawCardToPlayer(Player player, Deck deck) { + DrawCardRequestDto drawCardRequest = inputView.getPlayersResponse(player); + while (player.drawable() && drawCardRequest.isYes()) { + player.receiveCard(deck.drawCard()); + + outputView.printCards(player); + drawCardRequest = inputView.getPlayersResponse(player); + } + } + + private void drawCardToDealer(Dealer dealer, Deck deck) { + while (dealer.drawable()) { + dealer.receiveCard(deck.drawCard()); + outputView.printDealerCardGiven(); + } + } +}
Java
Dto ์ด๋ฆ„์„ DrawCardRequestDto๋กœ ๋ณ€๊ฒฝํ•˜๊ณ  ํŒ๋‹จ๋กœ์ง์„ Dto๋กœ ์ด๋™ํ–ˆ์Šต๋‹ˆ๋‹ค. Dto๊ฐ€ ๊ฐ€์ง„ ๋ฐ์ดํ„ฐ๋งŒ์„ ์ด์šฉํ•œ ๊ฐ„๋‹จํ•œ ๋กœ์ง์€ Dto์—์„œ ์ฒ˜๋ฆฌํ•ด๋„ ๋œ๋‹ค๋Š” ๊ฒƒ์„ ์•Œ๊ฒŒ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. Dto ์ด๋ฆ„์„ ๋ฐ›์•„์˜จ ๊ฒƒ์ธ์ง€, ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ์ธ์ง€์— ๋”ฐ๋ผ ํ†ต์ผํ•˜๋ฉด ์ผ๊ด€์„ฑ์ด ์žˆ์–ด ํ—ท๊ฐˆ๋ฆด ์ผ์ด ์—†์–ด์„œ ์ข‹์€ ๋ฐฉ๋ฒ•์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,17 @@ +package blackjack.utils; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class StringUtil { + private static final String COMMA = ","; + private static final String RESPONSE_RESTRICT_MESSAGE = "y ํ˜น์€ n ๋งŒ ์ž…๋ ฅํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค."; + + public static List<String> splitByComma(String input) { + List<String> names = Arrays.asList(input.split(COMMA)); + return names.stream() + .map(String::trim) + .collect(Collectors.toList()); + } +}
Java
๋กœ์ง์„ DrawCardRequestDto๋กœ ์ด๋™ํ–ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,32 @@ +package blackjack.domain.card; + +import blackjack.domain.card.strategy.DrawStrategy; +import blackjack.domain.card.strategy.RandomDrawStrategy; +import lombok.Getter; + +import java.util.LinkedList; +import java.util.List; + +public class Deck { + + private static final String ALERT_NO_CARD_LEFT = "์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์นด๋“œ๋ฅผ ๋ชจ๋‘ ์†Œ์ง„ํ•˜์˜€์Šต๋‹ˆ๋‹ค."; + + @Getter + private final List<Card> deck; + + public Deck() { + this.deck = new LinkedList<>(DeckFactory.createDeck()); + } + + public Card drawCard() { + if (deck.isEmpty()) { + throw new RuntimeException(ALERT_NO_CARD_LEFT); + } + return deck.remove(generateNextDrawCardIndex(new RandomDrawStrategy())); + } + + private int generateNextDrawCardIndex(DrawStrategy drawStrategy) { + return drawStrategy.getNextIndex(deck); + } + +}
Java
๋„ต ๊ทธ๋ ‡์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,32 @@ +package blackjack.domain.card; + +import blackjack.domain.card.strategy.DrawStrategy; +import blackjack.domain.card.strategy.RandomDrawStrategy; +import lombok.Getter; + +import java.util.LinkedList; +import java.util.List; + +public class Deck { + + private static final String ALERT_NO_CARD_LEFT = "์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์นด๋“œ๋ฅผ ๋ชจ๋‘ ์†Œ์ง„ํ•˜์˜€์Šต๋‹ˆ๋‹ค."; + + @Getter + private final List<Card> deck; + + public Deck() { + this.deck = new LinkedList<>(DeckFactory.createDeck()); + } + + public Card drawCard() { + if (deck.isEmpty()) { + throw new RuntimeException(ALERT_NO_CARD_LEFT); + } + return deck.remove(generateNextDrawCardIndex(new RandomDrawStrategy())); + } + + private int generateNextDrawCardIndex(DrawStrategy drawStrategy) { + return drawStrategy.getNextIndex(deck); + } + +}
Java
DrawStrategy ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ๋งŒ๋“ค๊ณ  ๊ทธ๊ฒƒ์„ ๊ตฌํ˜„ํ•˜๋Š” RandomDrawStrategy ํด๋ž˜์Šค๋ฅผ ๋งŒ๋“ค์—ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,39 @@ +package blackjack.domain.card; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class DeckFactory { + + private static final List<Card> cardsDeck; + + static { + cardsDeck = createCardsDeck(); + } + + private static List<Card> createCardsDeck() { + List<Card> cards = new ArrayList<>(); + + for (Denomination denomination : Denomination.values()) { + cards.addAll(createCards(denomination)); + } + return cards; + } + + private static List<Card> createCards(Denomination denomination) { + List<Card> cards = new ArrayList<>(); + + for (Type type : Type.values()) { + cards.add(new Card(denomination, type)); + } + + return cards; + } + + public static List<Card> createDeck() { + return Collections.unmodifiableList(cardsDeck); + } +} + +
Java
์Šคํƒœํ‹ฑ๋ธ”๋ก์œผ๋กœ ๋ณ€๊ฒฝํ–ˆ์Šต๋‹ˆ๋‹ค. ๊ธฐ๋Šฅ์€ ๋“ฑํ˜ธ๋ฅผ ์‚ฌ์šฉํ•œ ์ฝ”๋“œ์™€ ์ •ํ™•ํžˆ ๋™์ผํ•œ๊ฑด๊ฐ€์š”?
@@ -0,0 +1,38 @@ +package blackjack.domain.card; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class CardTest { + + @DisplayName("์นด๋“œ ๊ฐ์ฒด์˜ ์ˆซ์ž์™€ ์ข…๋ฅ˜๊ฐ’์ด ๊ฐ™์œผ๋ฉด ๊ฐ™์€ ๊ฐ์ฒด๋กœ ํŒ๋‹จํ•œ๋‹ค") + @Test + void equalsTest() { + //given, when, then + assertThat(new Card(Denomination.TWO, Type.DIAMOND)) + .isEqualTo(new Card(Denomination.TWO, Type.DIAMOND)); + + } + + @DisplayName("์นด๋“œ ๊ฐ์ฒด์˜ ์ˆซ์ž์™€ ์ข…๋ฅ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค") + @Test + void printCardTwoDiamond() { + //given + Card card = new Card(Denomination.TWO, Type.DIAMOND); + + //when, then + assertThat(card).hasToString("2๋‹ค์ด์•„๋ชฌ๋“œ"); + } + + @DisplayName("์นด๋“œ ๊ฐ์ฒด์˜ ์ˆซ์ž์™€ ์ข…๋ฅ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค") + @Test + void printCardAceHeart() { + //given + Card card = new Card(Denomination.ACE, Type.HEART); + + //when, then + assertThat(card.toString()).isEqualTo("Aํ•˜ํŠธ"); + } +}
Java
assert๋ฌธ์œผ๋กœ ๋ฌธ์ž์—ด์„ ๋น„๊ตํ•  ๋•Œ๋Š” hasToString๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,102 @@ +package blackjack.domain.participant; + +import blackjack.domain.card.Card; +import blackjack.domain.card.Denomination; +import lombok.Getter; +import org.apache.commons.lang3.StringUtils; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +@Getter +public abstract class Participant { + private static final int DIFFERENCE_OF_ACE_SCORE = 10; + private static final int BLACKJACK = 21; + private static final int ZERO = 0; + private static final String CHECK_NULL_OR_EMPTY = "์ด๋ฆ„์ด ๋นˆ ์นธ ํ˜น์€ null ๊ฐ’์ด ์•„๋‹Œ์ง€ ํ™•์ธํ•ด์ฃผ์„ธ์š”."; + private static final String CHECK_CONTAINING_ONLY_LETTERS_AND_DIGITS = "์ด๋ฆ„์€ ํŠน์ˆ˜๋ฌธ์ž๋ฅผ ํฌํ•จํ•˜์ง€ ์•Š์€ ๋ฌธ์ž์™€ ์ˆซ์ž๋กœ ์ง€์ •ํ•ด์ฃผ์„ธ์š”."; + + private final String name; + private final List<Card> cards; + + protected Participant(String name) { + validateName(name); + + this.name = name; + this.cards = new ArrayList<>(); + } + + private void validateName(String name) { + validateNullOrEmpty(name); + validateAlphaNumeric(name); + } + + private void validateNullOrEmpty(String name) { + if (StringUtils.isBlank(name)) { + throw new IllegalArgumentException(CHECK_NULL_OR_EMPTY); + } + } + + private void validateAlphaNumeric(String name) { + if (!StringUtils.isAlphanumericSpace(name)) { + throw new IllegalArgumentException(CHECK_CONTAINING_ONLY_LETTERS_AND_DIGITS); + } + } + + protected abstract boolean drawable(); + + public void receiveCard(Card card) { + cards.add(card); + } + + public int getCardsSum() { + int scoreOfAceAsEleven = sumOfCardsScore(); + int aceCount = getAceCount(); + + while (canCountAceAsOne(scoreOfAceAsEleven, aceCount)) { + scoreOfAceAsEleven = scoreOfAceAsOne(scoreOfAceAsEleven); + aceCount--; + } + + return scoreOfAceAsEleven; + } + + private int scoreOfAceAsOne(int scoreOfAceAsEleven) { + return scoreOfAceAsEleven - DIFFERENCE_OF_ACE_SCORE; + } + + private boolean canCountAceAsOne(int scoreOfAceAsEleven, int aceCount) { + return scoreOfAceAsEleven > BLACKJACK && aceCount > ZERO; + } + + private int getAceCount() { + return (int) cards.stream() + .filter(Card::isAce) + .count(); + } + + private int sumOfCardsScore() { + return cards.stream() + .map(Card::getDenomination) + .mapToInt(Denomination::getScore) + .sum(); + } + + public boolean isBust() { + return getCardsSum() > BLACKJACK; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Participant that = (Participant) o; + return Objects.equals(name, that.name) && Objects.equals(cards, that.cards); + } + + @Override + public int hashCode() { + return Objects.hash(name, cards); + } +}
Java
์ด ๋ถ€๋ถ„ ์ดํ•ด๊ฐ€ ์ž˜ ์•ˆ ๋˜๋Š”๋ฐ์š”, ์ œ ์ƒ๊ฐ์—๋Š” Participant๊ฐ€ ๊ฐ€์ง„ ์นด๋“œ ๋ชฉ๋ก์— ๋”ฐ๋ผ ์—์ด์Šค๋ฅผ 1๋กœ ๊ณ„์‚ฐํ•  ์ง€, 11๋กœ ๊ณ„์‚ฐํ•  ์ง€ ๋‹ค๋ฅด๊ฒŒ ํŒ๋‹จํ•ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— Participant์˜ ๋กœ์ง์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. Denomination ์™ธ๋ถ€์˜ ์กฐ๊ฑด์— ๋”ฐ๋ผ 1 ํ˜น์€ 11๋กœ ๊ณ„์‚ฐ๋˜๊ธฐ ๋•Œ๋ฌธ์— Denomination์„ ํฌํ•จํ•œ ์ƒ์œ„ ๊ตฌ์กฐ์—์„œ ๊ฒฐ์ •ํ•˜๋Š” ๊ฒŒ ๋งž๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. Denomination์— score๋ฅผ 1๋กœ ๊ฐ€์ง€๋Š” enum์„ ์ถ”๊ฐ€ํ•ด์„œ ๋ฆฌํŒฉํ† ๋ง์„ ์‹œ๋„ํ•ด๋ดค๋Š”๋ฐ ์–ด๋–ป๊ฒŒ ํ•ด์•ผ ํ•  ์ง€ ์ž˜ ๋ชจ๋ฅด๊ฒ ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,27 @@ +package blackjack.domain.participant; + +import lombok.Getter; + +@Getter +public class Player extends Participant { + + private static final int PLAYER_DRAW_THRESHOLD = 21; + private static final String DEALER_NAME = "๋”œ๋Ÿฌ"; + private static final String CHECK_SAME_NAME_AS_DEALER = "์ด๋ฆ„์€ ๋”œ๋Ÿฌ์™€ ๊ฐ™์„ ์ˆ˜ ์—†์œผ๋‹ˆ ๋‹ค๋ฅธ ์ด๋ฆ„์„ ์ง€์ •ํ•ด์ฃผ์„ธ์š”."; + + public Player(String name) { + super(name); + validateDealerNameDuplicated(name); + } + + private void validateDealerNameDuplicated(String name) { + if (name.equals(DEALER_NAME)) { + throw new IllegalArgumentException(CHECK_SAME_NAME_AS_DEALER); + } + } + + @Override + public boolean drawable() { + return getCardsSum() < PLAYER_DRAW_THRESHOLD; + } +}
Java
๋ง์”€ํ•˜์‹  ๋ถ€๋ถ„์ด ๋งž๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. ๋ฌธ์ž์—ด ์ƒ์„ฑ ๋กœ์ง์„ view๋กœ ์ด๋™ํ–ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,27 @@ +package blackjack.domain.participant; + +import lombok.Getter; + +@Getter +public class Player extends Participant { + + private static final int PLAYER_DRAW_THRESHOLD = 21; + private static final String DEALER_NAME = "๋”œ๋Ÿฌ"; + private static final String CHECK_SAME_NAME_AS_DEALER = "์ด๋ฆ„์€ ๋”œ๋Ÿฌ์™€ ๊ฐ™์„ ์ˆ˜ ์—†์œผ๋‹ˆ ๋‹ค๋ฅธ ์ด๋ฆ„์„ ์ง€์ •ํ•ด์ฃผ์„ธ์š”."; + + public Player(String name) { + super(name); + validateDealerNameDuplicated(name); + } + + private void validateDealerNameDuplicated(String name) { + if (name.equals(DEALER_NAME)) { + throw new IllegalArgumentException(CHECK_SAME_NAME_AS_DEALER); + } + } + + @Override + public boolean drawable() { + return getCardsSum() < PLAYER_DRAW_THRESHOLD; + } +}
Java
orElseThrow๋กœ ์ˆ˜์ •ํ•˜๊ณ , ๋ฉ”์„ธ์ง€๋ฅผ ๋‹ด์€ ์˜ˆ์™ธ๋ฅผ ๋˜์ง€๋„๋ก ํ–ˆ์Šต๋‹ˆ๋‹ค.
@@ -1,16 +1,28 @@ package webserver; -import java.io.DataOutputStream; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import webserver.controller.*; +import webserver.domain.HttpRequest; +import webserver.domain.HttpResponse; + import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import java.util.HashMap; +import java.util.Map; public class RequestHandler implements Runnable { private static final Logger logger = LoggerFactory.getLogger(RequestHandler.class); + private static final Map<String, Controller> controllers = new HashMap<>(); + + static { + controllers.put("/user/create", new CreateUserController()); + controllers.put("/user/login", new LoginController()); + controllers.put("/user/list", new ListUserController()); + controllers.put("/user/list.html", new ListUserController()); + } private Socket connection; @@ -21,35 +33,12 @@ public RequestHandler(Socket connectionSocket) { public void run() { logger.debug("New Client Connect! Connected IP : {}, Port : {}", connection.getInetAddress(), connection.getPort()); - try (InputStream in = connection.getInputStream(); OutputStream out = connection.getOutputStream()) { - // TODO ์‚ฌ์šฉ์ž ์š”์ฒญ์— ๋Œ€ํ•œ ์ฒ˜๋ฆฌ๋Š” ์ด ๊ณณ์— ๊ตฌํ˜„ํ•˜๋ฉด ๋œ๋‹ค. - DataOutputStream dos = new DataOutputStream(out); - byte[] body = "Hello World".getBytes(); - response200Header(dos, body.length); - responseBody(dos, body); - } catch (IOException e) { - logger.error(e.getMessage()); - } - } - - private void response200Header(DataOutputStream dos, int lengthOfBodyContent) { - try { - dos.writeBytes("HTTP/1.1 200 OK \r\n"); - dos.writeBytes("Content-Type: text/html;charset=utf-8\r\n"); - dos.writeBytes("Content-Length: " + lengthOfBodyContent + "\r\n"); - dos.writeBytes("\r\n"); - } catch (IOException e) { - logger.error(e.getMessage()); - } - } - - private void responseBody(DataOutputStream dos, byte[] body) { - try { - dos.write(body, 0, body.length); - dos.flush(); + HttpRequest httpRequest = new HttpRequest(in); + HttpResponse httpResponse = new HttpResponse(out); + controllers.getOrDefault(httpRequest.getPath(), new DefaultController()).service(httpRequest, httpResponse); } catch (IOException e) { logger.error(e.getMessage()); } } -} +} \ No newline at end of file
Java
path์— ๋งž๋Š” Controller ์ •์˜ ์ข‹์Šต๋‹ˆ๋‹ค ๐Ÿ‘
@@ -0,0 +1,80 @@ +package webserver.controller; + +import webserver.domain.HttpRequest; +import webserver.domain.HttpResponse; +import webserver.domain.HttpStatusCode; +import webserver.exceptions.InvalidRequestException; +import webserver.exceptions.NotYetSentException; + +public abstract class AbstractController implements Controller { + + public void service(HttpRequest request, HttpResponse response) { + try { + System.out.println(request.getMethod().name() + " " + request.getPath()); + methodMapping(request, response); + } catch (Exception e) { + if(!response.isSent()){ + System.out.println("์ž์‹ ์ปจํŠธ๋กค๋Ÿฌ์—์„œ ์ฒ˜๋ฆฌ ๋ˆ„๋ฝ๋œ ์˜ˆ์™ธ ์ƒํ™ฉ : " + e.getMessage()); + e.printStackTrace(); + response.send(HttpStatusCode.NOT_IMPLEMENTED, e.getMessage()); + } + } finally { + if (!response.isSent()) { + response.send(HttpStatusCode.INTERNAL_SERVER_ERROR); + throw new NotYetSentException("response์˜ ๋ฉ”์„œ๋“œ send()๊ฐ€ ํ˜ธ์ถœ๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค"); + } + } + } + + private void methodMapping(HttpRequest request, HttpResponse response) { + switch (request.getMethod()) { + case GET: + validateGetRequest(request, response); + doGet(request, response); + return; + case POST: + validatePostRequest(request, response); + doPost(request, response); + return; + case PUT: + validatePutRequest(request, response); + doPut(request, response); + return; + case DELETE: + validateDeleteRequest(request, response); + doDelete(request, response); + return; + default: + response.send(HttpStatusCode.METHOD_NOT_ALLOWED); + } + } + + public void doPost(HttpRequest request, HttpResponse response) { + response.send(HttpStatusCode.METHOD_NOT_ALLOWED); + } + + public void doGet(HttpRequest request, HttpResponse response) { + response.send(HttpStatusCode.METHOD_NOT_ALLOWED); + } + + public void doPut(HttpRequest request, HttpResponse response) { + response.send(HttpStatusCode.METHOD_NOT_ALLOWED); + } + + public void doDelete(HttpRequest request, HttpResponse response) { + response.send(HttpStatusCode.METHOD_NOT_ALLOWED); + } + + // ํ•„์š”์‹œ์— ์˜ค๋ฒ„๋ผ์ด๋”ฉ ํ•˜์—ฌ ์ธํ’‹๊ฐ’์„ ๊ฒ€์ฆํ•œ๋‹ค + public void validatePostRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException { + } + + public void validateGetRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException { + } + + public void validatePutRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException { + } + + public void validateDeleteRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException { + } +}
Java
์ถ”์ƒ ํด๋ž˜์Šค service ๋ฉ”์†Œ๋“œ์— ํ๋ฆ„์„ ์ •๋ฆฌํ•˜์—ฌ ํ…œํ”Œ๋ฆฟ ๋ฉ”์†Œ๋“œ ํŒจํ„ด์œผ๋กœ ์ ์šฉํ•ด์ฃผ์…จ๋„ค์š” ๐Ÿ‘ ๐Ÿ’ฏ
@@ -0,0 +1,21 @@ +package webserver.controller; + +import utils.FileIoUtils; +import webserver.domain.HttpRequest; +import webserver.domain.HttpResponse; +import webserver.domain.HttpStatusCode; + +import java.io.IOException; +import java.net.URISyntaxException; + +public class DefaultController extends AbstractController { + @Override + public void doGet(HttpRequest httpRequest, HttpResponse httpResponse) { + try { + httpResponse.send(HttpStatusCode.OK, FileIoUtils.readStaticHttpFile(httpRequest.getPath())); + } catch (URISyntaxException | IOException e) { + httpResponse.send(HttpStatusCode.NOT_FOUND); + } + } + +}
Java
http://localhost:8080/index.html ๋กœ ์ ‘์†ํ–ˆ์„ ๋•Œ ์ •์ƒ์ ์ธ ํŽ˜์ด์ง€ ํ˜ธ์ถœ์ด ๋˜์ง€ ์•Š๊ณ  ์žˆ์–ด์š”. (index ๋ฟ๋งŒ ์•„๋‹ˆ๋ผ ์ „์ฒด์ ์œผ๋กœ ์›นํŽ˜์ด์ง€ ์‘๋‹ต์ด ์ž˜๋ชป ๋œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!) ์ด ๋ถ€๋ถ„ ํ™•์ธ ๋ถ€ํƒ๋“œ๋ฆฝ๋‹ˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ํ•ด๋‹น ๋ฉ”์„œ๋“œ๋Š” Controller์˜ ๊ด€์‹ฌ์‚ฌ๊ฐ€ ์•„๋‹Œ๊ฒƒ ๊ฐ™์•„์š”! ์œ ํ‹ธ์„ฑ ํด๋ž˜์Šค๋กœ ๋งŒ๋“ค์–ด์ง€๋Š” ๊ฒƒ์ด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,32 @@ +package webserver.controller; + +import webserver.domain.HttpHeader; +import webserver.domain.HttpRequest; +import webserver.domain.HttpResponse; +import webserver.domain.HttpStatusCode; +import webserver.exceptions.InvalidRequestException; + +import java.io.IOException; + +import static service.JwpService.getProfilePage; +import static service.JwpService.isLogin; + +public class ListUserController extends AbstractController { + @Override + public void doGet(HttpRequest httpRequest, HttpResponse httpResponse) { + try { + httpResponse.send(HttpStatusCode.OK, getProfilePage()); + } catch (IOException e) { + httpResponse.send(HttpStatusCode.INTERNAL_SERVER_ERROR, "์ฝ์–ด๋“ค์ด๋Š”๋ฐ ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€์Šต๋‹ˆ๋‹ค"); + } + } + + @Override + public void validateGetRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException { + if (!isLogin(request.getHeaders().get(HttpHeader.COOKIE))) { + response.getHeaders().add(HttpHeader.LOCATION, "/user/login.html"); + response.send(HttpStatusCode.FOUND); + throw new InvalidRequestException("์ž˜๋ชป๋œ ๋กœ๊ทธ์ธ ์š”์ฒญ"); + } + } +}
Java
TemplateView๋ฅผ ๋งŒ๋“œ๋Š” ๋ถ€๋ถ„๋„ Controller ๋ณด๋‹ค๋Š” ๋‹ค๋ฅธ ๊ณณ์—์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋„๋ก ์œ ํ‹ธ์„ฑ ํด๋ž˜์Šค๋กœ ๋ถ„๋ฆฌํ•˜๋Š”๊ฒŒ ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,32 @@ +package webserver.controller; + +import webserver.domain.HttpHeader; +import webserver.domain.HttpRequest; +import webserver.domain.HttpResponse; +import webserver.domain.HttpStatusCode; +import webserver.exceptions.InvalidRequestException; + +import java.io.IOException; + +import static service.JwpService.getProfilePage; +import static service.JwpService.isLogin; + +public class ListUserController extends AbstractController { + @Override + public void doGet(HttpRequest httpRequest, HttpResponse httpResponse) { + try { + httpResponse.send(HttpStatusCode.OK, getProfilePage()); + } catch (IOException e) { + httpResponse.send(HttpStatusCode.INTERNAL_SERVER_ERROR, "์ฝ์–ด๋“ค์ด๋Š”๋ฐ ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€์Šต๋‹ˆ๋‹ค"); + } + } + + @Override + public void validateGetRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException { + if (!isLogin(request.getHeaders().get(HttpHeader.COOKIE))) { + response.getHeaders().add(HttpHeader.LOCATION, "/user/login.html"); + response.send(HttpStatusCode.FOUND); + throw new InvalidRequestException("์ž˜๋ชป๋œ ๋กœ๊ทธ์ธ ์š”์ฒญ"); + } + } +}
Java
login ์ƒํƒœ์ธ์ง€ ์—ฌ๋ถ€๋ฅผ Request๊ฐ€ ์•Œ ์ˆ˜ ์žˆ์ง€ ์•Š์„๊นŒ์š”? ํ•ด๋‹น ํ–‰๋™์„ Request์—๊ฒŒ ์œ„์ž„ํ•ด์ค์‹œ๋‹ค!
@@ -0,0 +1,46 @@ +package webserver.controller; + +import db.DataBase; +import model.User; +import webserver.domain.*; +import webserver.exceptions.InvalidRequestException; + +public class LoginController extends AbstractController { + private static final String INVALID_REQUEST_MESSAGE = "userId, password๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค"; + @Override + public void doPost(HttpRequest httpRequest, HttpResponse httpResponse) { + User findUser = DataBase.findUserById(httpRequest.getParameters().get("userId")); + if(findUser == null){ + sendLoginFailed(httpResponse); + return; + } + if (!findUser.getPassword().equals(httpRequest.getParameters().get("password"))) { + sendLoginFailed(httpResponse); + return; + } + sendLoginSucceeded(httpResponse); + } + + @Override + public void validatePostRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException { + HttpParameters httpParameters = request.getParameters(); + if (httpParameters.contain("userId") && httpParameters.contain("password")) { + return; + } + response.send(HttpStatusCode.BAD_REQUEST, INVALID_REQUEST_MESSAGE); + throw new InvalidRequestException(INVALID_REQUEST_MESSAGE); + } + + private void sendLoginSucceeded(HttpResponse httpResponse) { + httpResponse.getHeaders().add(HttpHeader.SET_COOKIE, "logined=true; Path=/"); + httpResponse.getHeaders().add(HttpHeader.LOCATION, "/index.html"); + httpResponse.send(HttpStatusCode.FOUND); + } + + private void sendLoginFailed(HttpResponse httpResponse) { + httpResponse.getHeaders().add(HttpHeader.SET_COOKIE, "logined=false; Path=/"); + httpResponse.getHeaders().add(HttpHeader.LOCATION, "/user/login_failed.html"); + httpResponse.send(HttpStatusCode.FOUND); + } + +}
Java
response header์— cookie, location ์…‹ํŒ…ํ•ด์ฃผ๋Š” ๋ถ€๋ถ„์€ Response๋กœ ์ฑ…์ž„์„ ์ด๋™์‹œํ‚ฌ ์ˆ˜ ์žˆ์ง€ ์•Š์„๊นŒ์š”? Controller์—์„œ ๋กœ๊ทธ์ธ์—ฌ๋ถ€์™€ location๋งŒ httpResponse์—๊ฒŒ ๋„˜๊ธฐ๋ฉด ์•Œ์•„์„œ ์…‹ํŒ… ๋˜์–ด์•ผํ•  ๊ฒƒ ๊ฐ™์•„์š” :)
@@ -0,0 +1,80 @@ +package webserver.domain; + +import utils.IOUtils; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + + +public class HttpRequest { + private final HttpHeaders headers; + private final HttpParameters parameters; + private HttpMethod method; + private String body; + private String path; + + public HttpRequest(InputStream in) throws IOException { + headers = new HttpHeaders(); + parameters = new HttpParameters(); + BufferedReader reader = new BufferedReader(new InputStreamReader(in)); + + readFirstLine(reader); + readHeaders(reader); + if (headers.contain(HttpHeader.CONTENT_LENGTH)) { + body = IOUtils.readData(reader, Integer.parseInt(headers.get(HttpHeader.CONTENT_LENGTH))); + parameters.parseAndSet(body); + } + } + + private void readFirstLine(BufferedReader reader) throws IOException { + String[] firstLineTokens = reader.readLine().split(" "); + String requestUrl = firstLineTokens[1]; + method = HttpMethod.valueOf(firstLineTokens[0]); + parseUrl(requestUrl); + } + + private void readHeaders(BufferedReader reader) throws IOException { + String line = reader.readLine(); + while (isValid(line)) { + String[] header = line.split(": "); + headers.add(header[0], header[1]); + line = reader.readLine(); + } + } + + private boolean isValid(String line) { + return (line != null) && !"".equals(line); + } + + private void parseUrl(String requestUrl) { + if (requestUrl.indexOf('?') == -1) { + path = requestUrl; + return; + } + String[] urlToken = requestUrl.split("\\?"); + path = urlToken[0]; + parameters.parseAndSet(urlToken[1]); + } + + public HttpHeaders getHeaders() { + return headers; + } + + public HttpParameters getParameters() { + return parameters; + } + + public HttpMethod getMethod() { + return method; + } + + public String getBody() { + return body; + } + + public String getPath() { + return path; + } +}
Java
Request-Line์„ ํŒŒ์‹ฑํ•  ๋•Œ 1, 0 ๊ณผ ๊ฐ™์€ ์˜๋ฏธ๋ฅผ ์ฐพ๊ธฐ ์–ด๋ ค์šด ๋กœ์ง์ด ์กด์žฌํ•˜๋Š”๋ฐ์š”! firstLine์€ ์ŠคํŽ™์ƒ Method SP Request-URI SP HTTP-Version CRLF ์œผ๋กœ ์ •์˜๋ฉ๋‹ˆ๋‹ค. ์ŠคํŽ™์„ ๋งค์น˜ ํŒจํ„ด์œผ๋กœ ์ •์˜ํ•˜๊ณ  ๊ทธ์— ๋งž๊ฒŒ Index ์˜๋ฏธ๋ฅผ ๋ถ€์—ฌํ•ด์ฃผ๋Š”๊ฑด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,21 @@ +package webserver.controller; + +import utils.FileIoUtils; +import webserver.domain.HttpRequest; +import webserver.domain.HttpResponse; +import webserver.domain.HttpStatusCode; + +import java.io.IOException; +import java.net.URISyntaxException; + +public class DefaultController extends AbstractController { + @Override + public void doGet(HttpRequest httpRequest, HttpResponse httpResponse) { + try { + httpResponse.send(HttpStatusCode.OK, FileIoUtils.readStaticHttpFile(httpRequest.getPath())); + } catch (URISyntaxException | IOException e) { + httpResponse.send(HttpStatusCode.NOT_FOUND); + } + } + +}
Java
์›นํŽ˜์ด์ง€๊ฐ€ ์ž˜ ๋œจ๋Š”๊ฒŒ ์•„๋‹ˆ๋ผ์„œ ์†Œ์Šค๋Š” ์ž˜ ๋ฐ›์•„์˜ค๋Š”๋ฐ ์™œ ๊ทธ๋žฌ๋‚˜ ์‹ถ์—ˆ๋Š”๋ฐ, ๋ฒ„๊ทธ์˜€๋„ค์š”. ์ž˜ ๊ณ ์ณ์„œ ๋ฐ˜์˜ํ• ๊ฒŒ์š”!
@@ -0,0 +1,80 @@ +package webserver.domain; + +import utils.IOUtils; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + + +public class HttpRequest { + private final HttpHeaders headers; + private final HttpParameters parameters; + private HttpMethod method; + private String body; + private String path; + + public HttpRequest(InputStream in) throws IOException { + headers = new HttpHeaders(); + parameters = new HttpParameters(); + BufferedReader reader = new BufferedReader(new InputStreamReader(in)); + + readFirstLine(reader); + readHeaders(reader); + if (headers.contain(HttpHeader.CONTENT_LENGTH)) { + body = IOUtils.readData(reader, Integer.parseInt(headers.get(HttpHeader.CONTENT_LENGTH))); + parameters.parseAndSet(body); + } + } + + private void readFirstLine(BufferedReader reader) throws IOException { + String[] firstLineTokens = reader.readLine().split(" "); + String requestUrl = firstLineTokens[1]; + method = HttpMethod.valueOf(firstLineTokens[0]); + parseUrl(requestUrl); + } + + private void readHeaders(BufferedReader reader) throws IOException { + String line = reader.readLine(); + while (isValid(line)) { + String[] header = line.split(": "); + headers.add(header[0], header[1]); + line = reader.readLine(); + } + } + + private boolean isValid(String line) { + return (line != null) && !"".equals(line); + } + + private void parseUrl(String requestUrl) { + if (requestUrl.indexOf('?') == -1) { + path = requestUrl; + return; + } + String[] urlToken = requestUrl.split("\\?"); + path = urlToken[0]; + parameters.parseAndSet(urlToken[1]); + } + + public HttpHeaders getHeaders() { + return headers; + } + + public HttpParameters getParameters() { + return parameters; + } + + public HttpMethod getMethod() { + return method; + } + + public String getBody() { + return body; + } + + public String getPath() { + return path; + } +}
Java
๋งค์น˜ ํŒจํ„ด ์ข‹๋„ค์š” ์•„์ง ๋ฐ˜์˜์„ ๋ชปํ•˜์˜€์ง€๋งŒ ๋งค์น˜ ํŒจํ„ด์ด๋ผ๋Š” ์•„์ด๋””์–ด ์•Œ๋ ค์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค
@@ -0,0 +1,46 @@ +package webserver.controller; + +import db.DataBase; +import model.User; +import webserver.domain.*; +import webserver.exceptions.InvalidRequestException; + +public class LoginController extends AbstractController { + private static final String INVALID_REQUEST_MESSAGE = "userId, password๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค"; + @Override + public void doPost(HttpRequest httpRequest, HttpResponse httpResponse) { + User findUser = DataBase.findUserById(httpRequest.getParameters().get("userId")); + if(findUser == null){ + sendLoginFailed(httpResponse); + return; + } + if (!findUser.getPassword().equals(httpRequest.getParameters().get("password"))) { + sendLoginFailed(httpResponse); + return; + } + sendLoginSucceeded(httpResponse); + } + + @Override + public void validatePostRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException { + HttpParameters httpParameters = request.getParameters(); + if (httpParameters.contain("userId") && httpParameters.contain("password")) { + return; + } + response.send(HttpStatusCode.BAD_REQUEST, INVALID_REQUEST_MESSAGE); + throw new InvalidRequestException(INVALID_REQUEST_MESSAGE); + } + + private void sendLoginSucceeded(HttpResponse httpResponse) { + httpResponse.getHeaders().add(HttpHeader.SET_COOKIE, "logined=true; Path=/"); + httpResponse.getHeaders().add(HttpHeader.LOCATION, "/index.html"); + httpResponse.send(HttpStatusCode.FOUND); + } + + private void sendLoginFailed(HttpResponse httpResponse) { + httpResponse.getHeaders().add(HttpHeader.SET_COOKIE, "logined=false; Path=/"); + httpResponse.getHeaders().add(HttpHeader.LOCATION, "/user/login_failed.html"); + httpResponse.send(HttpStatusCode.FOUND); + } + +}
Java
Response์— ๋„˜๊ฒจ์ฃผ๋ ค๊ณ  ํ•˜์˜€์ง€๋งŒ Response๊ฐ€ ์ˆœ์ˆ˜ํ•˜๊ฒŒ HTTP ์ŠคํŽ™์— ๋”ฐ๋ฅธ ์ „์†ก๋งŒ ๋˜๋„๋ก ๊ฐ„๊ฒฐํ•˜๊ฒŒ ์งœ์—ฌ์ ธ์žˆ์–ด์„œ ์ค‘๊ฐ„ ํด๋ž˜์Šค๋ฅผ ๋งŒ๋“œ๋Š” ๋ฐฉ๋ฒ•์œผ๋กœ ๊ณ ๋ฏผํ•ด๋ณด๊ณ  ์žˆ์–ด์š”.
@@ -0,0 +1,32 @@ +package webserver.controller; + +import webserver.domain.HttpHeader; +import webserver.domain.HttpRequest; +import webserver.domain.HttpResponse; +import webserver.domain.HttpStatusCode; +import webserver.exceptions.InvalidRequestException; + +import java.io.IOException; + +import static service.JwpService.getProfilePage; +import static service.JwpService.isLogin; + +public class ListUserController extends AbstractController { + @Override + public void doGet(HttpRequest httpRequest, HttpResponse httpResponse) { + try { + httpResponse.send(HttpStatusCode.OK, getProfilePage()); + } catch (IOException e) { + httpResponse.send(HttpStatusCode.INTERNAL_SERVER_ERROR, "์ฝ์–ด๋“ค์ด๋Š”๋ฐ ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€์Šต๋‹ˆ๋‹ค"); + } + } + + @Override + public void validateGetRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException { + if (!isLogin(request.getHeaders().get(HttpHeader.COOKIE))) { + response.getHeaders().add(HttpHeader.LOCATION, "/user/login.html"); + response.send(HttpStatusCode.FOUND); + throw new InvalidRequestException("์ž˜๋ชป๋œ ๋กœ๊ทธ์ธ ์š”์ฒญ"); + } + } +}
Java
Request ์— ์œ„์ž„ํ•˜๋ฉด ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ๋งคํ•‘ํ•˜๊ณ , ๊ฐ’์„ ํ• ๋‹นํ•˜๋Š” Request ์—ญํ• ๊นŒ์ง€๋งŒ ๋งก๊ธด ์ƒํƒœ๋ผ ์ค‘๊ฐ„ ํด๋ž˜์Šค๋ฅผ ๋งŒ๋“œ๋Š” ๋ฐฉ์‹์œผ๋กœ ๊ณ ๋ฏผ์„ ํ•ด๋ณด์•˜์–ด์š”. ๊ทธ๋Ÿฌ๋‹ค๊ฐ€, Spring ์— ์žˆ๋Š” ArgumentResolver ์™€ ์œ ์‚ฌํ•˜๊ฒŒ, ๊ฒ€์ฆ์ด ํ•„์š”ํ•œ ๋•Œ์—๋งŒ ์˜ค๋ฒ„๋ผ์ด๋”ฉ ํ•˜๋„๋ก AbstractController์— validate...Request ๋ผ๋Š” ๋ฉ”์„œ๋“œ๋“ค์„ ๋งŒ๋“ค์–ด ๋ณด์•˜์Šต๋‹ˆ๋‹ค. ์ด ๊ฒฝ์šฐ, ๋กœ๊ทธ์ธ์ด ํ•„์š”ํ•œ ์œ ์‚ฌํ•œ ์ปจํŠธ๋กค๋Ÿฌ์— ๋Œ€ํ•ด์„œ ์ค‘๋ณต ์ฝ”๋“œ๊ฐ€ ์ƒ์„ฑ๋œ๋‹ค๋Š” ๋ถ€๋‹ด์ด ์žˆ๋Š”๋ฐ, ๋กœ๊ทธ์ธ ์„œ๋น„์Šค๋ฅผ ํ†ตํ•ฉํ•˜๋Š” ์ถ”์ƒ ๊ฐ์ฒด์ธ ๋กœ๊ทธ์ธ ์ปจํŠธ๋กค๋Ÿฌ๋ฅผ ๋งŒ๋“ค๊ฑฐ๋‚˜, ๋‚˜์ค‘์— MVC ๋ชจ๋ธ์ธ ์–ด๋…ธํ…Œ์ด์…˜์„ ์ ์šฉํ• ๊นŒํ•˜๋Š”๋ฐ ์ด๋Ÿฐ ๋ฐฉ์‹์€ ์–ด๋–ค๊ฐ€์š”?
@@ -0,0 +1,45 @@ +package controller; + +import controller.handler.Handler; +import exception.utils.NoFileException; +import model.request.HttpRequest; +import model.response.HttpResponse; +import model.PathInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; + +public abstract class Controller { + private static final Logger log = LoggerFactory.getLogger( Controller.class ); + protected final Map<PathInfo, Handler> handlers = new HashMap<>(); + protected String basePath = ""; + + public void putHandler(String path, String method, Handler handler) { + handlers.put(new PathInfo(basePath + path, method), handler); + } + + public void setBasePath(String basePath) { + this.basePath = basePath; + } + + public boolean hasSameBasePath(String path) { + return path.startsWith(basePath); + } + + public boolean handle(HttpRequest request, HttpResponse response) throws NoFileException, IOException { + for (Map.Entry<PathInfo, Handler> entry : handlers.entrySet()) { + log.info("matching {} with controller {}", request.getPath(), entry.getKey().getPath()); + + if (request.getPath().matches(entry.getKey().getPath())) { + log.info("handling {} with controller {}", request.getPath(), entry.getKey().getPath()); + entry.getValue().handle(request, response); + return true; + } + } + return false; + } +}
Java
handlers ๋Š” ๊ตณ์ด LinkedHashMap ์„ ์‚ฌ์šฉํ•œ ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,30 @@ +package model; + +import java.util.Objects; + +public class PathInfo { + private final String path; + private final String method; + + public PathInfo(String path, String method) { + this.path = path; + this.method = method; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + PathInfo that = (PathInfo) o; + return Objects.equals(path, that.path) && Objects.equals(method, that.method); + } + + @Override + public int hashCode() { + return Objects.hash(path, method); + } + + public String getPath() { + return path; + } +}
Java
PathInfo ๊ฐ์ฒด๋ฅผ ๋ณ„๋„๋กœ ์„ ์–ธํ•˜์…จ๊ตฐ์š” ๐Ÿ’ฏ
@@ -0,0 +1,44 @@ +package controller; + +import controller.handler.SecuredHandler; +import model.request.HttpRequest; +import model.response.HttpResponse; +import service.UserService; +import view.View; + +import java.io.IOException; +import java.io.OutputStream; + +public class UserController extends Controller { + { + setBasePath("/user"); + putHandler("/create", "POST", this::handleCreate); + putHandler("/login", "POST", this::handleLogin); + putHandler("/list", "GET", new SecuredHandler(this::handleUserList)); + putHandler("/logout", "GET", new SecuredHandler(this::handleLogout)); + } + + private UserService userService = new UserService(); + + public void handleCreate(HttpRequest request, HttpResponse response) { + userService.addUser(request.getParsedBody()); + response.sendRedirect("/index.html"); + } + + public void handleLogin(HttpRequest request, HttpResponse response) { + if (!userService.login(request.getParsedBody())) { + response.setCookie("logined=false").sendRedirect("/user/login_failed.html"); + return; + } + response.setCookie("logined=true").sendRedirect("/index.html"); + } + + public void handleUserList(HttpRequest request, HttpResponse response) throws IOException { + byte[] body = View.getUsersView(userService.findAll(), "/user/list"); + response.sendView(body); + } + + public void handleLogout(HttpRequest request, HttpResponse response) throws IOException { + response.setCookie("logined=false").sendRedirect("/index.html"); + } +}
Java
DataBase ์— ์ง์ ‘ ์ ‘๊ทผํ•˜์ง€ ๋ง๊ณ  ๋ณ„๋„์˜ ์„œ๋น„์Šค ํด๋ž˜์Šค๋กœ ๋ถ„๋ฆฌํ•ด๋ณด๋ฉด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,44 @@ +package controller; + +import controller.handler.SecuredHandler; +import model.request.HttpRequest; +import model.response.HttpResponse; +import service.UserService; +import view.View; + +import java.io.IOException; +import java.io.OutputStream; + +public class UserController extends Controller { + { + setBasePath("/user"); + putHandler("/create", "POST", this::handleCreate); + putHandler("/login", "POST", this::handleLogin); + putHandler("/list", "GET", new SecuredHandler(this::handleUserList)); + putHandler("/logout", "GET", new SecuredHandler(this::handleLogout)); + } + + private UserService userService = new UserService(); + + public void handleCreate(HttpRequest request, HttpResponse response) { + userService.addUser(request.getParsedBody()); + response.sendRedirect("/index.html"); + } + + public void handleLogin(HttpRequest request, HttpResponse response) { + if (!userService.login(request.getParsedBody())) { + response.setCookie("logined=false").sendRedirect("/user/login_failed.html"); + return; + } + response.setCookie("logined=true").sendRedirect("/index.html"); + } + + public void handleUserList(HttpRequest request, HttpResponse response) throws IOException { + byte[] body = View.getUsersView(userService.findAll(), "/user/list"); + response.sendView(body); + } + + public void handleLogout(HttpRequest request, HttpResponse response) throws IOException { + response.setCookie("logined=false").sendRedirect("/index.html"); + } +}
Java
์œ„์™€ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ์ง์ ‘ DataBase ์— ์ ‘๊ทผํ•˜๊ธฐ ๋ณด๋‹ค ์„œ๋น„์Šค ๊ฐ์ฒด๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ์–ด๋–จ๊นŒ์š”? ๋„˜๊ฒจ์ค€ ๊ฐ’์„ ๊ธฐ๋ฐ˜์œผ๋กœ ๋กœ๊ทธ์ธ ๋˜์—ˆ๋Š”์ง€ ๋˜์ง€ ์•Š์•˜๋Š”์ง€ ์—ฌ๋ถ€๋ฅผ boolean ๊ฐ’์œผ๋กœ ์กฐํšŒํ•  ์ˆ˜ ์žˆ๋‹ค๋ฉด ์ข€ ๋” ๊ฐ„๊ฒฐํ•œ ์ฝ”๋“œ๋กœ ๊ฐœ์„ ํ•  ์ˆ˜ ์žˆ์„๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,45 @@ +package controller; + +import controller.handler.Handler; +import exception.utils.NoFileException; +import model.request.HttpRequest; +import model.response.HttpResponse; +import model.PathInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; + +public abstract class Controller { + private static final Logger log = LoggerFactory.getLogger( Controller.class ); + protected final Map<PathInfo, Handler> handlers = new HashMap<>(); + protected String basePath = ""; + + public void putHandler(String path, String method, Handler handler) { + handlers.put(new PathInfo(basePath + path, method), handler); + } + + public void setBasePath(String basePath) { + this.basePath = basePath; + } + + public boolean hasSameBasePath(String path) { + return path.startsWith(basePath); + } + + public boolean handle(HttpRequest request, HttpResponse response) throws NoFileException, IOException { + for (Map.Entry<PathInfo, Handler> entry : handlers.entrySet()) { + log.info("matching {} with controller {}", request.getPath(), entry.getKey().getPath()); + + if (request.getPath().matches(entry.getKey().getPath())) { + log.info("handling {} with controller {}", request.getPath(), entry.getKey().getPath()); + entry.getValue().handle(request, response); + return true; + } + } + return false; + } +}
Java
handle ๋ฉ”์„œ๋“œ์˜ ์ฒซ๋ฒˆ์งธ ์ธ์ž๋Š” HttpRequest ์ธ๋ฐ, ๋‘๋ฒˆ์งธ ์ธ์ž๋Š” OutputStream ์ด๋„ค์š”. HttpRequest / HttpResponse ํ˜•ํƒœ๊ฐ€ ๋” ์ ํ•ฉํ•ด ๋ณด์ž…๋‹ˆ๋‹ค ๐Ÿ˜„
@@ -0,0 +1,66 @@ +package controller; + +import controller.error.ErrorHandlerFactory; +import controller.handler.Handler; +import exception.utils.NoFileException; +import model.request.HttpRequest; +import model.response.HttpResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import webserver.RequestHandler; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.Socket; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +public class ControllerManager { + private static final Logger log = LoggerFactory.getLogger(RequestHandler.class); + private static final List<Controller> controllers = new ArrayList<>(); + static { + registerController(new ViewController()); + registerController(new UserController()); + } + + public static void registerController(Controller controller) { + controllers.add(controller); + } + + public static void runControllers(Socket connection) { + try (InputStream in = connection.getInputStream(); OutputStream out = connection.getOutputStream()) { + HttpRequest httpRequest = HttpRequest.of(in); + HttpResponse httpResponse = HttpResponse.of(out); + handleRequest(httpRequest, httpResponse); + } catch (IOException e) { + log.error("{} {}", e.getMessage(), e.getStackTrace()); + } + } + + private static void handleRequest(HttpRequest httpRequest, HttpResponse httpResponse) { + List<Controller> selectedControllers = controllers.stream() + .filter(controller -> controller.hasSameBasePath(httpRequest.getPath())) + .collect(Collectors.toList()); + try { + for (Controller controller : selectedControllers) { + if (controller.handle(httpRequest, httpResponse)) return; + } + + defaultHandle(httpRequest, httpResponse); + } catch (NoFileException | IOException | RuntimeException e) { + Handler errorHandler = ErrorHandlerFactory.getHandler(e); + try { + errorHandler.handle(httpRequest, httpResponse); + log.warn(e.getMessage()); + } catch (Exception handleError) { + log.error("{} {}", handleError.getMessage(), handleError.getStackTrace()); + } + } + } + + public static void defaultHandle(HttpRequest request, HttpResponse response) throws NoFileException { + response.forward("./templates", request.getPath()); + } +}
Java
์ปจํŠธ๋กค๋Ÿฌ ๋งค๋‹ˆ์ €๊นŒ์ง€ ์ž‘์„ฑํ•˜์…จ๋„ค์š” ๐Ÿ‘
@@ -1,16 +1,48 @@ package model; +import exception.user.WrongEmailException; +import exception.user.WrongIdException; +import exception.user.WrongNameException; +import exception.user.WrongPasswordException; + public class User { - private String userId; - private String password; - private String name; - private String email; + private final String userId; + private final String password; + private final String name; + private final String email; public User(String userId, String password, String name, String email) { - this.userId = userId; - this.password = password; - this.name = name; - this.email = email; + this.userId = validateId(userId); + this.password = validatePw(password); + this.name = validateName(name); + this.email = validateEmail(email.replace("%40", "@")); + } + + private String validatePw(String password) { + if(!password.matches("^[\\w]{1,30}$")){ + throw new WrongPasswordException(); + } + return password; + } + + private String validateId(String userId) { + if(!userId.matches("^[\\w]{1,30}$")) + throw new WrongIdException(); + return userId; + } + + private String validateName(String name) { + if (!name.matches("^[\\w๊ฐ€-ํžฃ]{1,30}$")) { + throw new WrongNameException(); + } + return name; + } + + private String validateEmail(String email) { + if(!email.matches("^[\\w]{1,30}@[\\w]{1,30}.[\\w]{1,30}$")){ + throw new WrongEmailException(); + } + return email; } public String getUserId() {
Java
validation ๋กœ์ง์„ ์ถ”๊ฐ€ํ•˜์‹  ๊ฒƒ์€ ๊ธ์ •์ ์ž…๋‹ˆ๋‹ค. ๋‹ค๋งŒ User ๊ฐ์ฒด๊ฐ€ ์ธ์Šคํ„ด์Šคํ™” ๋  ๋•Œ๋งˆ๋‹ค validate ๋ฉ”์„œ๋“œ๊ฐ€ ํ˜ธ์ถœ๋˜๊ฒŒ ๋˜๋Š”๋ฐ์š”. User ๋ผ๋Š” ๋„๋ฉ”์ธ ๋ชจ๋ธ์ด ๊ฐ–์ถ”๊ณ  ์žˆ์–ด์•ผํ•  ํ•„์ˆ˜์ ์ธ validation ์ธ์ง€ ์•„๋‹ˆ๋ฉด ์ƒˆ๋กœ์šด User ๋ฅผ ์ƒ์„ฑํ•˜๋Š” ์‚ฌ์šฉ์ž์˜ ์š”์ฒญ์—์„œ๋งŒ ํ•„์š”ํ•œ validation ์ธ์ง€์— ๋”ฐ๋ผ์„œ User ๊ฐ์ฒด์—์„œ ์ฒ˜๋ฆฌํ•˜๋Š”๊ฒŒ ์ ํ•ฉํ•  ์ˆ˜๋„ ์žˆ๊ณ  / Controller ์˜์—ญ์—์„œ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ์ด ๋” ๋‚˜์„ ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค. ์ด๋ถ€๋ถ„์€ ํ•œ๋ฒˆ ๊ณ ๋ฏผํ•ด๋ด์ฃผ์„ธ์š” ๐Ÿ˜„
@@ -0,0 +1,7 @@ +package exception.utils; + +public class NoFileException extends Exception { + public NoFileException(String path) { + super(path + " ํŒŒ์ผ์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } +}
Java
NoFIleException ๊ณผ ๊ฐ™์€ ๊ฒฝ์šฐ์—๋Š” ์–ด๋–ค ํŒŒ์ผ์„ ์ฐพ์„ ์ˆ˜ ์—†๋Š”์ง€ ํ‘œ์‹œ๋  ์ˆ˜ ์žˆ๊ฒŒ ๊ฐœ์„ ๋˜๋ฉด ๋” ์ข‹๊ฒ ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,30 @@ +package controller; + +import exception.utils.NoFileException; +import model.request.HttpRequest; +import model.response.HttpResponse; + +import java.io.IOException; +import java.io.OutputStream; + +public class ViewController extends Controller { + + { + setBasePath(""); + putHandler("/js/.*", "GET", this::handleFile); + putHandler("/css/.*", "GET", this::handleFile); + putHandler("/fonts/.*", "GET", this::handleFile); + putHandler("/favicon.ico", "GET", this::handleFile); + putHandler("/index.html", "GET", this::handleView); + putHandler("/", "GET", this::handleView); + } + + public void handleFile(HttpRequest request, HttpResponse response) throws NoFileException { + response.forward("./static", request.getPath()); + } + + public void handleView(HttpRequest request, HttpResponse response) throws NoFileException { + response.forward("./templates", + (request.getPath().equals("/") ? "/index.html" : request.getPath())); + } +}
Java
![image](https://user-images.githubusercontent.com/1266944/106766656-68cad300-667d-11eb-9e7b-52fffd02632d.png) Fonts ํŒŒ์ผ์ด ๋กœ๋”ฉ๋˜์ง€ ์•Š๋Š” ํ˜„์ƒ์ด ์žˆ์Šต๋‹ˆ๋‹ค. ํ™•์ธ ๋ถ€ํƒ๋“œ๋ ค์š” :smile
@@ -0,0 +1,45 @@ +package controller; + +import controller.handler.Handler; +import exception.utils.NoFileException; +import model.request.HttpRequest; +import model.response.HttpResponse; +import model.PathInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; + +public abstract class Controller { + private static final Logger log = LoggerFactory.getLogger( Controller.class ); + protected final Map<PathInfo, Handler> handlers = new HashMap<>(); + protected String basePath = ""; + + public void putHandler(String path, String method, Handler handler) { + handlers.put(new PathInfo(basePath + path, method), handler); + } + + public void setBasePath(String basePath) { + this.basePath = basePath; + } + + public boolean hasSameBasePath(String path) { + return path.startsWith(basePath); + } + + public boolean handle(HttpRequest request, HttpResponse response) throws NoFileException, IOException { + for (Map.Entry<PathInfo, Handler> entry : handlers.entrySet()) { + log.info("matching {} with controller {}", request.getPath(), entry.getKey().getPath()); + + if (request.getPath().matches(entry.getKey().getPath())) { + log.info("handling {} with controller {}", request.getPath(), entry.getKey().getPath()); + entry.getValue().handle(request, response); + return true; + } + } + return false; + } +}
Java
Handlers ๊ฐ€ ์ˆœ์„œ๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ๋“ฑ๋ก๋˜์–ด์•ผ ํ•  ํ•„์š”๊ฐ€ ์žˆ๋‹ค๋ฉด ์ฐจํ›„์— ์‹ค์ˆ˜ํ•˜๊ธฐ ์‰ฌ์šด ๊ตฌ์กฐ ์ž…๋‹ˆ๋‹ค. path ๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ๋™์ž‘ํ•  handler ๊ฐ€ ๋‹ค๋ฅธ ๋ฐฉ์‹์œผ๋กœ ๋งค์นญ๋  ์ˆ˜๋Š” ์—†์„์ง€ ๊ณ ๋ฏผํ•ด๋ด์ฃผ์„ธ์š” ๐Ÿ˜„