code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -0,0 +1,125 @@ +import React, { Component } from 'react'; +import { withRouter } from 'react-router-dom'; +import { API } from '../../../config'; +import './Login.scss'; + +class LoginYeseul extends Component { + constructor(props) { + super(props); + this.state = { + inputId: '', + inputPw: '', + loginMode: true, + }; + } + + handleInput = e => { + const { name, value } = e.target; + this.setState({ [name]: value }); + }; + + convertMode = () => { + this.setState({ + loginMode: !this.state.loginMode, + }); + }; + + signIn = e => { + const { inputId, inputPw } = this.state; + e.preventDefault(); + fetch(API.SIGN_IN, { + method: 'POST', + body: JSON.stringify({ + email: inputId, + password: inputPw, + }), + }) + .then(users => users.json()) + .then(users => { + if (users.MESSAGE === 'SUCCESS') { + this.setState({ + inputId: '', + inputPw: '', + }); + localStorage.setItem('token', users.ACCESS_TOKEN); + this.props.history.push('/main-yeseul'); + } else if (users.MESSAGE === 'INVALID_USER') { + const wantToSignUp = window.confirm( + '์ž˜๋ชป๋œ ์ •๋ณด์ž…๋‹ˆ๋‹ค. ํšŒ์›๊ฐ€์ž…ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ?' + ); + wantToSignUp && this.convertMode(); + } + }); + }; + + signUp = e => { + const { inputId, inputPw } = this.state; + e.preventDefault(); + fetch(API.SIGN_UP, { + method: 'POST', + body: JSON.stringify({ + email: inputId, + password: inputPw, + }), + }) + .then(users => users.json()) + .then(users => { + if (users.MESSAGE === 'SUCCESS') { + this.setState({ + inputId: '', + inputPw: '', + }); + alert(`ํšŒ์›๊ฐ€์ž…๋˜์—ˆ์Šต๋‹ˆ๋‹ค!๐ŸŽ‰ ๋กœ๊ทธ์ธํ•ด์ฃผ์„ธ์š”`); + this.convertMode(); + } else { + alert(users.MESSAGE); + } + }); + }; + + render() { + const { inputId, inputPw, loginMode } = this.state; + const checkId = /^\w[\w\-.]*@\w+\.\w{2,}/; + + return ( + <main className="loginYeseul give-border"> + <h1 className="logo">westagram</h1> + <form + className="login-form" + onSubmit={loginMode ? this.signIn : this.signUp} + > + <div className="login-form__input-box"> + <input + type="text" + name="inputId" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + value={inputId} + onChange={this.handleInput} + /> + <input + type="password" + name="inputPw" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + value={inputPw} + onChange={this.handleInput} + /> + </div> + <button + type="submit" + disabled={!(checkId.test(inputId) && inputPw.length > 8)} + > + {loginMode ? '๋กœ๊ทธ์ธ' : 'ํšŒ์›๊ฐ€์ž…'} + </button> + </form> + <a + href="https://www.instagram.com/accounts/password/reset/" + className="find-pw" + > + ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”? + </a> + </main> + ); + } +} + +export default withRouter(LoginYeseul);
JavaScript
checkId์— ๋“ค์–ด๊ฐ€๋Š”๋ฐ์ดํ„ฐ๋Š” ์–ด๋–ค๊ฑธ ์˜๋ฏธํ•˜๋Š”๊ฑด๊ฐ€์—ฌ????
@@ -0,0 +1,125 @@ +import React, { Component } from 'react'; +import { withRouter } from 'react-router-dom'; +import { API } from '../../../config'; +import './Login.scss'; + +class LoginYeseul extends Component { + constructor(props) { + super(props); + this.state = { + inputId: '', + inputPw: '', + loginMode: true, + }; + } + + handleInput = e => { + const { name, value } = e.target; + this.setState({ [name]: value }); + }; + + convertMode = () => { + this.setState({ + loginMode: !this.state.loginMode, + }); + }; + + signIn = e => { + const { inputId, inputPw } = this.state; + e.preventDefault(); + fetch(API.SIGN_IN, { + method: 'POST', + body: JSON.stringify({ + email: inputId, + password: inputPw, + }), + }) + .then(users => users.json()) + .then(users => { + if (users.MESSAGE === 'SUCCESS') { + this.setState({ + inputId: '', + inputPw: '', + }); + localStorage.setItem('token', users.ACCESS_TOKEN); + this.props.history.push('/main-yeseul'); + } else if (users.MESSAGE === 'INVALID_USER') { + const wantToSignUp = window.confirm( + '์ž˜๋ชป๋œ ์ •๋ณด์ž…๋‹ˆ๋‹ค. ํšŒ์›๊ฐ€์ž…ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ?' + ); + wantToSignUp && this.convertMode(); + } + }); + }; + + signUp = e => { + const { inputId, inputPw } = this.state; + e.preventDefault(); + fetch(API.SIGN_UP, { + method: 'POST', + body: JSON.stringify({ + email: inputId, + password: inputPw, + }), + }) + .then(users => users.json()) + .then(users => { + if (users.MESSAGE === 'SUCCESS') { + this.setState({ + inputId: '', + inputPw: '', + }); + alert(`ํšŒ์›๊ฐ€์ž…๋˜์—ˆ์Šต๋‹ˆ๋‹ค!๐ŸŽ‰ ๋กœ๊ทธ์ธํ•ด์ฃผ์„ธ์š”`); + this.convertMode(); + } else { + alert(users.MESSAGE); + } + }); + }; + + render() { + const { inputId, inputPw, loginMode } = this.state; + const checkId = /^\w[\w\-.]*@\w+\.\w{2,}/; + + return ( + <main className="loginYeseul give-border"> + <h1 className="logo">westagram</h1> + <form + className="login-form" + onSubmit={loginMode ? this.signIn : this.signUp} + > + <div className="login-form__input-box"> + <input + type="text" + name="inputId" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + value={inputId} + onChange={this.handleInput} + /> + <input + type="password" + name="inputPw" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + value={inputPw} + onChange={this.handleInput} + /> + </div> + <button + type="submit" + disabled={!(checkId.test(inputId) && inputPw.length > 8)} + > + {loginMode ? '๋กœ๊ทธ์ธ' : 'ํšŒ์›๊ฐ€์ž…'} + </button> + </form> + <a + href="https://www.instagram.com/accounts/password/reset/" + className="find-pw" + > + ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”? + </a> + </main> + ); + } +} + +export default withRouter(LoginYeseul);
JavaScript
> checkId์— ๋“ค์–ด๊ฐ€๋Š”๋ฐ์ดํ„ฐ๋Š” ์–ด๋–ค๊ฑธ ์˜๋ฏธํ•˜๋Š”๊ฑด๊ฐ€์—ฌ???? ์ž…๋ ฅํ•œ ์•„์ด๋””๊ฐ€ ์ด๋ฉ”์ผ ํ˜•์‹์— ๋งž๋Š”์ง€ ์ฒดํฌํ•˜๋Š” ์ •๊ทœํ‘œํ˜„์‹์ด์—์š”! ๋„ค์ด๋ฐ์ด ์ง๊ด€์ ์ด์ง€ ์•Š์€๊ฐ€์š”??
@@ -0,0 +1,83 @@ +@import '../../../../../Styles/common.scss'; + +.navYeseul { + position: fixed; + top: 0; + left: 50%; + right: 0; + transform: translateX(-50%); + padding: 8px 0; + border-bottom: 1px solid $main-border; + background-color: #fff; + z-index: 9999; + + .inner-nav { + display: flex; + justify-content: space-between; + align-items: center; + margin: 0 auto; + padding: 0 20px; + width: 100%; + max-width: 975px; + box-sizing: border-box; + + h1 { + display: flex; + align-items: center; + margin: 0; + font-size: 28px; + color: $main-font; + + button { + margin-right: 15px; + padding: 0 14px 0 0; + width: 22px; + height: 22px; + box-sizing: content-box; + border-right: 2px solid $main-font; + + img { + margin: 0; + } + } + } + + .nav__search { + display: flex; + align-items: center; + padding: 3px 10px 3px 26px; + width: 215px; + min-width: 125px; + height: 28px; + box-sizing: border-box; + border: 1px solid $main-border; + border-radius: 3px; + background-color: $bg-light-grey; + + input { + height: 100%; + background-color: transparent; + + &::placeholder { + text-align: center; + } + } + } + + .nav__menu { + display: flex; + + li { + margin-left: 22px; + width: 22px; + height: 22px; + + .like-button { + padding: 0; + width: 22px; + height: 22px; + } + } + } + } +}
Unknown
์˜ค ๊ผผ๊ผผํžˆ ๋ด์ฃผ์…จ๋„ค์š” ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹น :) ๊ณ ์น˜๋Ÿฌ๊ฐ€์œ 
@@ -0,0 +1,125 @@ +import React, { Component } from 'react'; +import { withRouter } from 'react-router-dom'; +import { API } from '../../../config'; +import './Login.scss'; + +class LoginYeseul extends Component { + constructor(props) { + super(props); + this.state = { + inputId: '', + inputPw: '', + loginMode: true, + }; + } + + handleInput = e => { + const { name, value } = e.target; + this.setState({ [name]: value }); + }; + + convertMode = () => { + this.setState({ + loginMode: !this.state.loginMode, + }); + }; + + signIn = e => { + const { inputId, inputPw } = this.state; + e.preventDefault(); + fetch(API.SIGN_IN, { + method: 'POST', + body: JSON.stringify({ + email: inputId, + password: inputPw, + }), + }) + .then(users => users.json()) + .then(users => { + if (users.MESSAGE === 'SUCCESS') { + this.setState({ + inputId: '', + inputPw: '', + }); + localStorage.setItem('token', users.ACCESS_TOKEN); + this.props.history.push('/main-yeseul'); + } else if (users.MESSAGE === 'INVALID_USER') { + const wantToSignUp = window.confirm( + '์ž˜๋ชป๋œ ์ •๋ณด์ž…๋‹ˆ๋‹ค. ํšŒ์›๊ฐ€์ž…ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ?' + ); + wantToSignUp && this.convertMode(); + } + }); + }; + + signUp = e => { + const { inputId, inputPw } = this.state; + e.preventDefault(); + fetch(API.SIGN_UP, { + method: 'POST', + body: JSON.stringify({ + email: inputId, + password: inputPw, + }), + }) + .then(users => users.json()) + .then(users => { + if (users.MESSAGE === 'SUCCESS') { + this.setState({ + inputId: '', + inputPw: '', + }); + alert(`ํšŒ์›๊ฐ€์ž…๋˜์—ˆ์Šต๋‹ˆ๋‹ค!๐ŸŽ‰ ๋กœ๊ทธ์ธํ•ด์ฃผ์„ธ์š”`); + this.convertMode(); + } else { + alert(users.MESSAGE); + } + }); + }; + + render() { + const { inputId, inputPw, loginMode } = this.state; + const checkId = /^\w[\w\-.]*@\w+\.\w{2,}/; + + return ( + <main className="loginYeseul give-border"> + <h1 className="logo">westagram</h1> + <form + className="login-form" + onSubmit={loginMode ? this.signIn : this.signUp} + > + <div className="login-form__input-box"> + <input + type="text" + name="inputId" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + value={inputId} + onChange={this.handleInput} + /> + <input + type="password" + name="inputPw" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + value={inputPw} + onChange={this.handleInput} + /> + </div> + <button + type="submit" + disabled={!(checkId.test(inputId) && inputPw.length > 8)} + > + {loginMode ? '๋กœ๊ทธ์ธ' : 'ํšŒ์›๊ฐ€์ž…'} + </button> + </form> + <a + href="https://www.instagram.com/accounts/password/reset/" + className="find-pw" + > + ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”? + </a> + </main> + ); + } +} + +export default withRouter(LoginYeseul);
JavaScript
(์•ˆ๋„ฃ์œผ๋ฉด ์˜ค๋ฅ˜๊ฐ€ ๋œจ๋”๋ผ๊ตฌ์š”..)
@@ -0,0 +1,83 @@ +@import '../../../../../Styles/common.scss'; + +.navYeseul { + position: fixed; + top: 0; + left: 50%; + right: 0; + transform: translateX(-50%); + padding: 8px 0; + border-bottom: 1px solid $main-border; + background-color: #fff; + z-index: 9999; + + .inner-nav { + display: flex; + justify-content: space-between; + align-items: center; + margin: 0 auto; + padding: 0 20px; + width: 100%; + max-width: 975px; + box-sizing: border-box; + + h1 { + display: flex; + align-items: center; + margin: 0; + font-size: 28px; + color: $main-font; + + button { + margin-right: 15px; + padding: 0 14px 0 0; + width: 22px; + height: 22px; + box-sizing: content-box; + border-right: 2px solid $main-font; + + img { + margin: 0; + } + } + } + + .nav__search { + display: flex; + align-items: center; + padding: 3px 10px 3px 26px; + width: 215px; + min-width: 125px; + height: 28px; + box-sizing: border-box; + border: 1px solid $main-border; + border-radius: 3px; + background-color: $bg-light-grey; + + input { + height: 100%; + background-color: transparent; + + &::placeholder { + text-align: center; + } + } + } + + .nav__menu { + display: flex; + + li { + margin-left: 22px; + width: 22px; + height: 22px; + + .like-button { + padding: 0; + width: 22px; + height: 22px; + } + } + } + } +}
Unknown
์™œ ์ œ common์—” ์—†์ฃ ?!?!
@@ -0,0 +1,125 @@ +import React, { Component } from 'react'; +import { withRouter } from 'react-router-dom'; +import { API } from '../../../config'; +import './Login.scss'; + +class LoginYeseul extends Component { + constructor(props) { + super(props); + this.state = { + inputId: '', + inputPw: '', + loginMode: true, + }; + } + + handleInput = e => { + const { name, value } = e.target; + this.setState({ [name]: value }); + }; + + convertMode = () => { + this.setState({ + loginMode: !this.state.loginMode, + }); + }; + + signIn = e => { + const { inputId, inputPw } = this.state; + e.preventDefault(); + fetch(API.SIGN_IN, { + method: 'POST', + body: JSON.stringify({ + email: inputId, + password: inputPw, + }), + }) + .then(users => users.json()) + .then(users => { + if (users.MESSAGE === 'SUCCESS') { + this.setState({ + inputId: '', + inputPw: '', + }); + localStorage.setItem('token', users.ACCESS_TOKEN); + this.props.history.push('/main-yeseul'); + } else if (users.MESSAGE === 'INVALID_USER') { + const wantToSignUp = window.confirm( + '์ž˜๋ชป๋œ ์ •๋ณด์ž…๋‹ˆ๋‹ค. ํšŒ์›๊ฐ€์ž…ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ?' + ); + wantToSignUp && this.convertMode(); + } + }); + }; + + signUp = e => { + const { inputId, inputPw } = this.state; + e.preventDefault(); + fetch(API.SIGN_UP, { + method: 'POST', + body: JSON.stringify({ + email: inputId, + password: inputPw, + }), + }) + .then(users => users.json()) + .then(users => { + if (users.MESSAGE === 'SUCCESS') { + this.setState({ + inputId: '', + inputPw: '', + }); + alert(`ํšŒ์›๊ฐ€์ž…๋˜์—ˆ์Šต๋‹ˆ๋‹ค!๐ŸŽ‰ ๋กœ๊ทธ์ธํ•ด์ฃผ์„ธ์š”`); + this.convertMode(); + } else { + alert(users.MESSAGE); + } + }); + }; + + render() { + const { inputId, inputPw, loginMode } = this.state; + const checkId = /^\w[\w\-.]*@\w+\.\w{2,}/; + + return ( + <main className="loginYeseul give-border"> + <h1 className="logo">westagram</h1> + <form + className="login-form" + onSubmit={loginMode ? this.signIn : this.signUp} + > + <div className="login-form__input-box"> + <input + type="text" + name="inputId" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + value={inputId} + onChange={this.handleInput} + /> + <input + type="password" + name="inputPw" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + value={inputPw} + onChange={this.handleInput} + /> + </div> + <button + type="submit" + disabled={!(checkId.test(inputId) && inputPw.length > 8)} + > + {loginMode ? '๋กœ๊ทธ์ธ' : 'ํšŒ์›๊ฐ€์ž…'} + </button> + </form> + <a + href="https://www.instagram.com/accounts/password/reset/" + className="find-pw" + > + ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”? + </a> + </main> + ); + } +} + +export default withRouter(LoginYeseul);
JavaScript
์•„๋‹ˆ์—์—ฌ ์ œ๊ฐ€ ์ž˜๋ชฐ๋ž์–ด์š” ใ…‹ใ…‹ใ…‹ใ…‹ ์ž˜ํ•˜์…จ์–ด์š”!!
@@ -0,0 +1,125 @@ +import React, { Component } from 'react'; +import { withRouter } from 'react-router-dom'; +import { API } from '../../../config'; +import './Login.scss'; + +class LoginYeseul extends Component { + constructor(props) { + super(props); + this.state = { + inputId: '', + inputPw: '', + loginMode: true, + }; + } + + handleInput = e => { + const { name, value } = e.target; + this.setState({ [name]: value }); + }; + + convertMode = () => { + this.setState({ + loginMode: !this.state.loginMode, + }); + }; + + signIn = e => { + const { inputId, inputPw } = this.state; + e.preventDefault(); + fetch(API.SIGN_IN, { + method: 'POST', + body: JSON.stringify({ + email: inputId, + password: inputPw, + }), + }) + .then(users => users.json()) + .then(users => { + if (users.MESSAGE === 'SUCCESS') { + this.setState({ + inputId: '', + inputPw: '', + }); + localStorage.setItem('token', users.ACCESS_TOKEN); + this.props.history.push('/main-yeseul'); + } else if (users.MESSAGE === 'INVALID_USER') { + const wantToSignUp = window.confirm( + '์ž˜๋ชป๋œ ์ •๋ณด์ž…๋‹ˆ๋‹ค. ํšŒ์›๊ฐ€์ž…ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ?' + ); + wantToSignUp && this.convertMode(); + } + }); + }; + + signUp = e => { + const { inputId, inputPw } = this.state; + e.preventDefault(); + fetch(API.SIGN_UP, { + method: 'POST', + body: JSON.stringify({ + email: inputId, + password: inputPw, + }), + }) + .then(users => users.json()) + .then(users => { + if (users.MESSAGE === 'SUCCESS') { + this.setState({ + inputId: '', + inputPw: '', + }); + alert(`ํšŒ์›๊ฐ€์ž…๋˜์—ˆ์Šต๋‹ˆ๋‹ค!๐ŸŽ‰ ๋กœ๊ทธ์ธํ•ด์ฃผ์„ธ์š”`); + this.convertMode(); + } else { + alert(users.MESSAGE); + } + }); + }; + + render() { + const { inputId, inputPw, loginMode } = this.state; + const checkId = /^\w[\w\-.]*@\w+\.\w{2,}/; + + return ( + <main className="loginYeseul give-border"> + <h1 className="logo">westagram</h1> + <form + className="login-form" + onSubmit={loginMode ? this.signIn : this.signUp} + > + <div className="login-form__input-box"> + <input + type="text" + name="inputId" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + value={inputId} + onChange={this.handleInput} + /> + <input + type="password" + name="inputPw" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + value={inputPw} + onChange={this.handleInput} + /> + </div> + <button + type="submit" + disabled={!(checkId.test(inputId) && inputPw.length > 8)} + > + {loginMode ? '๋กœ๊ทธ์ธ' : 'ํšŒ์›๊ฐ€์ž…'} + </button> + </form> + <a + href="https://www.instagram.com/accounts/password/reset/" + className="find-pw" + > + ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”? + </a> + </main> + ); + } +} + +export default withRouter(LoginYeseul);
JavaScript
์ €๋Š” ์ด๋ฒคํŠธ๋ฅผ ์ค€ input์— name attribute๋ฅผ ๋ถ€์—ฌํ•ด์„œ handleInputId์ด๋ž‘ handleInputPw ํ•จ์ˆ˜๋ฅผ ํ•˜๋‚˜๋กœ ํ•ฉ์ณค๋Š”๋ฐ ์ฐธ๊ณ  ํ•˜์…”์„œ ๋ฐ˜์˜ํ•ด๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์šค! handleInput = e => { this.setState({ [e.target.name]: e.target.value, }); };
@@ -0,0 +1,125 @@ +import React, { Component } from 'react'; +import { withRouter } from 'react-router-dom'; +import { API } from '../../../config'; +import './Login.scss'; + +class LoginYeseul extends Component { + constructor(props) { + super(props); + this.state = { + inputId: '', + inputPw: '', + loginMode: true, + }; + } + + handleInput = e => { + const { name, value } = e.target; + this.setState({ [name]: value }); + }; + + convertMode = () => { + this.setState({ + loginMode: !this.state.loginMode, + }); + }; + + signIn = e => { + const { inputId, inputPw } = this.state; + e.preventDefault(); + fetch(API.SIGN_IN, { + method: 'POST', + body: JSON.stringify({ + email: inputId, + password: inputPw, + }), + }) + .then(users => users.json()) + .then(users => { + if (users.MESSAGE === 'SUCCESS') { + this.setState({ + inputId: '', + inputPw: '', + }); + localStorage.setItem('token', users.ACCESS_TOKEN); + this.props.history.push('/main-yeseul'); + } else if (users.MESSAGE === 'INVALID_USER') { + const wantToSignUp = window.confirm( + '์ž˜๋ชป๋œ ์ •๋ณด์ž…๋‹ˆ๋‹ค. ํšŒ์›๊ฐ€์ž…ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ?' + ); + wantToSignUp && this.convertMode(); + } + }); + }; + + signUp = e => { + const { inputId, inputPw } = this.state; + e.preventDefault(); + fetch(API.SIGN_UP, { + method: 'POST', + body: JSON.stringify({ + email: inputId, + password: inputPw, + }), + }) + .then(users => users.json()) + .then(users => { + if (users.MESSAGE === 'SUCCESS') { + this.setState({ + inputId: '', + inputPw: '', + }); + alert(`ํšŒ์›๊ฐ€์ž…๋˜์—ˆ์Šต๋‹ˆ๋‹ค!๐ŸŽ‰ ๋กœ๊ทธ์ธํ•ด์ฃผ์„ธ์š”`); + this.convertMode(); + } else { + alert(users.MESSAGE); + } + }); + }; + + render() { + const { inputId, inputPw, loginMode } = this.state; + const checkId = /^\w[\w\-.]*@\w+\.\w{2,}/; + + return ( + <main className="loginYeseul give-border"> + <h1 className="logo">westagram</h1> + <form + className="login-form" + onSubmit={loginMode ? this.signIn : this.signUp} + > + <div className="login-form__input-box"> + <input + type="text" + name="inputId" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + value={inputId} + onChange={this.handleInput} + /> + <input + type="password" + name="inputPw" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + value={inputPw} + onChange={this.handleInput} + /> + </div> + <button + type="submit" + disabled={!(checkId.test(inputId) && inputPw.length > 8)} + > + {loginMode ? '๋กœ๊ทธ์ธ' : 'ํšŒ์›๊ฐ€์ž…'} + </button> + </form> + <a + href="https://www.instagram.com/accounts/password/reset/" + className="find-pw" + > + ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”? + </a> + </main> + ); + } +} + +export default withRouter(LoginYeseul);
JavaScript
- API ๋ถ€๋Š” ์ดํ›„์— src/config.js ํŒŒ์ผ์„ ๋งŒ๋“ค์–ด ํ•ด๋‹น ํŒŒ์ผ์—์„œ ์ผ๊ด„์ ์œผ๋กœ ๊ด€๋ฆฌํ•ฉ๋‹ˆ๋‹ค. ```js // config.js const IP = '10.58.6.252:8000'; export const SIGN_IN_API = `http://${IP}/user/signin`; // Login.js import { SIGN_IN_API } from '../../config.js'; ... fetch(SIGN_IN_API).then().then() ... ``` - ์œ„์™€ ๊ฐ™์ด config.js ์—์„œ ์ผ๊ด„์ ์œผ๋กœ ๊ด€๋ฆฌํ• ๊ฒฝ์šฐ, ๋ฐฑ์—”๋“œ ์„œ๋ฒ„์˜ IP ๊ฐ€ ๋ณ€๊ฒฝ๋˜๊ฑฐ๋‚˜ ํ˜น์€ ์—”๋“œํฌ์ธํŠธ๊ฐ€ ๋ณ€๊ฒฝ๋˜์—ˆ์„ ๋•Œ, config.js ์—์„œ๋งŒ ํ•œ๋ฒˆ ์ˆ˜์ •ํ•ด์ฃผ๋ฉด ๋˜๊ธฐ ๋•Œ๋ฌธ์— ์œ ์ง€๋ณด์ˆ˜๊ฐ€ ํŽธํ•ด์ง‘๋‹ˆ๋‹ค.
@@ -0,0 +1,125 @@ +import React, { Component } from 'react'; +import { withRouter } from 'react-router-dom'; +import { API } from '../../../config'; +import './Login.scss'; + +class LoginYeseul extends Component { + constructor(props) { + super(props); + this.state = { + inputId: '', + inputPw: '', + loginMode: true, + }; + } + + handleInput = e => { + const { name, value } = e.target; + this.setState({ [name]: value }); + }; + + convertMode = () => { + this.setState({ + loginMode: !this.state.loginMode, + }); + }; + + signIn = e => { + const { inputId, inputPw } = this.state; + e.preventDefault(); + fetch(API.SIGN_IN, { + method: 'POST', + body: JSON.stringify({ + email: inputId, + password: inputPw, + }), + }) + .then(users => users.json()) + .then(users => { + if (users.MESSAGE === 'SUCCESS') { + this.setState({ + inputId: '', + inputPw: '', + }); + localStorage.setItem('token', users.ACCESS_TOKEN); + this.props.history.push('/main-yeseul'); + } else if (users.MESSAGE === 'INVALID_USER') { + const wantToSignUp = window.confirm( + '์ž˜๋ชป๋œ ์ •๋ณด์ž…๋‹ˆ๋‹ค. ํšŒ์›๊ฐ€์ž…ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ?' + ); + wantToSignUp && this.convertMode(); + } + }); + }; + + signUp = e => { + const { inputId, inputPw } = this.state; + e.preventDefault(); + fetch(API.SIGN_UP, { + method: 'POST', + body: JSON.stringify({ + email: inputId, + password: inputPw, + }), + }) + .then(users => users.json()) + .then(users => { + if (users.MESSAGE === 'SUCCESS') { + this.setState({ + inputId: '', + inputPw: '', + }); + alert(`ํšŒ์›๊ฐ€์ž…๋˜์—ˆ์Šต๋‹ˆ๋‹ค!๐ŸŽ‰ ๋กœ๊ทธ์ธํ•ด์ฃผ์„ธ์š”`); + this.convertMode(); + } else { + alert(users.MESSAGE); + } + }); + }; + + render() { + const { inputId, inputPw, loginMode } = this.state; + const checkId = /^\w[\w\-.]*@\w+\.\w{2,}/; + + return ( + <main className="loginYeseul give-border"> + <h1 className="logo">westagram</h1> + <form + className="login-form" + onSubmit={loginMode ? this.signIn : this.signUp} + > + <div className="login-form__input-box"> + <input + type="text" + name="inputId" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + value={inputId} + onChange={this.handleInput} + /> + <input + type="password" + name="inputPw" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + value={inputPw} + onChange={this.handleInput} + /> + </div> + <button + type="submit" + disabled={!(checkId.test(inputId) && inputPw.length > 8)} + > + {loginMode ? '๋กœ๊ทธ์ธ' : 'ํšŒ์›๊ฐ€์ž…'} + </button> + </form> + <a + href="https://www.instagram.com/accounts/password/reset/" + className="find-pw" + > + ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”? + </a> + </main> + ); + } +} + +export default withRouter(LoginYeseul);
JavaScript
- ์ •๊ทœ์‹ ๐Ÿ‘ ๐Ÿ‘
@@ -0,0 +1,125 @@ +import React, { Component } from 'react'; +import { withRouter } from 'react-router-dom'; +import { API } from '../../../config'; +import './Login.scss'; + +class LoginYeseul extends Component { + constructor(props) { + super(props); + this.state = { + inputId: '', + inputPw: '', + loginMode: true, + }; + } + + handleInput = e => { + const { name, value } = e.target; + this.setState({ [name]: value }); + }; + + convertMode = () => { + this.setState({ + loginMode: !this.state.loginMode, + }); + }; + + signIn = e => { + const { inputId, inputPw } = this.state; + e.preventDefault(); + fetch(API.SIGN_IN, { + method: 'POST', + body: JSON.stringify({ + email: inputId, + password: inputPw, + }), + }) + .then(users => users.json()) + .then(users => { + if (users.MESSAGE === 'SUCCESS') { + this.setState({ + inputId: '', + inputPw: '', + }); + localStorage.setItem('token', users.ACCESS_TOKEN); + this.props.history.push('/main-yeseul'); + } else if (users.MESSAGE === 'INVALID_USER') { + const wantToSignUp = window.confirm( + '์ž˜๋ชป๋œ ์ •๋ณด์ž…๋‹ˆ๋‹ค. ํšŒ์›๊ฐ€์ž…ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ?' + ); + wantToSignUp && this.convertMode(); + } + }); + }; + + signUp = e => { + const { inputId, inputPw } = this.state; + e.preventDefault(); + fetch(API.SIGN_UP, { + method: 'POST', + body: JSON.stringify({ + email: inputId, + password: inputPw, + }), + }) + .then(users => users.json()) + .then(users => { + if (users.MESSAGE === 'SUCCESS') { + this.setState({ + inputId: '', + inputPw: '', + }); + alert(`ํšŒ์›๊ฐ€์ž…๋˜์—ˆ์Šต๋‹ˆ๋‹ค!๐ŸŽ‰ ๋กœ๊ทธ์ธํ•ด์ฃผ์„ธ์š”`); + this.convertMode(); + } else { + alert(users.MESSAGE); + } + }); + }; + + render() { + const { inputId, inputPw, loginMode } = this.state; + const checkId = /^\w[\w\-.]*@\w+\.\w{2,}/; + + return ( + <main className="loginYeseul give-border"> + <h1 className="logo">westagram</h1> + <form + className="login-form" + onSubmit={loginMode ? this.signIn : this.signUp} + > + <div className="login-form__input-box"> + <input + type="text" + name="inputId" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + value={inputId} + onChange={this.handleInput} + /> + <input + type="password" + name="inputPw" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + value={inputPw} + onChange={this.handleInput} + /> + </div> + <button + type="submit" + disabled={!(checkId.test(inputId) && inputPw.length > 8)} + > + {loginMode ? '๋กœ๊ทธ์ธ' : 'ํšŒ์›๊ฐ€์ž…'} + </button> + </form> + <a + href="https://www.instagram.com/accounts/password/reset/" + className="find-pw" + > + ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”? + </a> + </main> + ); + } +} + +export default withRouter(LoginYeseul);
JavaScript
- ํด๋ž˜์Šค ๋„ค์ž„ ๋„ค์ด๋ฐ ๐Ÿ‘
@@ -0,0 +1,60 @@ +@import '../../../Styles/common.scss'; + +.loginYeseul { + position: fixed; + top: 50%; + left: 50%; + transform: translate(-50%, -60%); + padding: 32px 0 25px; + width: 350px; + text-align: center; + + h1 { + font-size: 40px; + } + + .login-form { + margin: 35px 40px 120px; + + &__input-box { + margin-bottom: 15px; + + input { + margin: 3px 0; + padding: 12px 10px 10px; + border: 1px solid $main-border; + border-radius: 3px; + background-color: $bg-light-grey; + + &::placeholder, + &::-webkit-input-placeholder, + &::-ms-input-placeholder { + color: $font--grey; + } + + &:focus { + border: 1px solid $border--gray; + } + } + } + + button { + padding: 8px; + width: 100%; + border-radius: 4px; + background-color: $btn--blue; + color: #fff; + font-weight: 600; + } + } + + .find-pw { + font-size: 13px; + } + + button:disabled, + input:disabled { + opacity: 0.3; + pointer-events: none; + } +}
Unknown
- & ์—ฐ์‚ฐ์ž ํ™œ์šฉ ๊ตฟ์ž…๋‹ˆ๋‹ค!
@@ -0,0 +1,55 @@ +import React, { Component } from 'react'; +import { Link } from 'react-router-dom'; +import './Comment.scss'; + +class Comment extends Component { + constructor(props) { + super(props); + this.state = { + isLiked: false, + }; + } + + likeComment = () => { + this.setState({ isLiked: !this.state.isLiked }); + }; + + render() { + const { isLiked } = this.state; + const { info, handleClick } = this.props; + + return ( + <p className="feed__comment align-item-center"> + <span className="user-name">{info.writer}</span> + <Link to="/main-yeseul">{info.tagId ? `@${info.tagId}` : ''}</Link> + {info.content} + <button + type="button" + className="delete-btn" + onClick={() => handleClick(info.id)} + > + x + </button> + <button + className={ + isLiked ? 'like-btn align-right clicked' : 'like-btn align-right ' + } + onClick={this.likeComment} + > + <svg + version="1.1" + id="Capa_1" + xmlns="http://www.w3.org/2000/svg" + xmlnsXlink="http://www.w3.org/1999/xlink" + viewBox="-50 -45 580 580" + xmlSpace="preserve" + > + <path d="M376,30c-27.783,0-53.255,8.804-75.707,26.168c-21.525,16.647-35.856,37.85-44.293,53.268c-8.437-15.419-22.768-36.621-44.293-53.268C189.255,38.804,163.783,30,136,30C58.468,30,0,93.417,0,177.514c0,90.854,72.943,153.015,183.369,247.118c18.752,15.981,40.007,34.095,62.099,53.414C248.38,480.596,252.12,482,256,482s7.62-1.404,10.532-3.953c22.094-19.322,43.348-37.435,62.111-53.425C439.057,330.529,512,268.368,512,177.514C512,93.417,453.532,30,376,30z" /> + </svg> + </button> + </p> + ); + } +} + +export default Comment;
JavaScript
- id ๊ฐ’์€ ํ”„๋กœ์ ํŠธ ์ „์ฒด ๋‚ด์—์„œ ์œ ์ผํ•ด์•ผํ•˜๊ธฐ ๋•Œ๋ฌธ์—, ๊ผญ ํ•„์š”ํ•œ ๊ฒฝ์šฐ์—๋งŒ ์‚ฌ์šฉํ•ด์ฃผ์„ธ์š”! - id ๋Œ€์‹ ์— onClick ์ด๋ฒคํŠธ์— ๋ฐ”๋กœ ์ธ์ž๋ฅผ ๋„˜๊ฒจ์ฃผ์‹ค ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค. ์ฐธ๊ณ ํ•ด์ฃผ์„ธ์š”! ```js onClick = {() => this.props.handleClick(info.id)} ```
@@ -0,0 +1,140 @@ +import React, { Component } from 'react'; +import { Link } from 'react-router-dom'; +import User from '../User/User'; +import Comment from '../Comment/Comment'; +import IconButton from '../Button/IconButton'; +import { API } from '../../../../../config'; +import './Feed.scss'; + +class Feed extends Component { + constructor(props) { + super(props); + this.state = { + inputComment: '', + commentId: 0, + comments: [], + }; + } + + componentDidMount() { + const { feedId } = this.props; + fetch(API.COMMENT) + .then(comments => comments.json()) + .then(comments => { + this.setState({ + commentId: comments.length + 1, + comments: comments.filter(comment => comment.feedId === feedId), + }); + }); + } + + handleInput = e => { + this.setState({ inputComment: e.target.value }); + }; + + addComment = e => { + const { inputComment, commentId, comments } = this.state; + + e.preventDefault(); + this.setState({ + inputComment: '', + commentId: commentId + 1, + comments: [ + ...comments, + { + id: commentId.toString(), + writer: this.props.userName, + content: inputComment, + tagId: '', + }, + ], + }); + }; + + deleteComment = clickedId => { + const { comments } = this.state; + this.setState({ + comments: comments.filter(comment => comment.id !== clickedId), + }); + }; + + render() { + const { inputComment, comments } = this.state; + const { writer, contents } = this.props; + + return ( + <article className="feed give-border"> + <header className="feed__header"> + <User size="small" user={writer}> + <IconButton + className="feed__header__more-icon align-right" + info={{ name: '๋”๋ณด๊ธฐ', fileName: 'more.svg' }} + /> + </User> + </header> + <div className="feed__image"> + <img + alt={`by ${writer.name} on ${contents.date}`} + src={contents.postedImage} + /> + </div> + <div className="feed__btns"> + <button type="button"> + <img + alt="์ข‹์•„์š”" + src="https://s3.ap-northeast-2.amazonaws.com/cdn.wecode.co.kr/bearu/heart.png" + /> + </button> + <IconButton info={{ name: '๋Œ“๊ธ€', fileName: 'comment.svg' }} /> + <IconButton info={{ name: '๊ณต์œ ํ•˜๊ธฐ', fileName: 'send.svg' }} /> + <IconButton + className="align-right" + info={{ name: '๋ถ๋งˆํฌ', fileName: 'bookmark.svg' }} + /> + </div> + <p className="feed__likes-number"> + <Link to="/main-yeseul">{`์ข‹์•„์š” ${contents.likesNum}๊ฐœ`}</Link> + </p> + <div className="feed__description"> + <p> + <span className="user-name">{writer.name}</span> + <span>{contents.description}</span> + </p> + </div> + <div className="feed__comments"> + {comments.map(comment => ( + <Comment + key={comment.id} + info={comment} + handleClick={this.deleteComment} + /> + ))} + </div> + <form + className="feed__form align-item-center space-between" + name="commentForm" + > + <IconButton info={{ name: '์ด๋ชจํ‹ฐ์ฝ˜', fileName: 'emoticon.svg' }} /> + <input + type="text" + placeholder="๋Œ“๊ธ€ ๋‹ฌ๊ธฐ..." + value={inputComment} + className="feed__input-comment" + name="inputComment" + onChange={this.handleInput} + /> + <input + type="submit" + className="feed__submit-comment" + name="submitComment" + value="๊ฒŒ์‹œ" + disabled={!(inputComment.length > 0)} + onClick={this.addComment} + /> + </form> + </article> + ); + } +} + +export default Feed;
JavaScript
- get ๋ฉ”์„œ๋“œ๋Š” ๊ธฐ๋ณธ ๋ฉ”์„œ๋“œ์ด๊ธฐ ๋•Œ๋ฌธ์— ์ƒ๋žตํ•ด์ฃผ์‹ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ```suggestion fetch('/data/Yeseul/commentData.json') ```
@@ -0,0 +1,140 @@ +import React, { Component } from 'react'; +import { Link } from 'react-router-dom'; +import User from '../User/User'; +import Comment from '../Comment/Comment'; +import IconButton from '../Button/IconButton'; +import { API } from '../../../../../config'; +import './Feed.scss'; + +class Feed extends Component { + constructor(props) { + super(props); + this.state = { + inputComment: '', + commentId: 0, + comments: [], + }; + } + + componentDidMount() { + const { feedId } = this.props; + fetch(API.COMMENT) + .then(comments => comments.json()) + .then(comments => { + this.setState({ + commentId: comments.length + 1, + comments: comments.filter(comment => comment.feedId === feedId), + }); + }); + } + + handleInput = e => { + this.setState({ inputComment: e.target.value }); + }; + + addComment = e => { + const { inputComment, commentId, comments } = this.state; + + e.preventDefault(); + this.setState({ + inputComment: '', + commentId: commentId + 1, + comments: [ + ...comments, + { + id: commentId.toString(), + writer: this.props.userName, + content: inputComment, + tagId: '', + }, + ], + }); + }; + + deleteComment = clickedId => { + const { comments } = this.state; + this.setState({ + comments: comments.filter(comment => comment.id !== clickedId), + }); + }; + + render() { + const { inputComment, comments } = this.state; + const { writer, contents } = this.props; + + return ( + <article className="feed give-border"> + <header className="feed__header"> + <User size="small" user={writer}> + <IconButton + className="feed__header__more-icon align-right" + info={{ name: '๋”๋ณด๊ธฐ', fileName: 'more.svg' }} + /> + </User> + </header> + <div className="feed__image"> + <img + alt={`by ${writer.name} on ${contents.date}`} + src={contents.postedImage} + /> + </div> + <div className="feed__btns"> + <button type="button"> + <img + alt="์ข‹์•„์š”" + src="https://s3.ap-northeast-2.amazonaws.com/cdn.wecode.co.kr/bearu/heart.png" + /> + </button> + <IconButton info={{ name: '๋Œ“๊ธ€', fileName: 'comment.svg' }} /> + <IconButton info={{ name: '๊ณต์œ ํ•˜๊ธฐ', fileName: 'send.svg' }} /> + <IconButton + className="align-right" + info={{ name: '๋ถ๋งˆํฌ', fileName: 'bookmark.svg' }} + /> + </div> + <p className="feed__likes-number"> + <Link to="/main-yeseul">{`์ข‹์•„์š” ${contents.likesNum}๊ฐœ`}</Link> + </p> + <div className="feed__description"> + <p> + <span className="user-name">{writer.name}</span> + <span>{contents.description}</span> + </p> + </div> + <div className="feed__comments"> + {comments.map(comment => ( + <Comment + key={comment.id} + info={comment} + handleClick={this.deleteComment} + /> + ))} + </div> + <form + className="feed__form align-item-center space-between" + name="commentForm" + > + <IconButton info={{ name: '์ด๋ชจํ‹ฐ์ฝ˜', fileName: 'emoticon.svg' }} /> + <input + type="text" + placeholder="๋Œ“๊ธ€ ๋‹ฌ๊ธฐ..." + value={inputComment} + className="feed__input-comment" + name="inputComment" + onChange={this.handleInput} + /> + <input + type="submit" + className="feed__submit-comment" + name="submitComment" + value="๊ฒŒ์‹œ" + disabled={!(inputComment.length > 0)} + onClick={this.addComment} + /> + </form> + </article> + ); + } +} + +export default Feed;
JavaScript
- ๋ถˆ๋ณ€์„ฑ ์ž˜ ์ง€์ผœ์ฃผ์…จ๋„ค์š”! ๐Ÿ‘ ๐Ÿ‘
@@ -0,0 +1,140 @@ +import React, { Component } from 'react'; +import { Link } from 'react-router-dom'; +import User from '../User/User'; +import Comment from '../Comment/Comment'; +import IconButton from '../Button/IconButton'; +import { API } from '../../../../../config'; +import './Feed.scss'; + +class Feed extends Component { + constructor(props) { + super(props); + this.state = { + inputComment: '', + commentId: 0, + comments: [], + }; + } + + componentDidMount() { + const { feedId } = this.props; + fetch(API.COMMENT) + .then(comments => comments.json()) + .then(comments => { + this.setState({ + commentId: comments.length + 1, + comments: comments.filter(comment => comment.feedId === feedId), + }); + }); + } + + handleInput = e => { + this.setState({ inputComment: e.target.value }); + }; + + addComment = e => { + const { inputComment, commentId, comments } = this.state; + + e.preventDefault(); + this.setState({ + inputComment: '', + commentId: commentId + 1, + comments: [ + ...comments, + { + id: commentId.toString(), + writer: this.props.userName, + content: inputComment, + tagId: '', + }, + ], + }); + }; + + deleteComment = clickedId => { + const { comments } = this.state; + this.setState({ + comments: comments.filter(comment => comment.id !== clickedId), + }); + }; + + render() { + const { inputComment, comments } = this.state; + const { writer, contents } = this.props; + + return ( + <article className="feed give-border"> + <header className="feed__header"> + <User size="small" user={writer}> + <IconButton + className="feed__header__more-icon align-right" + info={{ name: '๋”๋ณด๊ธฐ', fileName: 'more.svg' }} + /> + </User> + </header> + <div className="feed__image"> + <img + alt={`by ${writer.name} on ${contents.date}`} + src={contents.postedImage} + /> + </div> + <div className="feed__btns"> + <button type="button"> + <img + alt="์ข‹์•„์š”" + src="https://s3.ap-northeast-2.amazonaws.com/cdn.wecode.co.kr/bearu/heart.png" + /> + </button> + <IconButton info={{ name: '๋Œ“๊ธ€', fileName: 'comment.svg' }} /> + <IconButton info={{ name: '๊ณต์œ ํ•˜๊ธฐ', fileName: 'send.svg' }} /> + <IconButton + className="align-right" + info={{ name: '๋ถ๋งˆํฌ', fileName: 'bookmark.svg' }} + /> + </div> + <p className="feed__likes-number"> + <Link to="/main-yeseul">{`์ข‹์•„์š” ${contents.likesNum}๊ฐœ`}</Link> + </p> + <div className="feed__description"> + <p> + <span className="user-name">{writer.name}</span> + <span>{contents.description}</span> + </p> + </div> + <div className="feed__comments"> + {comments.map(comment => ( + <Comment + key={comment.id} + info={comment} + handleClick={this.deleteComment} + /> + ))} + </div> + <form + className="feed__form align-item-center space-between" + name="commentForm" + > + <IconButton info={{ name: '์ด๋ชจํ‹ฐ์ฝ˜', fileName: 'emoticon.svg' }} /> + <input + type="text" + placeholder="๋Œ“๊ธ€ ๋‹ฌ๊ธฐ..." + value={inputComment} + className="feed__input-comment" + name="inputComment" + onChange={this.handleInput} + /> + <input + type="submit" + className="feed__submit-comment" + name="submitComment" + value="๊ฒŒ์‹œ" + disabled={!(inputComment.length > 0)} + onClick={this.addComment} + /> + </form> + </article> + ); + } +} + +export default Feed;
JavaScript
- setState ๊ฐ€ ๊ธฐ์กด์˜ state ๊ฐ’์— **๋ณ‘ํ•ฉ** ํ•˜๋Š” ์˜คํผ๋ ˆ์ด์…˜ ์ด๊ธฐ ๋•Œ๋ฌธ์—, ...this.state ๋ฅผ ํ•ด์ฃผ์‹ค ํ•„์š”๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. ```suggestion this.setState({ comments: comments.filter(comment => comment.id !== clickedId), }); ```
@@ -0,0 +1,14 @@ +const flowTypeDao = require('../models/flowTypeDao'); +const error = require('../utils/error'); + +const getFlowTypes = async () => { + const flowTypes = await flowTypeDao.getFlowTypes(); + if (flowTypes.length === 0) { + error.throwErr(404, 'NOT_FOUND_TYPE'); + } + return flowTypes; +} + +module.exports = { + getFlowTypes +} \ No newline at end of file
JavaScript
```suggestion return flowTypes; } ``` else ์—†์–ด๋„ ๋  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค :)
@@ -2,12 +2,11 @@ import styled from '@emotion/styled'; import { useRouter } from 'next/router'; import React, { useCallback, useMemo } from 'react'; import { FieldValues } from 'react-hook-form'; -import { useMutation } from 'react-query'; import { useRecoilValue } from 'recoil'; import { useGetFlavors } from '@/apis/flavors'; -import { ICreateReviewPayload, postReview } from '@/apis/review'; -import { uploadImage } from '@/apis/upload/uploadImage'; +import { ICreateReviewPayload, useCreateReviewMutation } from '@/apis/review'; +import { useUploadImageMutation } from '@/apis/upload/uploadImage'; import BottomFloatingButtonArea from '@/components/BottomFloatingButtonArea'; import { BOTTOM_FLOATING_BUTTON_AREA_HEIGHT } from '@/components/BottomFloatingButtonArea/BottomFloatingButtonArea'; import Button, { ButtonCount } from '@/components/Button'; @@ -39,8 +38,8 @@ const ReviewDetailContainer: React.FC<RecordThirdStepContainerProps> = ({ const router = useRouter(); const reviewForm = useRecoilValue($reviewForm); const { data: flavors } = useGetFlavors(); - const { mutateAsync: uploadImageMutation } = useMutation(uploadImage); - const { mutateAsync: createReviewMutation } = useMutation(postReview); + const { uploadImage } = useUploadImageMutation(); + const { createReview } = useCreateReviewMutation(); // const { mutateAsync: updateRecordMutation } = useMutation(updateRecord, { // onSuccess: () => { // router.back(); @@ -60,25 +59,25 @@ const ReviewDetailContainer: React.FC<RecordThirdStepContainerProps> = ({ const handleImageUpload = useCallback( async (image: FormData) => { - const { imageUrl } = await uploadImageMutation(image); + const { imageUrl } = await uploadImage(image); return imageUrl; }, - [uploadImageMutation], + [uploadImage], ); const handleCreateSubmit = useCallback( (data: FieldValues) => { - createReviewMutation( + createReview( { ...reviewForm, ...data, - beerId: beer.id, + beerId: beer?.id, } as ICreateReviewPayload, { onSuccess: (_data) => router.push(`/record/ticket/${_data.id}?type=${NEW_TYPE}`) }, ); }, - [createReviewMutation, reviewForm, beer.id, router], + [createReview, reviewForm, beer?.id, router], ); // const handleUpdateSubmit = useCallback( @@ -112,7 +111,7 @@ const ReviewDetailContainer: React.FC<RecordThirdStepContainerProps> = ({ > <StyledWrapper> <h2>{'๋‹น์‹ ๋งŒ์˜ ๋งฅ์ฃผ ์ด์•ผ๊ธฐ๋„ ๋“ค๋ ค์ฃผ์„ธ์š”'}</h2> - <p className="body-1">{beer.korName}</p> + <p className="body-1">{beer?.korName}</p> <ImageUploadField name="imageUrl" beer={beer}
Unknown
@hy57in mutation๋„ ํ•œ ๋ฒˆ ๋ž˜ํ•‘ํ•ด์„œ ์‚ฌ์šฉํ•˜๋Š”๊ฑด ์–ด๋– ์‹ ๊ฐ€์š”? ```typescript export const useCreateReviewMutation = () => { const cache = useQueryClient(); const { mutateAsync: createReviewMutation, ...rest } = useMutation(createReview, { onSuccess: async () => { await cache.invalidateQueries(queryKeyFactory.GET_REVIEW); }, }); return { createReview: createReviewMutation, ...rest, }; }; ```
@@ -2,12 +2,11 @@ import styled from '@emotion/styled'; import { useRouter } from 'next/router'; import React, { useCallback, useMemo } from 'react'; import { FieldValues } from 'react-hook-form'; -import { useMutation } from 'react-query'; import { useRecoilValue } from 'recoil'; import { useGetFlavors } from '@/apis/flavors'; -import { ICreateReviewPayload, postReview } from '@/apis/review'; -import { uploadImage } from '@/apis/upload/uploadImage'; +import { ICreateReviewPayload, useCreateReviewMutation } from '@/apis/review'; +import { useUploadImageMutation } from '@/apis/upload/uploadImage'; import BottomFloatingButtonArea from '@/components/BottomFloatingButtonArea'; import { BOTTOM_FLOATING_BUTTON_AREA_HEIGHT } from '@/components/BottomFloatingButtonArea/BottomFloatingButtonArea'; import Button, { ButtonCount } from '@/components/Button'; @@ -39,8 +38,8 @@ const ReviewDetailContainer: React.FC<RecordThirdStepContainerProps> = ({ const router = useRouter(); const reviewForm = useRecoilValue($reviewForm); const { data: flavors } = useGetFlavors(); - const { mutateAsync: uploadImageMutation } = useMutation(uploadImage); - const { mutateAsync: createReviewMutation } = useMutation(postReview); + const { uploadImage } = useUploadImageMutation(); + const { createReview } = useCreateReviewMutation(); // const { mutateAsync: updateRecordMutation } = useMutation(updateRecord, { // onSuccess: () => { // router.back(); @@ -60,25 +59,25 @@ const ReviewDetailContainer: React.FC<RecordThirdStepContainerProps> = ({ const handleImageUpload = useCallback( async (image: FormData) => { - const { imageUrl } = await uploadImageMutation(image); + const { imageUrl } = await uploadImage(image); return imageUrl; }, - [uploadImageMutation], + [uploadImage], ); const handleCreateSubmit = useCallback( (data: FieldValues) => { - createReviewMutation( + createReview( { ...reviewForm, ...data, - beerId: beer.id, + beerId: beer?.id, } as ICreateReviewPayload, { onSuccess: (_data) => router.push(`/record/ticket/${_data.id}?type=${NEW_TYPE}`) }, ); }, - [createReviewMutation, reviewForm, beer.id, router], + [createReview, reviewForm, beer?.id, router], ); // const handleUpdateSubmit = useCallback( @@ -112,7 +111,7 @@ const ReviewDetailContainer: React.FC<RecordThirdStepContainerProps> = ({ > <StyledWrapper> <h2>{'๋‹น์‹ ๋งŒ์˜ ๋งฅ์ฃผ ์ด์•ผ๊ธฐ๋„ ๋“ค๋ ค์ฃผ์„ธ์š”'}</h2> - <p className="body-1">{beer.korName}</p> + <p className="body-1">{beer?.korName}</p> <ImageUploadField name="imageUrl" beer={beer}
Unknown
@hy57in `useGetReviewsByBeer` ๋„ queryKey๋ฅผ queryKeyFactory์—์„œ ๊ฐ€์ ธ์˜ค๋Š” ๋ฐฉ์‹์œผ๋กœ ๋ณ€๊ฒฝํ•˜๋Š”๊ฑฐ ์–ด๋–จ๊นŒ์š”!? ref - https://github.com/beerair/beerair-web/blob/8a3fb178139646a813eac410820e31846c3460c3/src/commons/queryKeyFactory.ts
@@ -2,12 +2,11 @@ import styled from '@emotion/styled'; import { useRouter } from 'next/router'; import React, { useCallback, useMemo } from 'react'; import { FieldValues } from 'react-hook-form'; -import { useMutation } from 'react-query'; import { useRecoilValue } from 'recoil'; import { useGetFlavors } from '@/apis/flavors'; -import { ICreateReviewPayload, postReview } from '@/apis/review'; -import { uploadImage } from '@/apis/upload/uploadImage'; +import { ICreateReviewPayload, useCreateReviewMutation } from '@/apis/review'; +import { useUploadImageMutation } from '@/apis/upload/uploadImage'; import BottomFloatingButtonArea from '@/components/BottomFloatingButtonArea'; import { BOTTOM_FLOATING_BUTTON_AREA_HEIGHT } from '@/components/BottomFloatingButtonArea/BottomFloatingButtonArea'; import Button, { ButtonCount } from '@/components/Button'; @@ -39,8 +38,8 @@ const ReviewDetailContainer: React.FC<RecordThirdStepContainerProps> = ({ const router = useRouter(); const reviewForm = useRecoilValue($reviewForm); const { data: flavors } = useGetFlavors(); - const { mutateAsync: uploadImageMutation } = useMutation(uploadImage); - const { mutateAsync: createReviewMutation } = useMutation(postReview); + const { uploadImage } = useUploadImageMutation(); + const { createReview } = useCreateReviewMutation(); // const { mutateAsync: updateRecordMutation } = useMutation(updateRecord, { // onSuccess: () => { // router.back(); @@ -60,25 +59,25 @@ const ReviewDetailContainer: React.FC<RecordThirdStepContainerProps> = ({ const handleImageUpload = useCallback( async (image: FormData) => { - const { imageUrl } = await uploadImageMutation(image); + const { imageUrl } = await uploadImage(image); return imageUrl; }, - [uploadImageMutation], + [uploadImage], ); const handleCreateSubmit = useCallback( (data: FieldValues) => { - createReviewMutation( + createReview( { ...reviewForm, ...data, - beerId: beer.id, + beerId: beer?.id, } as ICreateReviewPayload, { onSuccess: (_data) => router.push(`/record/ticket/${_data.id}?type=${NEW_TYPE}`) }, ); }, - [createReviewMutation, reviewForm, beer.id, router], + [createReview, reviewForm, beer?.id, router], ); // const handleUpdateSubmit = useCallback( @@ -112,7 +111,7 @@ const ReviewDetailContainer: React.FC<RecordThirdStepContainerProps> = ({ > <StyledWrapper> <h2>{'๋‹น์‹ ๋งŒ์˜ ๋งฅ์ฃผ ์ด์•ผ๊ธฐ๋„ ๋“ค๋ ค์ฃผ์„ธ์š”'}</h2> - <p className="body-1">{beer.korName}</p> + <p className="body-1">{beer?.korName}</p> <ImageUploadField name="imageUrl" beer={beer}
Unknown
[bf34ee2](https://github.com/beerair/beerair-web/pull/162/commits/bf34ee2ba98545a4e64603f0bdad6d5195f50a47) ๋งŒ๋“ค์–ด๋‘์‹  queryKeyFactory ๋ฅผ ์žŠ๊ณ  ์žˆ์—ˆ๋„ค์š”. ํ•ด๋‹น๋ถ€๋ถ„ ์ˆ˜์ •ํ–ˆ์Šต๋‹ˆ๋‹ค! mutaion๋„ ๋ž˜ํ•‘ํ•ด์„œ ์ˆ˜์ •ํ–ˆ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,45 @@ +import { useMutation, useQueryClient } from 'react-query'; + +import request from '@/commons/axios'; +import { queryKeyFactory } from '@/commons/queryKeyFactory'; +import { IBaseResponse, IReview } from '@/types'; + +/** + * ๋ฆฌ๋ทฐ ๋“ฑ๋ก + */ + +export interface ICreateReviewResponseData extends IBaseResponse<IReview> {} + +export interface ICreateReviewPayload { + beerId: number; + content: string; + feelStatus: number; + imageUrl: string; + isPublic: boolean; + flavorIds: number[]; +} + +export const createReview = async (payload: ICreateReviewPayload) => { + const res = await request<ICreateReviewResponseData>({ + method: 'post', + url: '/api/v1/reviews', + data: { payload }, + }); + + return res.data; +}; + +export const useCreateReviewMutation = () => { + const cache = useQueryClient(); + + const { mutateAsync: createReviewMutation, ...rest } = useMutation(createReview, { + onSuccess: async () => { + await cache.invalidateQueries(queryKeyFactory.GET_REVIEW()); + }, + }); + + return { + createReview: createReviewMutation, + ...rest, + }; +};
TypeScript
@hy57in ๋ฆฌ๋ทฐ ์ƒ์„ฑ๋˜๊ณ  ํ˜ธ์ถœ๋˜๋Š” success ํ•จ์ˆ˜ ๋‚ด๋ถ€์—์„œ๋Š” ๋ฆฌ๋ทฐ ๋ฆฌ์ŠคํŠธ๋ฅผ invalidate ์‹œ์ผœ์•ผํ•˜์ง€ ์•Š๋‚˜์š”..?
@@ -0,0 +1,45 @@ +import { useMutation, useQueryClient } from 'react-query'; + +import request from '@/commons/axios'; +import { queryKeyFactory } from '@/commons/queryKeyFactory'; +import { IBaseResponse, IReview } from '@/types'; + +/** + * ๋ฆฌ๋ทฐ ๋“ฑ๋ก + */ + +export interface ICreateReviewResponseData extends IBaseResponse<IReview> {} + +export interface ICreateReviewPayload { + beerId: number; + content: string; + feelStatus: number; + imageUrl: string; + isPublic: boolean; + flavorIds: number[]; +} + +export const createReview = async (payload: ICreateReviewPayload) => { + const res = await request<ICreateReviewResponseData>({ + method: 'post', + url: '/api/v1/reviews', + data: { payload }, + }); + + return res.data; +}; + +export const useCreateReviewMutation = () => { + const cache = useQueryClient(); + + const { mutateAsync: createReviewMutation, ...rest } = useMutation(createReview, { + onSuccess: async () => { + await cache.invalidateQueries(queryKeyFactory.GET_REVIEW()); + }, + }); + + return { + createReview: createReviewMutation, + ...rest, + }; +};
TypeScript
์•„ํ•ซ..! ๋ฆฌ๋ทฐ ๋ฆฌ์ŠคํŠธ๋ฅผ invalidate ํ•˜๋Š” ๊ฒƒ์œผ๋กœ ์ˆ˜์ •ํ–ˆ์Šต๋‹ˆ๋‹ค. ๋ฆฌ๋ทฐ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ๐Ÿซข
@@ -97,12 +97,12 @@ const BeerTicketTitle: React.FC<BeerTicketTitleProps> = ({ {sliceAndUpperCase(beer?.country?.engName || 'non', 3)} </span> <div className="ticket-detail"> - {`${beer?.alcohol?.toFixed(1)}%`} + {beer?.alcohol ? `${beer.alcohol?.toFixed(1)}%` : '-'} <span className="ticket-detail-split-dot">{'โ€ข'}</span> - {beer?.type?.korName} + {beer?.type?.korName ?? '-'} </div> </div> - <span className="ticket-beer-name">{beer?.korName}</span> + <span className="ticket-beer-name">{beer?.korName ?? '-'}</span> </StyledBeerTicketTitle> ); };
Unknown
'?' ์—†์–ด๋„ ๊ดœ์ฐฎ์„ ๊ฒƒ ๊ฐ™์•„์š”! ```suggestion {beer?.alcohol ? `${beer.alcohol.toFixed(1)}%` : '-'} ```
@@ -0,0 +1,41 @@ +package nextstep.security.authorization.manager; + +import nextstep.security.authentication.Authentication; +import nextstep.security.authorization.AuthorizationDecision; +import nextstep.security.authorization.Secured; +import org.aopalliance.intercept.MethodInvocation; +import org.springframework.core.annotation.AnnotationUtils; + +import java.lang.reflect.Method; +import java.util.Collection; +import java.util.Set; + +public class SecuredAuthorizationManager implements AuthorizationManager<MethodInvocation> { + + private final AuthorizationManager<Collection<String>> authorizationManager; + + public SecuredAuthorizationManager() { + this.authorizationManager = new AuthoritiesAuthorizationManager(); + } + + @Override + public AuthorizationDecision check(Authentication authentication, MethodInvocation invocation) { + Method method = invocation.getMethod(); + boolean isGranted = isGranted(authentication, method); + + return new AuthorizationDecision(isGranted); + } + + private boolean isGranted(Authentication authentication, Method method) { + return (authentication != null && checkAuthorization(authentication, method)); + } + + private boolean checkAuthorization(Authentication authentication, Method method) { + if (!method.isAnnotationPresent(Secured.class)) { + return false; + } + + Secured secured = AnnotationUtils.findAnnotation(method, Secured.class); + return this.authorizationManager.check(authentication, Set.of(secured.value())).isGranted(); + } +}
Java
```suggestion if (authentication == null) { return AuthorizationDecision.ACCESS_DENIED; } ``` ๊ถŒํ•œ์— ๋”ฐ๋ฅธ ์˜ˆ์™ธ ์ฒ˜๋ฆฌ๋Š” Interceptor์˜ ์—ญํ• ๋กœ ๋„˜๊ฒจ์ฃผ๋ฉด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,28 @@ +package nextstep.security.authorization.manager; + +import jakarta.servlet.http.HttpServletRequest; +import nextstep.security.authentication.Authentication; +import nextstep.security.authorization.AuthorizationDecision; +import nextstep.security.authorization.access.RequestMatcherEntry; + +import java.util.List; + +public class RequestMatcherDelegatingAuthorizationManager implements AuthorizationManager<HttpServletRequest> { + + private final List<RequestMatcherEntry<AuthorizationManager<HttpServletRequest>>> mappings; + + public RequestMatcherDelegatingAuthorizationManager(List<RequestMatcherEntry<AuthorizationManager<HttpServletRequest>>> mappings) { + this.mappings = mappings; + } + + @Override + public AuthorizationDecision check(Authentication authentication, HttpServletRequest httpServletRequest) { + for (RequestMatcherEntry<AuthorizationManager<HttpServletRequest>> entry : mappings) { + if (entry.getMatcher().matches(httpServletRequest)) { + return entry.getManager().check(authentication, httpServletRequest); + } + } + + return AuthorizationDecision.ACCESS_DENIED; + } +}
Java
AuthorizationManager์— ๋Œ€ํ•œ ์ถ”์ƒํ™”๋ฅผ ์ž˜ ํ•ด์ฃผ์…จ๋„ค์š” ๐Ÿ‘
@@ -1,13 +1,23 @@ package nextstep.app; +import jakarta.servlet.http.HttpServletRequest; import nextstep.app.domain.Member; import nextstep.app.domain.MemberRepository; import nextstep.security.authentication.AuthenticationException; import nextstep.security.authentication.BasicAuthenticationFilter; import nextstep.security.authentication.UsernamePasswordAuthenticationFilter; -import nextstep.security.authorization.CheckAuthenticationFilter; -import nextstep.security.authorization.SecuredAspect; +import nextstep.security.authorization.AuthorizationFilter; import nextstep.security.authorization.SecuredMethodInterceptor; +import nextstep.security.authorization.access.AnyRequestMatcher; +import nextstep.security.authorization.access.MvcRequestMatcher; +import nextstep.security.authorization.access.RequestMatcherEntry; +import nextstep.security.authorization.manager.AuthenticatedAuthorizationManager; +import nextstep.security.authorization.manager.DenyAllAuthorizationManager; +import nextstep.security.authorization.manager.HasAuthorityAuthorizationManager; +import nextstep.security.authorization.manager.AuthorizationManager; +import nextstep.security.authorization.manager.PermitAllAuthorizationManager; +import nextstep.security.authorization.manager.RequestMatcherDelegatingAuthorizationManager; +import nextstep.security.authorization.manager.SecuredAuthorizationManager; import nextstep.security.config.DefaultSecurityFilterChain; import nextstep.security.config.DelegatingFilterProxy; import nextstep.security.config.FilterChainProxy; @@ -18,7 +28,9 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.http.HttpMethod; +import java.util.ArrayList; import java.util.List; import java.util.Set; @@ -42,23 +54,14 @@ public FilterChainProxy filterChainProxy(List<SecurityFilterChain> securityFilte return new FilterChainProxy(securityFilterChains); } - @Bean - public SecuredMethodInterceptor securedMethodInterceptor() { - return new SecuredMethodInterceptor(); - } -// @Bean -// public SecuredAspect securedAspect() { -// return new SecuredAspect(); -// } - @Bean public SecurityFilterChain securityFilterChain() { return new DefaultSecurityFilterChain( List.of( new SecurityContextHolderFilter(), new UsernamePasswordAuthenticationFilter(userDetailsService()), new BasicAuthenticationFilter(userDetailsService()), - new CheckAuthenticationFilter() + new AuthorizationFilter(requestAuthorizationManager()) ) ); } @@ -87,4 +90,35 @@ public Set<String> getAuthorities() { }; }; } + + @Bean + public SecuredMethodInterceptor securedMethodInterceptor() { + return new SecuredMethodInterceptor( + new SecuredAuthorizationManager() + ); + } + + @Bean + public RequestMatcherDelegatingAuthorizationManager requestAuthorizationManager() { + List<RequestMatcherEntry<AuthorizationManager<HttpServletRequest>>> mappings = new ArrayList<>(); + + mappings.add(new RequestMatcherEntry<>( + new MvcRequestMatcher(HttpMethod.GET, "/members/me"), + new AuthenticatedAuthorizationManager<>()) + ); + mappings.add(new RequestMatcherEntry<>( + new MvcRequestMatcher(HttpMethod.GET, "/members"), + new HasAuthorityAuthorizationManager<>("ADMIN")) + ); + mappings.add(new RequestMatcherEntry<>( + new MvcRequestMatcher(HttpMethod.GET, "/search"), + new PermitAllAuthorizationManager<>()) + ); + mappings.add(new RequestMatcherEntry<>( + new AnyRequestMatcher(), + new DenyAllAuthorizationManager<>()) + ); + + return new RequestMatcherDelegatingAuthorizationManager(mappings); + } }
Java
`๊ทธ ์™ธ ๋ชจ๋“  ์š”์ฒญ์€ ๊ถŒํ•œ์„ ์ œํ•œํ•˜๊ธฐ ์œ„ํ•ด DenyAllAuthorizationManager๋กœ ์ฒ˜๋ฆฌ` ํ•ด๋‹น ์š”๊ตฌ์‚ฌํ•ญ์ด ๋ฐ˜์˜ ์•ˆ๋˜์–ด ์žˆ๋Š” ๊ฒƒ ๊ฐ™๋„ค์š”!
@@ -1,13 +1,23 @@ package nextstep.app; +import jakarta.servlet.http.HttpServletRequest; import nextstep.app.domain.Member; import nextstep.app.domain.MemberRepository; import nextstep.security.authentication.AuthenticationException; import nextstep.security.authentication.BasicAuthenticationFilter; import nextstep.security.authentication.UsernamePasswordAuthenticationFilter; -import nextstep.security.authorization.CheckAuthenticationFilter; -import nextstep.security.authorization.SecuredAspect; +import nextstep.security.authorization.AuthorizationFilter; import nextstep.security.authorization.SecuredMethodInterceptor; +import nextstep.security.authorization.access.AnyRequestMatcher; +import nextstep.security.authorization.access.MvcRequestMatcher; +import nextstep.security.authorization.access.RequestMatcherEntry; +import nextstep.security.authorization.manager.AuthenticatedAuthorizationManager; +import nextstep.security.authorization.manager.DenyAllAuthorizationManager; +import nextstep.security.authorization.manager.HasAuthorityAuthorizationManager; +import nextstep.security.authorization.manager.AuthorizationManager; +import nextstep.security.authorization.manager.PermitAllAuthorizationManager; +import nextstep.security.authorization.manager.RequestMatcherDelegatingAuthorizationManager; +import nextstep.security.authorization.manager.SecuredAuthorizationManager; import nextstep.security.config.DefaultSecurityFilterChain; import nextstep.security.config.DelegatingFilterProxy; import nextstep.security.config.FilterChainProxy; @@ -18,7 +28,9 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.http.HttpMethod; +import java.util.ArrayList; import java.util.List; import java.util.Set; @@ -42,23 +54,14 @@ public FilterChainProxy filterChainProxy(List<SecurityFilterChain> securityFilte return new FilterChainProxy(securityFilterChains); } - @Bean - public SecuredMethodInterceptor securedMethodInterceptor() { - return new SecuredMethodInterceptor(); - } -// @Bean -// public SecuredAspect securedAspect() { -// return new SecuredAspect(); -// } - @Bean public SecurityFilterChain securityFilterChain() { return new DefaultSecurityFilterChain( List.of( new SecurityContextHolderFilter(), new UsernamePasswordAuthenticationFilter(userDetailsService()), new BasicAuthenticationFilter(userDetailsService()), - new CheckAuthenticationFilter() + new AuthorizationFilter(requestAuthorizationManager()) ) ); } @@ -87,4 +90,35 @@ public Set<String> getAuthorities() { }; }; } + + @Bean + public SecuredMethodInterceptor securedMethodInterceptor() { + return new SecuredMethodInterceptor( + new SecuredAuthorizationManager() + ); + } + + @Bean + public RequestMatcherDelegatingAuthorizationManager requestAuthorizationManager() { + List<RequestMatcherEntry<AuthorizationManager<HttpServletRequest>>> mappings = new ArrayList<>(); + + mappings.add(new RequestMatcherEntry<>( + new MvcRequestMatcher(HttpMethod.GET, "/members/me"), + new AuthenticatedAuthorizationManager<>()) + ); + mappings.add(new RequestMatcherEntry<>( + new MvcRequestMatcher(HttpMethod.GET, "/members"), + new HasAuthorityAuthorizationManager<>("ADMIN")) + ); + mappings.add(new RequestMatcherEntry<>( + new MvcRequestMatcher(HttpMethod.GET, "/search"), + new PermitAllAuthorizationManager<>()) + ); + mappings.add(new RequestMatcherEntry<>( + new AnyRequestMatcher(), + new DenyAllAuthorizationManager<>()) + ); + + return new RequestMatcherDelegatingAuthorizationManager(mappings); + } }
Java
๋ช…ํ™•ํ•œ ์—ญํ• ์„ ๊ตฌ๋ถ„ํ•˜๊ธฐ ์œ„ํ•ด AuthenticatedAuthorizationManager์™€ HasAuthorityAuthorizationManager๋ฅผ ๋ถ„๋ฆฌํ•ด์„œ ๊ตฌํ˜„ํ•ด๋ด๋„ ์ข‹๊ฒ ๋„ค์š”!
@@ -0,0 +1,41 @@ +package nextstep.security.authorization.manager; + +import nextstep.security.authentication.Authentication; +import nextstep.security.authorization.AuthorizationDecision; +import nextstep.security.authorization.Secured; +import org.aopalliance.intercept.MethodInvocation; +import org.springframework.core.annotation.AnnotationUtils; + +import java.lang.reflect.Method; +import java.util.Collection; +import java.util.Set; + +public class SecuredAuthorizationManager implements AuthorizationManager<MethodInvocation> { + + private final AuthorizationManager<Collection<String>> authorizationManager; + + public SecuredAuthorizationManager() { + this.authorizationManager = new AuthoritiesAuthorizationManager(); + } + + @Override + public AuthorizationDecision check(Authentication authentication, MethodInvocation invocation) { + Method method = invocation.getMethod(); + boolean isGranted = isGranted(authentication, method); + + return new AuthorizationDecision(isGranted); + } + + private boolean isGranted(Authentication authentication, Method method) { + return (authentication != null && checkAuthorization(authentication, method)); + } + + private boolean checkAuthorization(Authentication authentication, Method method) { + if (!method.isAnnotationPresent(Secured.class)) { + return false; + } + + Secured secured = AnnotationUtils.findAnnotation(method, Secured.class); + return this.authorizationManager.check(authentication, Set.of(secured.value())).isGranted(); + } +}
Java
์˜ˆ์™ธ ์ฑ…์ž„์€ Interceptor์—์„œ ํ•˜๋Š” ๊ฒƒ์ด ๋งž๋Š” ๊ฒƒ ๊ฐ™์•„์„œ ์ˆ˜์ • ํ•˜์˜€์Šต๋‹ˆ๋‹ค !
@@ -1,13 +1,23 @@ package nextstep.app; +import jakarta.servlet.http.HttpServletRequest; import nextstep.app.domain.Member; import nextstep.app.domain.MemberRepository; import nextstep.security.authentication.AuthenticationException; import nextstep.security.authentication.BasicAuthenticationFilter; import nextstep.security.authentication.UsernamePasswordAuthenticationFilter; -import nextstep.security.authorization.CheckAuthenticationFilter; -import nextstep.security.authorization.SecuredAspect; +import nextstep.security.authorization.AuthorizationFilter; import nextstep.security.authorization.SecuredMethodInterceptor; +import nextstep.security.authorization.access.AnyRequestMatcher; +import nextstep.security.authorization.access.MvcRequestMatcher; +import nextstep.security.authorization.access.RequestMatcherEntry; +import nextstep.security.authorization.manager.AuthenticatedAuthorizationManager; +import nextstep.security.authorization.manager.DenyAllAuthorizationManager; +import nextstep.security.authorization.manager.HasAuthorityAuthorizationManager; +import nextstep.security.authorization.manager.AuthorizationManager; +import nextstep.security.authorization.manager.PermitAllAuthorizationManager; +import nextstep.security.authorization.manager.RequestMatcherDelegatingAuthorizationManager; +import nextstep.security.authorization.manager.SecuredAuthorizationManager; import nextstep.security.config.DefaultSecurityFilterChain; import nextstep.security.config.DelegatingFilterProxy; import nextstep.security.config.FilterChainProxy; @@ -18,7 +28,9 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.http.HttpMethod; +import java.util.ArrayList; import java.util.List; import java.util.Set; @@ -42,23 +54,14 @@ public FilterChainProxy filterChainProxy(List<SecurityFilterChain> securityFilte return new FilterChainProxy(securityFilterChains); } - @Bean - public SecuredMethodInterceptor securedMethodInterceptor() { - return new SecuredMethodInterceptor(); - } -// @Bean -// public SecuredAspect securedAspect() { -// return new SecuredAspect(); -// } - @Bean public SecurityFilterChain securityFilterChain() { return new DefaultSecurityFilterChain( List.of( new SecurityContextHolderFilter(), new UsernamePasswordAuthenticationFilter(userDetailsService()), new BasicAuthenticationFilter(userDetailsService()), - new CheckAuthenticationFilter() + new AuthorizationFilter(requestAuthorizationManager()) ) ); } @@ -87,4 +90,35 @@ public Set<String> getAuthorities() { }; }; } + + @Bean + public SecuredMethodInterceptor securedMethodInterceptor() { + return new SecuredMethodInterceptor( + new SecuredAuthorizationManager() + ); + } + + @Bean + public RequestMatcherDelegatingAuthorizationManager requestAuthorizationManager() { + List<RequestMatcherEntry<AuthorizationManager<HttpServletRequest>>> mappings = new ArrayList<>(); + + mappings.add(new RequestMatcherEntry<>( + new MvcRequestMatcher(HttpMethod.GET, "/members/me"), + new AuthenticatedAuthorizationManager<>()) + ); + mappings.add(new RequestMatcherEntry<>( + new MvcRequestMatcher(HttpMethod.GET, "/members"), + new HasAuthorityAuthorizationManager<>("ADMIN")) + ); + mappings.add(new RequestMatcherEntry<>( + new MvcRequestMatcher(HttpMethod.GET, "/search"), + new PermitAllAuthorizationManager<>()) + ); + mappings.add(new RequestMatcherEntry<>( + new AnyRequestMatcher(), + new DenyAllAuthorizationManager<>()) + ); + + return new RequestMatcherDelegatingAuthorizationManager(mappings); + } }
Java
์•— ์ด๋ถ€๋ถ„์„ ๋นผ๋จน์—ˆ๊ตฐ์š” ใ…Žใ…Žใ…Ž permitAll()์ด ์•„๋‹ˆ๋ผ denyAll()๋กœ ์ฒ˜๋ฆฌํ•œ ๋’ค, ํ…Œ์ŠคํŠธ ์ถ”๊ฐ€ํ•˜๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.
@@ -1,13 +1,23 @@ package nextstep.app; +import jakarta.servlet.http.HttpServletRequest; import nextstep.app.domain.Member; import nextstep.app.domain.MemberRepository; import nextstep.security.authentication.AuthenticationException; import nextstep.security.authentication.BasicAuthenticationFilter; import nextstep.security.authentication.UsernamePasswordAuthenticationFilter; -import nextstep.security.authorization.CheckAuthenticationFilter; -import nextstep.security.authorization.SecuredAspect; +import nextstep.security.authorization.AuthorizationFilter; import nextstep.security.authorization.SecuredMethodInterceptor; +import nextstep.security.authorization.access.AnyRequestMatcher; +import nextstep.security.authorization.access.MvcRequestMatcher; +import nextstep.security.authorization.access.RequestMatcherEntry; +import nextstep.security.authorization.manager.AuthenticatedAuthorizationManager; +import nextstep.security.authorization.manager.DenyAllAuthorizationManager; +import nextstep.security.authorization.manager.HasAuthorityAuthorizationManager; +import nextstep.security.authorization.manager.AuthorizationManager; +import nextstep.security.authorization.manager.PermitAllAuthorizationManager; +import nextstep.security.authorization.manager.RequestMatcherDelegatingAuthorizationManager; +import nextstep.security.authorization.manager.SecuredAuthorizationManager; import nextstep.security.config.DefaultSecurityFilterChain; import nextstep.security.config.DelegatingFilterProxy; import nextstep.security.config.FilterChainProxy; @@ -18,7 +28,9 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.http.HttpMethod; +import java.util.ArrayList; import java.util.List; import java.util.Set; @@ -42,23 +54,14 @@ public FilterChainProxy filterChainProxy(List<SecurityFilterChain> securityFilte return new FilterChainProxy(securityFilterChains); } - @Bean - public SecuredMethodInterceptor securedMethodInterceptor() { - return new SecuredMethodInterceptor(); - } -// @Bean -// public SecuredAspect securedAspect() { -// return new SecuredAspect(); -// } - @Bean public SecurityFilterChain securityFilterChain() { return new DefaultSecurityFilterChain( List.of( new SecurityContextHolderFilter(), new UsernamePasswordAuthenticationFilter(userDetailsService()), new BasicAuthenticationFilter(userDetailsService()), - new CheckAuthenticationFilter() + new AuthorizationFilter(requestAuthorizationManager()) ) ); } @@ -87,4 +90,35 @@ public Set<String> getAuthorities() { }; }; } + + @Bean + public SecuredMethodInterceptor securedMethodInterceptor() { + return new SecuredMethodInterceptor( + new SecuredAuthorizationManager() + ); + } + + @Bean + public RequestMatcherDelegatingAuthorizationManager requestAuthorizationManager() { + List<RequestMatcherEntry<AuthorizationManager<HttpServletRequest>>> mappings = new ArrayList<>(); + + mappings.add(new RequestMatcherEntry<>( + new MvcRequestMatcher(HttpMethod.GET, "/members/me"), + new AuthenticatedAuthorizationManager<>()) + ); + mappings.add(new RequestMatcherEntry<>( + new MvcRequestMatcher(HttpMethod.GET, "/members"), + new HasAuthorityAuthorizationManager<>("ADMIN")) + ); + mappings.add(new RequestMatcherEntry<>( + new MvcRequestMatcher(HttpMethod.GET, "/search"), + new PermitAllAuthorizationManager<>()) + ); + mappings.add(new RequestMatcherEntry<>( + new AnyRequestMatcher(), + new DenyAllAuthorizationManager<>()) + ); + + return new RequestMatcherDelegatingAuthorizationManager(mappings); + } }
Java
์•ˆ๋…•ํ•˜์„ธ์š” ์žฌ์—ฐ๋‹˜ ! ์ œ๊ฐ€ ์ด๋ถ€๋ถ„ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ์ •ํ™•ํ•˜๊ฒŒ ์ดํ•ดํ•˜์ง€๋Š” ๋ชปํ•œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๊ธฐ์กด ์ œ๊ฐ€ ๊ตฌํ˜„ํ•œ ๋ถ€๋ถ„์€ AuthorityAuthorizationManager<T>์—์„œ ์ฒ˜๋ฆฌํ•  ๊ถŒํ•œ๋“ค์„ ๊ฐ€์ง€๊ณ  ์žˆ๊ณ , AuthoritiesAuthorizationManager๋Š” ์ „๋‹ฌ๋ฐ›์€ Role๋“ค๋กœ ๊ฒ€์‚ฌ๋งŒ ํ•˜๋Š” ์ฑ…์ž„์„ ๊ฐ€์ง€๊ณ  ์žˆ๋Š”๋ฐ์š”. HasAuthorityAuthorizationManager๋ผ๋Š” ๊ฒƒ์€ delegateํ•˜์ง€ ์•Š๊ณ , ์Šค์Šค๋กœ ์ฒ˜๋ฆฌํ•  ์—ญํ• ์„ ์•Œ๊ณ  ์žˆ๊ณ  ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฐ์ฒด๋ฅผ ์˜๋ฏธํ•˜์‹œ๋Š” ๊ฒŒ ๋งž์„๊นŒ์š”!?
@@ -1,13 +1,23 @@ package nextstep.app; +import jakarta.servlet.http.HttpServletRequest; import nextstep.app.domain.Member; import nextstep.app.domain.MemberRepository; import nextstep.security.authentication.AuthenticationException; import nextstep.security.authentication.BasicAuthenticationFilter; import nextstep.security.authentication.UsernamePasswordAuthenticationFilter; -import nextstep.security.authorization.CheckAuthenticationFilter; -import nextstep.security.authorization.SecuredAspect; +import nextstep.security.authorization.AuthorizationFilter; import nextstep.security.authorization.SecuredMethodInterceptor; +import nextstep.security.authorization.access.AnyRequestMatcher; +import nextstep.security.authorization.access.MvcRequestMatcher; +import nextstep.security.authorization.access.RequestMatcherEntry; +import nextstep.security.authorization.manager.AuthenticatedAuthorizationManager; +import nextstep.security.authorization.manager.DenyAllAuthorizationManager; +import nextstep.security.authorization.manager.HasAuthorityAuthorizationManager; +import nextstep.security.authorization.manager.AuthorizationManager; +import nextstep.security.authorization.manager.PermitAllAuthorizationManager; +import nextstep.security.authorization.manager.RequestMatcherDelegatingAuthorizationManager; +import nextstep.security.authorization.manager.SecuredAuthorizationManager; import nextstep.security.config.DefaultSecurityFilterChain; import nextstep.security.config.DelegatingFilterProxy; import nextstep.security.config.FilterChainProxy; @@ -18,7 +28,9 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.http.HttpMethod; +import java.util.ArrayList; import java.util.List; import java.util.Set; @@ -42,23 +54,14 @@ public FilterChainProxy filterChainProxy(List<SecurityFilterChain> securityFilte return new FilterChainProxy(securityFilterChains); } - @Bean - public SecuredMethodInterceptor securedMethodInterceptor() { - return new SecuredMethodInterceptor(); - } -// @Bean -// public SecuredAspect securedAspect() { -// return new SecuredAspect(); -// } - @Bean public SecurityFilterChain securityFilterChain() { return new DefaultSecurityFilterChain( List.of( new SecurityContextHolderFilter(), new UsernamePasswordAuthenticationFilter(userDetailsService()), new BasicAuthenticationFilter(userDetailsService()), - new CheckAuthenticationFilter() + new AuthorizationFilter(requestAuthorizationManager()) ) ); } @@ -87,4 +90,35 @@ public Set<String> getAuthorities() { }; }; } + + @Bean + public SecuredMethodInterceptor securedMethodInterceptor() { + return new SecuredMethodInterceptor( + new SecuredAuthorizationManager() + ); + } + + @Bean + public RequestMatcherDelegatingAuthorizationManager requestAuthorizationManager() { + List<RequestMatcherEntry<AuthorizationManager<HttpServletRequest>>> mappings = new ArrayList<>(); + + mappings.add(new RequestMatcherEntry<>( + new MvcRequestMatcher(HttpMethod.GET, "/members/me"), + new AuthenticatedAuthorizationManager<>()) + ); + mappings.add(new RequestMatcherEntry<>( + new MvcRequestMatcher(HttpMethod.GET, "/members"), + new HasAuthorityAuthorizationManager<>("ADMIN")) + ); + mappings.add(new RequestMatcherEntry<>( + new MvcRequestMatcher(HttpMethod.GET, "/search"), + new PermitAllAuthorizationManager<>()) + ); + mappings.add(new RequestMatcherEntry<>( + new AnyRequestMatcher(), + new DenyAllAuthorizationManager<>()) + ); + + return new RequestMatcherDelegatingAuthorizationManager(mappings); + } }
Java
ํ•ด๋‹น ์ฝ”๋ฉ˜ํŠธ๋Š” ํ•ด๋‹น ๊ฐ์ฒด๊ฐ€ ํ•˜๋‚˜์˜ ์—ญํ• ๋งŒ ๋‹ด๋‹นํ•˜๋ฉด ๊ฐ€๋…์„ฑ์ด ๋” ์ข‹์•„์งˆ ๊ฒƒ ๊ฐ™์•„ ๋‚จ๊ธด๊ฑด๋ฐ์š”. ์Šคํ”„๋ง ์‹œํ๋ฆฌํ‹ฐ๋„ ์ฐฌํ˜ธ๋‹˜์ด ๊ตฌํ˜„ํ•˜์‹  ๋ฐฉ์‹์ฒ˜๋Ÿผ ๋ถ„๋ฆฌ๋˜์–ด ์žˆ์ง€ ์•Š์€ ์ฝ”๋“œ๋ผ์„œ ๊ผญ ๋ฐ˜์˜ํ•˜์‹ค ํ•„์š”๋Š” ์—†์ง€๋งŒ.. ์ œ๊ฐ€ ๋ดค์„ ๋• ์Šคํ”„๋ง ์‹œํ๋ฆฌํ‹ฐ๋„ ์—ญํ• ์„ ๊ตฌ๋ถ„ํ•˜๋ฉด ๋” ๊ฐ€๋…์„ฑ์ด ์ข‹์•„์งˆ ๊ฒƒ ๊ฐ™์•„์„œ ใ…‹ใ…‹ ํ•œ ๋ฒˆ ๊ณ ๋ฏผํ•ด๋ณด์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ๋‚จ๊ฒผ์Šต๋‹ˆ๋‹ค~
@@ -0,0 +1,18 @@ +const categoryDao = require('../models/categoryDao'); +const error = require('../utils/error'); + +const getCategory = async (type) => { + const categoryTypes = { + '์ง€์ถœ' : [1, 2, 3], + '์ˆ˜์ž…' : [4] + } + + const categories = await categoryDao.getCategoriesByIds(categoryTypes[type]); + categories.map((category) => { category.type = type }) + + return categories; +} + +module.exports = { + getCategory +} \ No newline at end of file
JavaScript
```suggestion const getCategory = async (type) => { const categoryTypes = { '์ง€์ถœ' : [1, 2, 4], '์ˆ˜์ž…' : [3] } const categories = await categoryDao.getCategoriesByIds(categoryTypes[type]); categories.map((category) => { category.type = type }) return categories } module.exports = { getCategory } ``` 1. ์ˆ˜์ž…/์ง€์ถœ์˜ ํƒ€์ž…๊ณผ categoryId๋ฅผ ๋ชจ๋‘ ํ•˜๋“œ์ฝ”๋”ฉ ํ•ด๋‘๊ธฐ ๋ณด๋‹ค๋Š” ํƒ€์ž…์œผ๋กœ ๋ชจ์•„์„œ ์ •๋ฆฌํ•˜์‹œ๋Š” ๋ฐฉ๋ฒ•์ด ๋ณด๋‹ค ํ™•์žฅ์„ฑ ์žˆ๊ณ , ๊ฐ€๋…์„ฑ๋„ ๋†’์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. 2. category๋ฅผ dao์—์„œ ํ•˜๋‚˜์”ฉ for loop์œผ๋กœ getCategory dao์— query๋ฅผ ๋‚ ๋ฆฌ์‹œ๊ธฐ๋ณด๋‹ค๋Š” getCategoriesByIds ์ด๋ผ๋Š” dao ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“œ์…”์„œ ๋ฐฐ์—ด์„ ํ†ต์งธ๋กœ ์ธ์ž๋กœ ๋ณด๋‚ด๋Š” ๊ฒƒ์ด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜์„œ dao๋‹จ SQL ์ฟผ๋ฆฌ๋ฌธ์—์„œ๋„ ์ธ์ž๋ฅผ ๋ฐฐ์—ด๋กœ ๋ฐ›์œผ์…”์„œ ์—ฌ๋Ÿฌ ์นดํ…Œ๊ณ ๋ฆฌ๋ฅผ ํ•œ ๋ฒˆ์— SELECT ํ•˜๋Š” ๋ฐฉ์‹์„ ์ถ”์ฒœ๋“œ๋ฆฝ๋‹ˆ๋‹ค. Query ๋ฌธ์„ ๋ณด๋‚ด๋Š” ํšŸ์ˆ˜๋ฅผ 3ํšŒ์—์„œ 1ํšŒ๋กœ ์ค„์ด๊ธฐ ์œ„ํ•จ์ž…๋‹ˆ๋‹ค
@@ -0,0 +1,20 @@ +const categoryService = require('../services/categoryService'); +const error = require('../utils/error'); + +const getCategory = async (req, res) => { + try { + const { type } = req.query; + if (!type) { + error.throwErr(400, 'KEY_ERROR'); + } + const categories = await categoryService.getCategory(type); + return res.status(200).json({message: 'GET_SUCCESS', 'category': categories}); + } catch (err) { + console.error(err); + return res.status(err.statusCode || 500).json({message: err.message || 'INTERNAL_SERVER_ERROR'}); + } +} + +module.exports = { + getCategory +} \ No newline at end of file
JavaScript
์—๋Ÿฌ ๋ฐœ์ƒ์‹œ์ผœ ๋ณด์…จ๋‚˜์š”? ๋ชจ๋“  ์—๋Ÿฌ๊ฐ€ 'internal_server_error'๋กœ ๋‚ ํ…๋ฐ, ์˜๋„ํ•˜์‹  ๋ฐ”๊ฐ€ ๋งž์„๊นŒ์š”?
@@ -0,0 +1,18 @@ +const categoryDao = require('../models/categoryDao'); +const error = require('../utils/error'); + +const getCategory = async (type) => { + const categoryTypes = { + '์ง€์ถœ' : [1, 2, 3], + '์ˆ˜์ž…' : [4] + } + + const categories = await categoryDao.getCategoriesByIds(categoryTypes[type]); + categories.map((category) => { category.type = type }) + + return categories; +} + +module.exports = { + getCategory +} \ No newline at end of file
JavaScript
3. ๊ทผ๋ณธ์ ์ธ ์งˆ๋ฌธ์ด ํ•˜๋‚˜ ์žˆ๋Š”๋ฐ, category๊ฐ€ flow_type_id๋ฅผ FK๋กœ ๊ฐ€์ง€๊ณ  ์žˆ์œผ๋ฉด, ํ•˜๋“œ์ฝ”๋”ฉ์„ ์•ˆํ•ด๋„ ๋  ๊ฒƒ ๊ฐ™์€๋ฐ FK ์ƒ์„ฑํ•˜์‹œ๋Š”๊ฒŒ ์ข‹์ง€ ์•Š์„๊นŒ์š”? ์ด๋ถ€๋ถ„์€ ๋ฐฑ์—”๋“œ ํŒ€ ๊ฐ™์ด ๋ผ์šด์ง€์—์„œ ์ € ํ•œ ๋ฒˆ ์ฐพ์•„์™€ ์ฃผ์„ธ์š”!
@@ -0,0 +1,20 @@ +const categoryService = require('../services/categoryService'); +const error = require('../utils/error'); + +const getCategory = async (req, res) => { + try { + const { type } = req.query; + if (!type) { + error.throwErr(400, 'KEY_ERROR'); + } + const categories = await categoryService.getCategory(type); + return res.status(200).json({message: 'GET_SUCCESS', 'category': categories}); + } catch (err) { + console.error(err); + return res.status(err.statusCode || 500).json({message: err.message || 'INTERNAL_SERVER_ERROR'}); + } +} + +module.exports = { + getCategory +} \ No newline at end of file
JavaScript
์•„ ํ•ด๋‹น **error message** ๋ถ€๋ถ„ ์ˆ˜์ •ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค. `=> 'INTERNAL_SERVER_ERROR' || err.message}`
@@ -0,0 +1,14 @@ +const {DataSource} = require('typeorm'); +const dotenv = require('dotenv'); +dotenv.config(); + +const appDataSource = new DataSource({ + type : process.env.TYPEORM_CONNECTION, + host: process.env.TYPEORM_HOST, + port: process.env.TYPEORM_PORT, + username: process.env.TYPEORM_USERNAME, + password: process.env.TYPEORM_PASSWORD, + database: process.env.TYPEORM_DATABASE +}); + +module.exports = { appDataSource } \ No newline at end of file
JavaScript
๋ฐ˜์˜ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค!
@@ -1,4 +1,4 @@ -import { EstimationInputDTO, Estimation } from '#estimations/estimation.types.js'; +import { EstimationInputDTO, Estimation, IsActivate } from '#estimations/estimation.types.js'; import { IEstimationRepository } from '#estimations/interfaces/estimation.repository.interface.js'; import { PrismaService } from '#global/prisma.service.js'; import { FindOptions } from '#types/options.type.js'; @@ -88,4 +88,52 @@ export class EstimationRepository implements IEstimationRepository { take: pageSize, }); } + + // confirmedForId ๊ฐ’์ด null์ด ์•„๋‹ˆ๋ฉด์€ ์ด์‚ฌํ™•์ • ๋๋‚œ๊ฒƒ์ด๋‹ค..~! + async findReviewable(userId: string, moveInfoIds: string[], page: number, pageSize: number) { + const estimations = await this.prisma.estimation.findMany({ + where: { + confirmedForId: { in: moveInfoIds }, // ์™„๋ฃŒ๋œ ์ด์‚ฌ์™€ ์—ฐ๊ฒฐ๋œ ๊ฒฌ์ ์„ ์กฐํšŒ + }, + include: { + driver: true, // ๊ฒฌ์ ๊ณผ ๊ด€๋ จ๋œ ๋“œ๋ผ์ด๋ฒ„ ์ •๋ณด + moveInfo: true, // ๊ฒฌ์ ๊ณผ ๊ด€๋ จ๋œ ์ด์‚ฌ ์ •๋ณด + reviews: true, // ๊ฒฌ์ ์— ์ž‘์„ฑ๋œ ๋ฆฌ๋ทฐ๋“ค + }, + skip: (page - 1) * pageSize, + take: pageSize, + }); + + // ๋ฆฌ๋ทฐ๊ฐ€ ์—†๋Š” ๊ฒฌ์ ๋งŒ ํ•„ํ„ฐ๋ง + return estimations.filter(estimation => !estimation.reviews.some(review => review.ownerId === userId)); + } + + // ์œ ์ €์˜ ์ด์‚ฌ ์ •๋ณด ๋ชฉ๋ก ๊ฐ€์ ธ์˜ค๊ธฐ + async getUserMoveInfos(userId: string) { + return this.prisma.moveInfo.findMany({ + where: { ownerId: userId }, // ๋กœ๊ทธ์ธํ•œ ์œ ์ €์˜ ์ด์‚ฌ๋งŒ ์กฐํšŒํ•˜๊ธฐ + select: { id: true }, // ์ด์‚ฌ ID๋งŒ ์„ ํƒ + }); + } + + // ์ง€์ • ๊ฒฌ์  ์š”์ฒญ ์—ฌ๋ถ€ + async isDesignatedRequest(estimationId: string): Promise<IsActivate> { + const estimation = await this.prisma.estimation.findUnique({ + where: { id: estimationId }, + include: { + moveInfo: { + include: { + requests: { + where: { + status: 'APPLY', // + }, + }, + }, + }, + }, + }); + + // ์ง€์ •์š”์ฒญ์ด๋ฉด 'Active', ์ผ๋ฐ˜์š”์ฒญ์ด๋ฉด 'Inactive' + return estimation?.moveInfo.requests.length > 0 ? IsActivate.Active : IsActivate.Inactive; + } }
TypeScript
์•„๋งˆ๋„ javascript ๋ ˆ๋ฒจ์ด ์•„๋‹ˆ๋ผ prisma์—์„œ findMany ํ•ด์˜ค๋Š” ๋‹จ๊ณ„์—์„œ ์ด ์ž‘์—…์„ ํ•ด์„œ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๋‚˜์ค‘์— ํ•œ ๋ฒˆ ์ฐพ์•„๋ณด๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™๋„ค์š”.
@@ -1,4 +1,4 @@ -import { EstimationInputDTO, Estimation } from '#estimations/estimation.types.js'; +import { EstimationInputDTO, Estimation, IsActivate } from '#estimations/estimation.types.js'; import { IEstimationRepository } from '#estimations/interfaces/estimation.repository.interface.js'; import { PrismaService } from '#global/prisma.service.js'; import { FindOptions } from '#types/options.type.js'; @@ -88,4 +88,52 @@ export class EstimationRepository implements IEstimationRepository { take: pageSize, }); } + + // confirmedForId ๊ฐ’์ด null์ด ์•„๋‹ˆ๋ฉด์€ ์ด์‚ฌํ™•์ • ๋๋‚œ๊ฒƒ์ด๋‹ค..~! + async findReviewable(userId: string, moveInfoIds: string[], page: number, pageSize: number) { + const estimations = await this.prisma.estimation.findMany({ + where: { + confirmedForId: { in: moveInfoIds }, // ์™„๋ฃŒ๋œ ์ด์‚ฌ์™€ ์—ฐ๊ฒฐ๋œ ๊ฒฌ์ ์„ ์กฐํšŒ + }, + include: { + driver: true, // ๊ฒฌ์ ๊ณผ ๊ด€๋ จ๋œ ๋“œ๋ผ์ด๋ฒ„ ์ •๋ณด + moveInfo: true, // ๊ฒฌ์ ๊ณผ ๊ด€๋ จ๋œ ์ด์‚ฌ ์ •๋ณด + reviews: true, // ๊ฒฌ์ ์— ์ž‘์„ฑ๋œ ๋ฆฌ๋ทฐ๋“ค + }, + skip: (page - 1) * pageSize, + take: pageSize, + }); + + // ๋ฆฌ๋ทฐ๊ฐ€ ์—†๋Š” ๊ฒฌ์ ๋งŒ ํ•„ํ„ฐ๋ง + return estimations.filter(estimation => !estimation.reviews.some(review => review.ownerId === userId)); + } + + // ์œ ์ €์˜ ์ด์‚ฌ ์ •๋ณด ๋ชฉ๋ก ๊ฐ€์ ธ์˜ค๊ธฐ + async getUserMoveInfos(userId: string) { + return this.prisma.moveInfo.findMany({ + where: { ownerId: userId }, // ๋กœ๊ทธ์ธํ•œ ์œ ์ €์˜ ์ด์‚ฌ๋งŒ ์กฐํšŒํ•˜๊ธฐ + select: { id: true }, // ์ด์‚ฌ ID๋งŒ ์„ ํƒ + }); + } + + // ์ง€์ • ๊ฒฌ์  ์š”์ฒญ ์—ฌ๋ถ€ + async isDesignatedRequest(estimationId: string): Promise<IsActivate> { + const estimation = await this.prisma.estimation.findUnique({ + where: { id: estimationId }, + include: { + moveInfo: { + include: { + requests: { + where: { + status: 'APPLY', // + }, + }, + }, + }, + }, + }); + + // ์ง€์ •์š”์ฒญ์ด๋ฉด 'Active', ์ผ๋ฐ˜์š”์ฒญ์ด๋ฉด 'Inactive' + return estimation?.moveInfo.requests.length > 0 ? IsActivate.Active : IsActivate.Inactive; + } }
TypeScript
๋„ค!! ์ฐพ์•„๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค !! ํƒœ์˜๋‹˜ ์•Œ๋ ค์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!!!!
@@ -1,9 +1,14 @@ +import java.util.List; import java.util.Scanner; public class InputView { private static final String INPUT_MONEY_MESSAGE = "๊ตฌ์ž…๊ธˆ์•ก์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; private static final String INPUT_WINNING_LOTTO_MESSAGE = "์ง€๋‚œ ์ฃผ ๋‹น์ฒจ ๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + private static final String MANUAL_LOTTO_COUNT_MESSAGE = "์ˆ˜๋™์œผ๋กœ ๊ตฌ๋งคํ•  ๋กœ๋˜ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + private static final String MANUAL_LOTTO_NUMBER_MESSAGE = "์ˆ˜๋™์œผ๋กœ ๊ตฌ๋งคํ•  ๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + + private static final String INPUT_BONUS_NUMBER_MESSAGE = "๋ณด๋„ˆ์Šค ๋ณผ์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; private static Scanner scanner = new Scanner(System.in); @@ -12,6 +17,30 @@ public static int inputMoney() { return Integer.parseInt(scanner.nextLine()); } + public static int manualLottoCount() { + System.out.println(MANUAL_LOTTO_COUNT_MESSAGE); + return Integer.parseInt(scanner.nextLine()); + } + + public static List<LottoNumber> manualLotto(int i, int manualLottoCount) { + if (i == 0) { + System.out.println(MANUAL_LOTTO_NUMBER_MESSAGE); + } + + String inputs = scanner.nextLine(); + if (i != manualLottoCount - 1) { + scanner.nextLine(); + } + + return StringParsingUtils.parseToLottoNumber(inputs); + } + + public static BonusNumber inputBonusNumber() { + System.out.println(INPUT_BONUS_NUMBER_MESSAGE); + int bonusNumber = Integer.parseInt(scanner.nextLine()); + return new BonusNumber(new LottoNumber(bonusNumber)); + } + public static String inputWinningLottoNumber() { System.out.println(INPUT_WINNING_LOTTO_MESSAGE); return scanner.nextLine();
Java
์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ์‹คํ–‰์„ ์‹œ์ผœ๋ณด๋‹ˆ ์ž…๋ ฅ์„ ์—ฐ๋‹ฌ์•„ ๋ฐ›๊ธฐ ๋•Œ๋ฌธ์— ํ•œ ์ค„ ์ž…๋ ฅ์„ ๋ฐ›์€ ํ›„ ์ž…๋ ฅ์„ ํ•œ ๋ฒˆ ๋” ๊ธฐ๋‹ค๋ฆฌ๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค! ์–ด๋–ค ์˜๋„๋กœ ์‚ฌ์šฉํ•˜์‹  ๊ฑธ๊นŒ์š”?
@@ -9,19 +9,24 @@ public LottoGame() { statistics = new TreeMap<>(); } - public int inputMoney(int money) { + public int calculateLottoCount(int money) { return lottoCount = money / Lotto.LOTTO_PRICE; } - public LottoTicket generateAutoLottoTicket() { + public LottoTicket generateLottoTicket(int manualLottoCount) { List<Lotto> lottos = new ArrayList<>(); - for(int i = 0; i < lottoCount; i++) { + + for (int i = 0; i < manualLottoCount; i++) { + lottos.add(ManualLottoGenerator.generate(i, manualLottoCount)); + } + + for(int i = manualLottoCount; i < lottoCount; i++) { lottos.add(AutoLottoGenerator.generate()); } - return generateLottoTicket(lottos); + return makeLottoTicket(lottos); } - private LottoTicket generateLottoTicket(List<Lotto> lottos) { + private LottoTicket makeLottoTicket(List<Lotto> lottos) { return lottoTicket = new LottoTicket(lottos); }
Java
์ˆ˜๋™ ๋กœ๋˜์™€ ์ž๋™ ๋กœ๋˜๋ฅผ ํ•จ๊ป˜ ์ƒ์„ฑํ•˜๊ณ  ์žˆ๋Š”๋ฐ ์ด๋ฅผ ๋ถ„๋ฆฌ์‹œ์ผœ๋ณด๋ฉด ์–ด๋–จ๊นŒ์š”? ``` List<Lotto> lottos = InputView.manualLotto(lottoCount); OutputView.printLottoTicket(game.generateLottoTicket(lottos)); ``` ์ฝ”๋“œ ์ž์ฒด๋กœ generateLottoTicket์—์„œ ์ž๋™๋กœ๋˜๊นŒ์ง€ ์ƒ์„ฑํ•ด์ฃผ๋Š” ๊ฒƒ์ธ์ง€ ํ˜น์€ ์˜๋„ํ•œ๋Œ€๋กœ ์ˆ˜๋™ ๋กœ๋˜์™€ ์ž๋™ ๋กœ๋˜๋ฅผ ํ•จ๊ป˜ ์ƒ์„ฑํ•˜๋Š” ๊ฒƒ์ธ์ง€ ๋ฉ”์„œ๋“œ๋ช…๋งŒ ๋ณด๊ณ ๋Š” ์˜๋ฏธ๊ฐ€ ์กฐ๊ธˆ ๋ชจํ˜ธํ•˜๋‹ค๊ณ  ์ƒ๊ฐ๋ฉ๋‹ˆ๋‹ค. (๊ฐœ์ธ์  ์ƒ๊ฐ์œผ๋กœ) ๊ทธ๋ฆฌ๊ณ  ๋‚˜์ค‘์— ์š”๊ตฌ์‚ฌํ•ญ์ด ๋ณ€๊ฒฝ๋˜์–ด `์ˆ˜๋™ ๋กœ๋˜ ์ƒ์„ฑ๋งŒ` ํ˜น์€ `์ž๋™ ๋กœ๋˜ ์ƒ์„ฑ๋งŒ` ๊ทธ๋ฆฌ๊ณ  ์ง€๊ธˆ๊ณผ ๊ฐ™์ด `์ˆ˜๋™ ๋กœ๋˜์™€ ์ž๋™ ๋กœ๋˜๋ฅผ ์„ž์–ด์„œ` ํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•˜๋Š” ํ˜•ํƒœ๋ผ๋ฉด ๋ฉ”์„œ๋“œ ์ž์ฒด๋กœ ์กฐ๊ธˆ ๋” ๋ถ„๋ช…ํ•œ ์˜๋ฏธ๋ฅผ ๊ฐ€์ง€๊ณ  ๋ฉ”์„œ๋“œ๋ฅผ ์žฌํ™œ์šฉํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์„œ์š” ~
@@ -0,0 +1,12 @@ +public class BonusNumber { + private LottoNumber bonusNumber; + + public BonusNumber(LottoNumber bonusNumber) { + this.bonusNumber = bonusNumber; + } + + public LottoNumber getBonusNumber() { + return bonusNumber; + } +} +
Java
LottoNumber ์ž์ฒด๋„ ์›์‹œ๊ฐ’์„ ํฌ์žฅํ•œ ํ˜•ํƒœ๋กœ LottoNumber ํƒ€์ž…์œผ๋กœ bonusNumber๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š”๋ฐ ์ด๋ฅผ ํ•œ ๋ฒˆ ๋” ํฌ์žฅํ•˜์—ฌ ์‚ฌ์šฉํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ์œผ์‹ค๊นŒ์š”? BonusNumber์—์„œ๋Š” ์–ด๋– ํ•œ ํ–‰์œ„๋ฅผ ํ•˜์ง€ ์•Š๊ณ  ํฌ์žฅ๋œ ๊ฐ’์„ ํ•œ ๋ฒˆ ๋” Wrapping ํ•˜๋Š” ํ˜•ํƒœ๋กœ๋งŒ ์‚ฌ์šฉ๋˜๊ณ  ์žˆ๋Š”๋ฐ ๋ถˆํ•„์š”ํ•ด ๋ณด์—ฌ์„œ์š”~
@@ -43,6 +43,10 @@ public int match(WinningLotto winningLotto) { return matchCount; } + public boolean isBonusMatch(WinningLotto winningLotto) { + return lotto.contains(winningLotto.getBonusNumber()); + } + public boolean contains(LottoNumber lottoNumber) { return lotto.contains(lottoNumber); }
Java
lotto์— ๋ณด๋„ˆ์Šค ์ˆซ์ž๊ฐ€ ํฌํ•จ๋˜์–ด์žˆ๋Š”์ง€ ํŒ๋ณ„ํ•˜๋Š” ์—ญํ• ์„ ํ•˜๋Š” ๋ฉ”์†Œ๋“œ๋กœ ๋ณด์ด๋„ค์š”. ๋‹จ์ˆœํžˆ ํŒ๋ณ„ ์—ฌ๋ถ€๋ผ๋ฉด boolean ํƒ€์ž…์œผ๋กœ ๋ณ€๊ฒฝํ•ด์ฃผ๋ฉด ์–ด๋–จ๊นŒ์š”? ๋งŒ์•ฝ ๋ณด๋„ˆ์Šค ์ˆซ์ž๊ฐ€ 1๊ฐœ ์ด์ƒ์ด๋ผ๋Š” ์š”๊ตฌ์‚ฌํ•ญ ๋ณ€๊ฒฝ์„ ์—ผ๋‘ํ•œ ๊ตฌํ˜„์ด๋ผ๋ฉด 1, 0์„ ๋ฆฌํ„ดํ•˜๋Š” ๊ฒƒ๋ณด๋‹ค ๊ตฌ์ฒด์ ์œผ๋กœ ๋งค์นญ๋œ ๊ฐฏ์ˆ˜๋ฅผ ๋ฆฌํ„ดํ•ด์ฃผ๋Š” ์‹์œผ๋กœ ๋ณ€๊ฒฝํ•ด๋ณด๋ฉด ํ™•์žฅ์— ์œ ๋ฆฌํ•œ ๊ตฌํ˜„์ด ๋  ๊ฒƒ ๊ฐ™์•„์š”. ๋ฉ”์†Œ๋“œ๋ช…๋„ ์˜๋ฏธ์ „๋‹ฌ์„ ์กฐ๊ธˆ ๋” ๋ช…ํ™•ํ•˜๊ฒŒ ํ•˜๋ฉด ์™„๋ฒฝํ•  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹คb
@@ -6,6 +6,8 @@ public class OutputView { private static final String RESULT_STATISTICS_MESSAGE = "๋‹น์ฒจ ํ†ต๊ณ„"; private static final String BOUNDARY_LINE = "---------"; private static final String TOTAL_EARNING_RATIO_MESSAGE = "์ด ์ˆ˜์ต๋ฅ ์€ %s ์ž…๋‹ˆ๋‹ค."; + private static final int SECOND_RANK_COUNT = 5; + private static final int MINIMUM_PRIZE_COUNT = 3; public static void printLottoCount(int lottoCount) { System.out.printf((LOTTO_PURCHASE_COMPLETE_MESSAGE) + "%n", lottoCount); @@ -22,12 +24,29 @@ public static void printStatistics(Map<Rank, Integer> statistics) { System.out.println(BOUNDARY_LINE); for (Rank rank : statistics.keySet()) { - System.out.print(String.format("%d ๊ฐœ ์ผ์น˜ (%d์›)", rank.getMatchCount(), rank.getReward())); - System.out.println(" - " + statistics.get(rank) + "๊ฐœ"); + printResult(rank, statistics); } } public static void printEarningRate(String earningRate) { System.out.printf((TOTAL_EARNING_RATIO_MESSAGE) + "%n", earningRate); } + + private static void printResult(Rank rank, Map<Rank, Integer> statistics) { + if (validateMatchCountIs5(rank)) { + System.out.print(String.format("%d ๊ฐœ ์ผ์น˜, ๋ณด๋„ˆ์Šค ๋ณผ ์ผ์น˜ (%d์›)", rank.getMatchCount(), rank.getReward())); + System.out.println(" - " + statistics.get(rank) + "๊ฐœ"); + } else if (validateMatchCountOver3(rank)) { + System.out.print(String.format("%d ๊ฐœ ์ผ์น˜ (%d์›)", rank.getMatchCount(), rank.getReward())); + System.out.println(" - " + statistics.get(rank) + "๊ฐœ"); + } + } + + private static boolean validateMatchCountIs5(Rank rank) { + return rank.getMatchCount() == SECOND_RANK_COUNT && rank.isBonusMatch(); + } + + private static boolean validateMatchCountOver3(Rank rank) { + return rank.getMatchCount() >= MINIMUM_PRIZE_COUNT; + } } \ No newline at end of file
Java
์ œ์•ฝ์‚ฌํ•ญ ์š”๊ตฌ์‚ฌํ•ญ์„ ๋ฐ˜์˜ํ•  ๋•Œ `rank.getMatch() == 5 && rank.getBonusMatchCount() == 1` ์™€ ๊ฐ™์€ ์ฝ”๋“œ๋ฅผ ๋ฉ”์†Œ๋“œ๋กœ ๋”ฐ๋กœ ๋ถ„๋ฆฌํ•ด์„œ `validateMatchCount(rank)`์™€ ๊ฐ™์ด ์ž‘์„ฑํ•œ๋‹ค๋ฉด ์ฝ”๋“œ๋ฅผ ์ฝ๋Š” ๋‹ค๋ฅธ ๊ฐœ๋ฐœ์ž๊ฐ€ ์ œ์•ฝ์‚ฌํ•ญ์„ ํŒŒ์•…ํ•˜๋Š”๋ฐ ๋” ์‰ฌ์šธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๋ฉ”์†Œ๋“œ๋ช…๋งŒ ๋ณด๊ณ  "์ด ์ง€์ ์—์„œ validate ์ฒดํฌ๋ฅผ ํ•˜๋Š” ๊ตฌ๋‚˜"๋ผ๊ณ  ํ•œ๋ˆˆ์— ํŒŒ์•…์ด ๋˜๊ณ , ๊ตฌ์ฒด์ ์ธ ์ œ์•ฝ์‚ฌํ•ญ์ด ๊ถ๊ธˆํ•  ๋• ํ•ด๋‹น ๋ฉ”์†Œ๋“œ ๋‚ด๋ถ€ ๊ตฌํ˜„๋งŒ ์ฐพ์•„๋ณด๋ฉด ๋˜๊ฒŒ ๋ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์ถ”๊ฐ€๋กœ ์ˆซ์ž๋“ค๋„ ์ƒ์ˆ˜ ์ฒ˜๋ฆฌํ•ด์ฃผ๋ฉด ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -1,10 +1,33 @@ +import exception.*; +import java.util.List; + public class Application { public static void main(String[] args) { LottoGame game = new LottoGame(); - OutputView.printLottoCount(game.inputMoney(new Money(InputView.inputMoney()).getMoney())); - OutputView.printLottoTicket(game.generateAutoLottoTicket()); - WinningLotto winningLotto = new WinningLotto(StringParsingUtils.parseToLottoNumber(InputView.inputWinningLottoNumber())); - OutputView.printStatistics(game.calculateRankStatistics(winningLotto)); - OutputView.printEarningRate(game.calculateEarningRatio()); + while (true) { + try { + OutputView.printLottoCount(game.calculateLottoCount(new Money(InputView.inputMoney()).getMoney())); + int manualLottoCount = InputView.manualLottoCount(); + + OutputView.printLottoTicket(game.generateLottoTicket(manualLottoCount)); + List<LottoNumber> lottoNumbers = StringParsingUtils.parseToLottoNumber(InputView.inputWinningLottoNumber()); + BonusNumber bonusNumber = InputView.inputBonusNumber(); + WinningLotto winningLotto = new WinningLotto(lottoNumbers, bonusNumber); + + OutputView.printStatistics(game.calculateRankStatistics(winningLotto)); + OutputView.printEarningRate(game.calculateEarningRatio()); + break; + } catch (MoneyUnderMinMoneyException moneyUnderMinMoneyException) { + System.out.println(moneyUnderMinMoneyException.getMessage()); + } catch (LottoSizeMismatchException lottoSizeMismatchException) { + System.out.println(lottoSizeMismatchException.getMessage()); + } catch (LottoIsNotUniqueException lottoIsNotUniqueException) { + System.out.println(lottoIsNotUniqueException.getMessage()); + } catch (LottoNumberOutOfRangeException lottoNumberOutOfRangeException) { + System.out.println(lottoNumberOutOfRangeException.getMessage()); + } catch (BonusNumberDuplicatedException bonusNumberDuplicatedException) { + System.out.println(bonusNumberDuplicatedException.getMessage()); + } + } } } \ No newline at end of file
Java
ํฐ ์š”์†Œ๋Š” ์•„๋‹ˆ๊ฒ ์ง€๋งŒ ๊ด€๋ จ์„ฑ์— ๋”ฐ๋ผ์„œ ๊ฐœํ–‰์„ ์ถ”๊ฐ€ํ•ด ๊ตฌ๋ถ„ ์ง€์–ด์ฃผ๋Š” ๊ฒƒ๋„ ๊ฐ€๋…์„ฑ์„ ๋†’์ด๋Š” ์š”์†Œ๋ผ๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค!
@@ -1,9 +1,14 @@ +import java.util.List; import java.util.Scanner; public class InputView { private static final String INPUT_MONEY_MESSAGE = "๊ตฌ์ž…๊ธˆ์•ก์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; private static final String INPUT_WINNING_LOTTO_MESSAGE = "์ง€๋‚œ ์ฃผ ๋‹น์ฒจ ๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + private static final String MANUAL_LOTTO_COUNT_MESSAGE = "์ˆ˜๋™์œผ๋กœ ๊ตฌ๋งคํ•  ๋กœ๋˜ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + private static final String MANUAL_LOTTO_NUMBER_MESSAGE = "์ˆ˜๋™์œผ๋กœ ๊ตฌ๋งคํ•  ๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + + private static final String INPUT_BONUS_NUMBER_MESSAGE = "๋ณด๋„ˆ์Šค ๋ณผ์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; private static Scanner scanner = new Scanner(System.in); @@ -12,6 +17,30 @@ public static int inputMoney() { return Integer.parseInt(scanner.nextLine()); } + public static int manualLottoCount() { + System.out.println(MANUAL_LOTTO_COUNT_MESSAGE); + return Integer.parseInt(scanner.nextLine()); + } + + public static List<LottoNumber> manualLotto(int i, int manualLottoCount) { + if (i == 0) { + System.out.println(MANUAL_LOTTO_NUMBER_MESSAGE); + } + + String inputs = scanner.nextLine(); + if (i != manualLottoCount - 1) { + scanner.nextLine(); + } + + return StringParsingUtils.parseToLottoNumber(inputs); + } + + public static BonusNumber inputBonusNumber() { + System.out.println(INPUT_BONUS_NUMBER_MESSAGE); + int bonusNumber = Integer.parseInt(scanner.nextLine()); + return new BonusNumber(new LottoNumber(bonusNumber)); + } + public static String inputWinningLottoNumber() { System.out.println(INPUT_WINNING_LOTTO_MESSAGE); return scanner.nextLine();
Java
InputView์—์„œ ์ˆ˜๋™ ๋กœ๋˜์— ๋Œ€ํ•ด ๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅ ๋ฐ›๋Š” ์—ญํ• ์— ๋”ํ•ด ์ง์ ‘ ๋กœ๋˜๋ฅผ ์ƒ์„ฑํ•˜๋Š” ์—ญํ• ๊นŒ์ง€ ํ•˜๊ณ  ์žˆ๋„ค์š”. ์—ญํ• ์„ ๋ถ„๋ฆฌํ•ด๋ณผ ์ˆ˜ ์žˆ์„๊นŒ์š”? ๋ถ„๋ฆฌํ–ˆ์„ ๋•Œ ์–ด๋–ค ์ด์ ์ด ์ƒ๊ธธ๊นŒ์š”?
@@ -4,44 +4,36 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; public class LottoGameTest { @Test - @DisplayName("์‹ค์ œ ๋กœ๋˜ ์ˆ˜์ต๋ฅ ๊ณผ ์˜ˆ์ƒํ•œ ๋กœ๋˜ ์ˆ˜์ต๋ฅ ์ด ๊ฐ™๋‹ค๋ฉด ์„ฑ๊ณต์ด๋‹ค.") - public void should_success_when_real_lotto_earning_ratio_matches_expected_lotto_yield() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - // given + public void should_success_when_real_lotto_earning_ratio_matches_expected_lotto_yield() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{ LottoGame lottoGame = new LottoGame(); - lottoGame.inputMoney(1000); - - List<LottoNumber> testWinningLotto = new ArrayList<>(); - - for (int i = 1; i < 7; i++){ - testWinningLotto.add(new LottoNumber(i)); + lottoGame.calculateLottoCount(1000); + List<LottoNumber> lottoNumbers = new ArrayList<>(); + for(int i=1; i<7; i++) { + lottoNumbers.add(new LottoNumber(i)); } + List<Lotto> lottos = new ArrayList<>(); + lottos.add(new Lotto(lottoNumbers)); - List<Lotto> autoGeneratedLottos = new ArrayList<>(); - autoGeneratedLottos.add(new Lotto(testWinningLotto)); - - Method method = lottoGame.getClass().getDeclaredMethod("generateLottoTicket",List.class); + Method method = lottoGame.getClass().getDeclaredMethod("makeLottoTicket", List.class); method.setAccessible(true); - method.invoke(lottoGame, autoGeneratedLottos); - - lottoGame.calculateRankStatistics(new WinningLotto(testWinningLotto)); + method.invoke(lottoGame, lottos); - String expectedEarningRatio = "200000000.0"; + WinningLotto winningLotto = new WinningLotto(lottoNumbers, new BonusNumber(new LottoNumber(7))); + lottoGame.calculateRankStatistics(winningLotto); - // when + //when String earningRatio = lottoGame.calculateEarningRatio(); // then - assertThat(earningRatio).isEqualTo(expectedEarningRatio); + assertThat(earningRatio).isEqualTo("200000000.0"); } @Test @@ -53,9 +45,35 @@ public void should_success_when_input_money_return_lotto_as_much_as_input_money( LottoGame lottoGame = new LottoGame(); // when - int lottoCount = lottoGame.inputMoney(money); + int lottoCount = lottoGame.calculateLottoCount(money); // then assertThat(lottoCount).isEqualTo(expectedLottoCount); } + + @Test + @DisplayName("๊ตฌ์ž… ์žฅ์ˆ˜๋งŒํผ ๋กœ๋˜ ํ‹ฐ์ผ“์— ๋กœ๋˜๊ฐ€ ์ถ”๊ฐ€๋œ๋‹ค๋ฉด ์„ฑ๊ณต์ด๋‹ค.") + public void should_success_when_lotto_ticket_can_add_lottos_as_much_as_money() { + // given + int manualLottoCount = 1; + + LottoGame lottoGame = new LottoGame(); + int lottoCount = lottoGame.calculateLottoCount(3000); + + List<LottoNumber> lottoNumbers = new ArrayList<>(); + for (int i = 1; i < 7; i++) { + lottoNumbers.add(new LottoNumber(i)); + } + + List<Lotto> manualLotto = new ArrayList<>(); + for (int i = 0; i < manualLottoCount; i++) { + manualLotto.add(new Lotto(lottoNumbers)); + } + + // when + LottoTicket lottoTicket = lottoGame.generateLottoTicket(manualLottoCount); + + // then + assertThat(lottoTicket.getLottoTicket().size()).isEqualTo(lottoCount); + } } \ No newline at end of file
Java
`inputMoney()`๋ผ๋Š” ์ด๋ฆ„์˜ ๋ฉ”์†Œ๋“œ์˜ ๊ฒฐ๊ณผ๊ฐ’์œผ๋กœ ๋กœ๋˜ ๊ฐฏ์ˆ˜๊ฐ€ ๋‚˜์˜ค๋Š”๊ฒŒ ์กฐ๊ธˆ ์–ด์ƒ‰ํ•œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์ž…๋ ฅ๋ฐ›๋Š” ๋ฉ”์†Œ๋“œ์™€ ๊ฐฏ์ˆ˜๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๋ฉ”์†Œ๋“œ๋กœ ๋ถ„๋ฆฌํ•ด๋ณด๋ฉด ์–ด๋–จ๊นŒ์š”?
@@ -4,44 +4,36 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; public class LottoGameTest { @Test - @DisplayName("์‹ค์ œ ๋กœ๋˜ ์ˆ˜์ต๋ฅ ๊ณผ ์˜ˆ์ƒํ•œ ๋กœ๋˜ ์ˆ˜์ต๋ฅ ์ด ๊ฐ™๋‹ค๋ฉด ์„ฑ๊ณต์ด๋‹ค.") - public void should_success_when_real_lotto_earning_ratio_matches_expected_lotto_yield() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - // given + public void should_success_when_real_lotto_earning_ratio_matches_expected_lotto_yield() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{ LottoGame lottoGame = new LottoGame(); - lottoGame.inputMoney(1000); - - List<LottoNumber> testWinningLotto = new ArrayList<>(); - - for (int i = 1; i < 7; i++){ - testWinningLotto.add(new LottoNumber(i)); + lottoGame.calculateLottoCount(1000); + List<LottoNumber> lottoNumbers = new ArrayList<>(); + for(int i=1; i<7; i++) { + lottoNumbers.add(new LottoNumber(i)); } + List<Lotto> lottos = new ArrayList<>(); + lottos.add(new Lotto(lottoNumbers)); - List<Lotto> autoGeneratedLottos = new ArrayList<>(); - autoGeneratedLottos.add(new Lotto(testWinningLotto)); - - Method method = lottoGame.getClass().getDeclaredMethod("generateLottoTicket",List.class); + Method method = lottoGame.getClass().getDeclaredMethod("makeLottoTicket", List.class); method.setAccessible(true); - method.invoke(lottoGame, autoGeneratedLottos); - - lottoGame.calculateRankStatistics(new WinningLotto(testWinningLotto)); + method.invoke(lottoGame, lottos); - String expectedEarningRatio = "200000000.0"; + WinningLotto winningLotto = new WinningLotto(lottoNumbers, new BonusNumber(new LottoNumber(7))); + lottoGame.calculateRankStatistics(winningLotto); - // when + //when String earningRatio = lottoGame.calculateEarningRatio(); // then - assertThat(earningRatio).isEqualTo(expectedEarningRatio); + assertThat(earningRatio).isEqualTo("200000000.0"); } @Test @@ -53,9 +45,35 @@ public void should_success_when_input_money_return_lotto_as_much_as_input_money( LottoGame lottoGame = new LottoGame(); // when - int lottoCount = lottoGame.inputMoney(money); + int lottoCount = lottoGame.calculateLottoCount(money); // then assertThat(lottoCount).isEqualTo(expectedLottoCount); } + + @Test + @DisplayName("๊ตฌ์ž… ์žฅ์ˆ˜๋งŒํผ ๋กœ๋˜ ํ‹ฐ์ผ“์— ๋กœ๋˜๊ฐ€ ์ถ”๊ฐ€๋œ๋‹ค๋ฉด ์„ฑ๊ณต์ด๋‹ค.") + public void should_success_when_lotto_ticket_can_add_lottos_as_much_as_money() { + // given + int manualLottoCount = 1; + + LottoGame lottoGame = new LottoGame(); + int lottoCount = lottoGame.calculateLottoCount(3000); + + List<LottoNumber> lottoNumbers = new ArrayList<>(); + for (int i = 1; i < 7; i++) { + lottoNumbers.add(new LottoNumber(i)); + } + + List<Lotto> manualLotto = new ArrayList<>(); + for (int i = 0; i < manualLottoCount; i++) { + manualLotto.add(new Lotto(lottoNumbers)); + } + + // when + LottoTicket lottoTicket = lottoGame.generateLottoTicket(manualLottoCount); + + // then + assertThat(lottoTicket.getLottoTicket().size()).isEqualTo(lottoCount); + } } \ No newline at end of file
Java
๊ฒฐ๊ณผ๊ฐ’๊ณผ ๋น„๊ตํ•˜๋Š” ๊ฐ’์„ lottoCount๊ฐ€ ์•„๋‹Œ ์ง์ ‘์ ์ธ ์ˆซ์ž๋กœ ๋น„๊ตํ•˜๋ฉด ์–ด๋–จ๊นŒ์š”? ๋งŒ์•ฝ ์‹ค์ˆ˜๋กœ lottoGame.inputMoney()์—์„œ ์ž…๋ ฅ๋ฐ›์€ ๋ˆ์„ ๋ฐ˜์˜ฌ๋ฆผํ•ด์„œ ์žฅ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•˜๋„๋ก ํ•ด๋ฒ„๋ ธ๋‹ค๋ฉด ํ‹ฐ์ผ“์˜ ์‚ฌ์ด์ฆˆ๊ฐ€ 4๋”๋ผ๋„ ํ…Œ์ŠคํŠธ๊ฐ€ ํ†ต๊ณผํ•˜๊ฒŒ ๋  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์‚ฌ์‹ค ์ง€๊ธˆ ํ…Œ์ŠคํŠธ ์ฝ”๋“œ๋Š” `lottoGame.inputMoney()`๊ฐ€ ๋จผ์ € ๋ณด์žฅ๋˜์–ด์•ผํ•˜๋Š”๋งŒ ์ •ํ™•ํ•œ ํ…Œ์ŠคํŠธ๊ฐ€ ๊ฐ€๋Šฅํ•œ ์ฝ”๋“œ๋ผ๊ณ  ๋ณผ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ํ…Œ์ŠคํŠธ๋ฅผ ํ•˜๋‹ค๋ณด๋ฉด ์–ด์ฉ” ์ˆ˜ ์—†๋Š” ๋ถ€๋ถ„์ผ ์ˆ˜๋„ ์žˆ๊ณ , ์ œ ๋ง์ด ์ •๋‹ต์€ ์•„๋‹ˆ์ง€๋งŒ ๊ฒฐ๊ณผ๊ฐ’์€ ๊ฐ€๊ธ‰์  ๋” ์ •ํ™•ํ•œ ๊ฒƒ์— ์˜์กดํ•ด์•ผํ•˜์ง€ ์•Š์„๊นŒ ์ƒ๊ฐ์ด ๋“ค์–ด ๋ฆฌ๋ทฐ ๋‚จ๊ฒจ๋ดค์Šต๋‹ˆ๋‹ค.
@@ -1,9 +1,14 @@ +import java.util.List; import java.util.Scanner; public class InputView { private static final String INPUT_MONEY_MESSAGE = "๊ตฌ์ž…๊ธˆ์•ก์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; private static final String INPUT_WINNING_LOTTO_MESSAGE = "์ง€๋‚œ ์ฃผ ๋‹น์ฒจ ๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + private static final String MANUAL_LOTTO_COUNT_MESSAGE = "์ˆ˜๋™์œผ๋กœ ๊ตฌ๋งคํ•  ๋กœ๋˜ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + private static final String MANUAL_LOTTO_NUMBER_MESSAGE = "์ˆ˜๋™์œผ๋กœ ๊ตฌ๋งคํ•  ๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + + private static final String INPUT_BONUS_NUMBER_MESSAGE = "๋ณด๋„ˆ์Šค ๋ณผ์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; private static Scanner scanner = new Scanner(System.in); @@ -12,6 +17,30 @@ public static int inputMoney() { return Integer.parseInt(scanner.nextLine()); } + public static int manualLottoCount() { + System.out.println(MANUAL_LOTTO_COUNT_MESSAGE); + return Integer.parseInt(scanner.nextLine()); + } + + public static List<LottoNumber> manualLotto(int i, int manualLottoCount) { + if (i == 0) { + System.out.println(MANUAL_LOTTO_NUMBER_MESSAGE); + } + + String inputs = scanner.nextLine(); + if (i != manualLottoCount - 1) { + scanner.nextLine(); + } + + return StringParsingUtils.parseToLottoNumber(inputs); + } + + public static BonusNumber inputBonusNumber() { + System.out.println(INPUT_BONUS_NUMBER_MESSAGE); + int bonusNumber = Integer.parseInt(scanner.nextLine()); + return new BonusNumber(new LottoNumber(bonusNumber)); + } + public static String inputWinningLottoNumber() { System.out.println(INPUT_WINNING_LOTTO_MESSAGE); return scanner.nextLine();
Java
์ž๋™์ด ์•„๋‹Œ ์ˆ˜๋™์œผ๋กœ ์ž…๋ ฅํ•  ๊ฐฏ์ˆ˜๋งŒํผ ์ž…๋ ฅ์„ ๋ฐ›๋„๋ก ์š”๊ตฌ์‚ฌํ•ญ์ด ๊ธฐ์žฌ๋˜์–ด ์žˆ๊ธฐ ๋•Œ๋ฌธ์—, ๋งŒ์•ฝ `์ˆ˜๋™์œผ๋กœ ๊ตฌ๋งคํ•  ๋กœ๋˜ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.` ์—์„œ 2๊ฐœ๋ฅผ ์ž…๋ ฅํ–ˆ๋‹ค๋ฉด, 2์ค„์˜ ์ž…๋ ฅ ๊ฐ’์„ ๋„ฃ์–ด์ฃผ์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค!
@@ -1,9 +1,14 @@ +import java.util.List; import java.util.Scanner; public class InputView { private static final String INPUT_MONEY_MESSAGE = "๊ตฌ์ž…๊ธˆ์•ก์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; private static final String INPUT_WINNING_LOTTO_MESSAGE = "์ง€๋‚œ ์ฃผ ๋‹น์ฒจ ๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + private static final String MANUAL_LOTTO_COUNT_MESSAGE = "์ˆ˜๋™์œผ๋กœ ๊ตฌ๋งคํ•  ๋กœ๋˜ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + private static final String MANUAL_LOTTO_NUMBER_MESSAGE = "์ˆ˜๋™์œผ๋กœ ๊ตฌ๋งคํ•  ๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + + private static final String INPUT_BONUS_NUMBER_MESSAGE = "๋ณด๋„ˆ์Šค ๋ณผ์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; private static Scanner scanner = new Scanner(System.in); @@ -12,6 +17,30 @@ public static int inputMoney() { return Integer.parseInt(scanner.nextLine()); } + public static int manualLottoCount() { + System.out.println(MANUAL_LOTTO_COUNT_MESSAGE); + return Integer.parseInt(scanner.nextLine()); + } + + public static List<LottoNumber> manualLotto(int i, int manualLottoCount) { + if (i == 0) { + System.out.println(MANUAL_LOTTO_NUMBER_MESSAGE); + } + + String inputs = scanner.nextLine(); + if (i != manualLottoCount - 1) { + scanner.nextLine(); + } + + return StringParsingUtils.parseToLottoNumber(inputs); + } + + public static BonusNumber inputBonusNumber() { + System.out.println(INPUT_BONUS_NUMBER_MESSAGE); + int bonusNumber = Integer.parseInt(scanner.nextLine()); + return new BonusNumber(new LottoNumber(bonusNumber)); + } + public static String inputWinningLottoNumber() { System.out.println(INPUT_WINNING_LOTTO_MESSAGE); return scanner.nextLine();
Java
<img width="370" alt="แ„‰แ…ณแ„แ…ณแ„…แ…ตแ†ซแ„‰แ…ฃแ†บ 2022-07-04 แ„‹แ…ฉแ„’แ…ฎ 7 14 35" src="https://user-images.githubusercontent.com/62830487/177134400-0365bef0-a31c-4a57-9020-e294daa65100.png"> ๋กœ์ง์— ๋ฌธ์ œ๊ฐ€ ์žˆ์–ด๋ณด์ด๋„ค์š”. ์ˆ˜๋™ ๋กœ๋˜ 2์žฅ์„ ๊ตฌ๋งคํ•ด์„œ ๋กœ๋˜ 2์žฅ์˜ ๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ–ˆ๋Š”๋ฐ ์ž…๋ ฅ์„ ํ•œ ๋ฒˆ ๋” ๊ธฐ๋‹ค๋ฆฌ๊ณ  ์žˆ๋„ค์š”. ํ™•์ธ ๋ถ€ํƒ๋“œ๋ ค์š”.
@@ -9,19 +9,24 @@ public LottoGame() { statistics = new TreeMap<>(); } - public int inputMoney(int money) { + public int calculateLottoCount(int money) { return lottoCount = money / Lotto.LOTTO_PRICE; } - public LottoTicket generateAutoLottoTicket() { + public LottoTicket generateLottoTicket(int manualLottoCount) { List<Lotto> lottos = new ArrayList<>(); - for(int i = 0; i < lottoCount; i++) { + + for (int i = 0; i < manualLottoCount; i++) { + lottos.add(ManualLottoGenerator.generate(i, manualLottoCount)); + } + + for(int i = manualLottoCount; i < lottoCount; i++) { lottos.add(AutoLottoGenerator.generate()); } - return generateLottoTicket(lottos); + return makeLottoTicket(lottos); } - private LottoTicket generateLottoTicket(List<Lotto> lottos) { + private LottoTicket makeLottoTicket(List<Lotto> lottos) { return lottoTicket = new LottoTicket(lottos); }
Java
๊ฒฐ๊ตญ์€ ์ˆ˜๋™ ๋กœ๋˜์™€ ์ž๋™ ๋กœ๋˜ ๋ชจ๋‘ ํ•˜๋‚˜์˜ ๋กœ๋˜ ํ‹ฐ์ผ“์œผ๋กœ ํ•ฉ์ณ์ง€๋Š” ๋ถ€๋ถ„์ด ํ•„์š”ํ•˜๊ธฐ ๋•Œ๋ฌธ์—, ํ˜„์žฌ `generateLottoTicket()` ๋‚ด์˜ ์ˆ˜๋™๊ณผ ์ž๋™ ๋กœ๋˜ ์ƒ์„ฑ ๊ฐ๊ฐ์˜ ๋ฐ˜๋ณต๋ฌธ์„ `generateManualLottoTicket()`๊ณผ `generateAutoLottoTicket()` ์œผ๋กœ ๋ฉ”์„œ๋“œ๋ฅผ ๋ถ„๋ฆฌํ•ด๋ณด๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,12 @@ +public class BonusNumber { + private LottoNumber bonusNumber; + + public BonusNumber(LottoNumber bonusNumber) { + this.bonusNumber = bonusNumber; + } + + public LottoNumber getBonusNumber() { + return bonusNumber; + } +} +
Java
@sunghyuki ๊ธฐ์กด์— Lotto ๊ฐ์ฒด๋กœ๋งŒ ๊ตฌ์„ฑ๋œ WinningLotto์— BonusNumber๋ฅผ ์ถ”๊ฐ€ํ•˜์—ฌ, ๋กœ๋˜ ๋‹น์ฒจ ๋ฒˆํ˜ธ ์ค‘ 5๊ฐœ๊ฐ€ ์ผ์น˜ํ•˜๋Š” ๊ฒฝ์šฐ BonusNumber ์ผ์น˜ ์—ฌ๋ถ€ ํ™•์ธ์„ ๋ถ„๋ช…ํ•˜๊ฒŒ ํ•˜๊ธฐ ์œ„ํ•ด LottoNumber ํƒ€์ž…์œผ๋กœ ๊ตฌ์„ฑ๋œ BonusNumber๋ฅผ ์ƒ์„ฑํ–ˆ์Šต๋‹ˆ๋‹ค~
@@ -4,44 +4,36 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; public class LottoGameTest { @Test - @DisplayName("์‹ค์ œ ๋กœ๋˜ ์ˆ˜์ต๋ฅ ๊ณผ ์˜ˆ์ƒํ•œ ๋กœ๋˜ ์ˆ˜์ต๋ฅ ์ด ๊ฐ™๋‹ค๋ฉด ์„ฑ๊ณต์ด๋‹ค.") - public void should_success_when_real_lotto_earning_ratio_matches_expected_lotto_yield() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - // given + public void should_success_when_real_lotto_earning_ratio_matches_expected_lotto_yield() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{ LottoGame lottoGame = new LottoGame(); - lottoGame.inputMoney(1000); - - List<LottoNumber> testWinningLotto = new ArrayList<>(); - - for (int i = 1; i < 7; i++){ - testWinningLotto.add(new LottoNumber(i)); + lottoGame.calculateLottoCount(1000); + List<LottoNumber> lottoNumbers = new ArrayList<>(); + for(int i=1; i<7; i++) { + lottoNumbers.add(new LottoNumber(i)); } + List<Lotto> lottos = new ArrayList<>(); + lottos.add(new Lotto(lottoNumbers)); - List<Lotto> autoGeneratedLottos = new ArrayList<>(); - autoGeneratedLottos.add(new Lotto(testWinningLotto)); - - Method method = lottoGame.getClass().getDeclaredMethod("generateLottoTicket",List.class); + Method method = lottoGame.getClass().getDeclaredMethod("makeLottoTicket", List.class); method.setAccessible(true); - method.invoke(lottoGame, autoGeneratedLottos); - - lottoGame.calculateRankStatistics(new WinningLotto(testWinningLotto)); + method.invoke(lottoGame, lottos); - String expectedEarningRatio = "200000000.0"; + WinningLotto winningLotto = new WinningLotto(lottoNumbers, new BonusNumber(new LottoNumber(7))); + lottoGame.calculateRankStatistics(winningLotto); - // when + //when String earningRatio = lottoGame.calculateEarningRatio(); // then - assertThat(earningRatio).isEqualTo(expectedEarningRatio); + assertThat(earningRatio).isEqualTo("200000000.0"); } @Test @@ -53,9 +45,35 @@ public void should_success_when_input_money_return_lotto_as_much_as_input_money( LottoGame lottoGame = new LottoGame(); // when - int lottoCount = lottoGame.inputMoney(money); + int lottoCount = lottoGame.calculateLottoCount(money); // then assertThat(lottoCount).isEqualTo(expectedLottoCount); } + + @Test + @DisplayName("๊ตฌ์ž… ์žฅ์ˆ˜๋งŒํผ ๋กœ๋˜ ํ‹ฐ์ผ“์— ๋กœ๋˜๊ฐ€ ์ถ”๊ฐ€๋œ๋‹ค๋ฉด ์„ฑ๊ณต์ด๋‹ค.") + public void should_success_when_lotto_ticket_can_add_lottos_as_much_as_money() { + // given + int manualLottoCount = 1; + + LottoGame lottoGame = new LottoGame(); + int lottoCount = lottoGame.calculateLottoCount(3000); + + List<LottoNumber> lottoNumbers = new ArrayList<>(); + for (int i = 1; i < 7; i++) { + lottoNumbers.add(new LottoNumber(i)); + } + + List<Lotto> manualLotto = new ArrayList<>(); + for (int i = 0; i < manualLottoCount; i++) { + manualLotto.add(new Lotto(lottoNumbers)); + } + + // when + LottoTicket lottoTicket = lottoGame.generateLottoTicket(manualLottoCount); + + // then + assertThat(lottoTicket.getLottoTicket().size()).isEqualTo(lottoCount); + } } \ No newline at end of file
Java
@Bellroute ์ €ํฌ๋Š” ์ž…๋ ฅ ๊ธˆ์•ก๋งŒํผ ๋กœ๋˜ ๋ฆฌ์ŠคํŠธ๊ฐ€ ์ž˜ ์ถ”๊ฐ€๋˜๋Š”์ง€ ํ…Œ์ŠคํŠธํ•˜๋ ค๊ณ  ์ž‘์„ฑํ–ˆ๋Š”๋ฐ, ์ ์–ด์ฃผ์‹  ๋ฆฌ๋ทฐ๋ฅผ ์ž˜ ์ดํ•ดํ•˜์ง€ ๋ชปํ•œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๋ถ€์—ฐ ์„ค๋ช… ๋ถ€ํƒ๋“œ๋ ค๋„ ๋ ๊นŒ์š”??
@@ -1,9 +1,14 @@ +import java.util.List; import java.util.Scanner; public class InputView { private static final String INPUT_MONEY_MESSAGE = "๊ตฌ์ž…๊ธˆ์•ก์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; private static final String INPUT_WINNING_LOTTO_MESSAGE = "์ง€๋‚œ ์ฃผ ๋‹น์ฒจ ๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + private static final String MANUAL_LOTTO_COUNT_MESSAGE = "์ˆ˜๋™์œผ๋กœ ๊ตฌ๋งคํ•  ๋กœ๋˜ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + private static final String MANUAL_LOTTO_NUMBER_MESSAGE = "์ˆ˜๋™์œผ๋กœ ๊ตฌ๋งคํ•  ๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + + private static final String INPUT_BONUS_NUMBER_MESSAGE = "๋ณด๋„ˆ์Šค ๋ณผ์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; private static Scanner scanner = new Scanner(System.in); @@ -12,6 +17,30 @@ public static int inputMoney() { return Integer.parseInt(scanner.nextLine()); } + public static int manualLottoCount() { + System.out.println(MANUAL_LOTTO_COUNT_MESSAGE); + return Integer.parseInt(scanner.nextLine()); + } + + public static List<LottoNumber> manualLotto(int i, int manualLottoCount) { + if (i == 0) { + System.out.println(MANUAL_LOTTO_NUMBER_MESSAGE); + } + + String inputs = scanner.nextLine(); + if (i != manualLottoCount - 1) { + scanner.nextLine(); + } + + return StringParsingUtils.parseToLottoNumber(inputs); + } + + public static BonusNumber inputBonusNumber() { + System.out.println(INPUT_BONUS_NUMBER_MESSAGE); + int bonusNumber = Integer.parseInt(scanner.nextLine()); + return new BonusNumber(new LottoNumber(bonusNumber)); + } + public static String inputWinningLottoNumber() { System.out.println(INPUT_WINNING_LOTTO_MESSAGE); return scanner.nextLine();
Java
@Bellroute ๊ธฐ์กด์— ์ €ํฌ๊ฐ€ ์ž‘์„ฑํ•œ ์ฝ”๋“œ๋Š” ์ง€์ ํ•ด์ฃผ์‹  ๊ฒƒ์ฒ˜๋Ÿผ Lottoame ์ฑ…์ž„์„ InputView์—์„œ ๋ถ€์—ฌํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ์ด ๊ฒฝ์šฐ ๋ณ€๊ฒฝ์‚ฌํ•ญ์ด ์ƒ๊ธธ ๋•Œ, InputView์™€ Lotto๋ฅผ ์ƒ์„ฑํ•˜๋Š” LottoGame์„ ๋ชจ๋‘ ์ˆ˜์ •ํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค. ํ™•์ธํ•ด๋ณด๋‹ˆ LottoGame์— ๊ธฐ์กด์— ์ž‘์„ฑํ•ด๋‘” Lotto ์ƒ์„ฑ ๋ฉ”์„œ๋“œ๋ฅผ ํ™œ์šฉํ•ด์„œ ๋ฆฌํŽ™ํ† ๋งํ•˜์˜€์Šต๋‹ˆ๋‹ค.
@@ -3,8 +3,10 @@ import { ParsedUrlQuery } from "querystring"; import { GetServerSideProps } from "next"; import { useState } from "react"; import { useQuery } from "@tanstack/react-query"; +import { getReviewStat, getReviews } from "@/lib/api/ReviewService"; import { getTrainerInfo } from "@/lib/api/trainerService"; import { getFavorite } from "@/lib/api/userService"; +import { ReviewResult } from "@/types/reviews"; import FindTrainerCard from "@/components/Cards/FindTrainerCard"; import { HorizontalLine } from "@/components/Common/Line"; import Loading from "@/components/Common/Loading"; @@ -38,6 +40,7 @@ export const getServerSideProps: GetServerSideProps = async (context) => { export default function DetailTrainer({ trainerId }: { trainerId: string | null }) { const [currentPage, setCurrentPage] = useState<number>(1); + const pageSize = 3; const { data, isLoading, isError } = useQuery( ["trainer-detail", trainerId], () => getTrainerInfo(trainerId as string), @@ -46,22 +49,42 @@ export default function DetailTrainer({ trainerId }: { trainerId: string | null }, ); + const { data: reviewStat } = useQuery(["review-stat"], () => getReviewStat(trainerId as string), { + enabled: !!trainerId, + cacheTime: 5 * 60 * 1000, + staleTime: 5 * 60 * 1000, + }); + const { + data: reviewList, + isLoading: isReviewLoading, + isError: isReviewError, + } = useQuery<ReviewResult>( + ["reviews", currentPage], + () => getReviews(trainerId as string, { page: currentPage, limit: pageSize }), + { + enabled: !!trainerId, + keepPreviousData: true, + }, + ); + const { data: favoriteInfo, isLoading: isFavoriteLoading, isError: isFavoriteError, } = useQuery(["favorite"], () => getFavorite(trainerId as string), { enabled: !!trainerId }); - if (isError || isFavoriteError) return <div>error!!</div>; + if (isError || isReviewError || isFavoriteError) return <div>error!!</div>; const trainerInfo = data?.profile; + const reviews = reviewList?.reviews || []; + const totalCount = reviewList?.totalCount || 0; return ( <div className={clsx( "relative flex flex-col justify-between gap-16 m-auto mt-[2.4rem] mb-16 px-8", "pc:flex-row pc:gap-0 pc:mt-[5.6rem] pc:max-w-[144rem]", - "tablet:max-w-[74.4rem] mobile:max-w-[37.5rem]", + "tablet:max-w-[74.4rem] mobile:max-w-auto", )} > <div className={"flex flex-col gap-[2.4rem] w-full pc:gap-16 pc:pr-[10rem]"}> @@ -73,8 +96,12 @@ export default function DetailTrainer({ trainerId }: { trainerId: string | null <HorizontalLine width="100%" /> <TrainerInfo profile={trainerInfo} /> {/* ๋ฆฌ๋ทฐ ๋ฆฌ์ŠคํŠธ api ์—ฐ๊ฒฐํ•ด์•ผํ•จ */} - <TrainerReview reviewList={trainerInfo} /> - <Pagination currentPage={currentPage} totalPages={5} onPageChange={setCurrentPage} /> + <TrainerReview reviewList={reviews} reviewStat={reviewStat} totalCount={totalCount} /> + <Pagination + currentPage={currentPage} + totalPages={Math.ceil(totalCount / pageSize)} + onPageChange={setCurrentPage} + /> </div> <div className="flex flex-col gap-[2.4rem] pc:gap-16"> <TrainerControl profile={trainerInfo} /> @@ -83,7 +110,7 @@ export default function DetailTrainer({ trainerId }: { trainerId: string | null <ShareSNS label="๋‚˜๋งŒ ์•Œ๊ธฐ์—” ์•„์‰ฌ์šด ๊ฐ•์‚ฌ๋‹˜์ธ๊ฐ€์š”?" trainerInfo={trainerInfo} /> </div> </div> - {isLoading || (isFavoriteLoading && <Loading />)} + {(isLoading || isReviewLoading || isFavoriteLoading) && <Loading />} </div> ); }
Unknown
```js useQuery(["review-stat", trainerId], () => getReviewStat(trainerId as string), { enabled: !!trainerId, cacheTime: 5 * 60 * 1000, staleTime: 5 * 60 * 1000 }); ``` ๋กœ ํ•ด์ฃผ์‹œ๋Š”๊ฒŒ ์ข‹์•„๋ณด์—ฌ์š”.
@@ -3,8 +3,10 @@ import { ParsedUrlQuery } from "querystring"; import { GetServerSideProps } from "next"; import { useState } from "react"; import { useQuery } from "@tanstack/react-query"; +import { getReviewStat, getReviews } from "@/lib/api/ReviewService"; import { getTrainerInfo } from "@/lib/api/trainerService"; import { getFavorite } from "@/lib/api/userService"; +import { ReviewResult } from "@/types/reviews"; import FindTrainerCard from "@/components/Cards/FindTrainerCard"; import { HorizontalLine } from "@/components/Common/Line"; import Loading from "@/components/Common/Loading"; @@ -38,6 +40,7 @@ export const getServerSideProps: GetServerSideProps = async (context) => { export default function DetailTrainer({ trainerId }: { trainerId: string | null }) { const [currentPage, setCurrentPage] = useState<number>(1); + const pageSize = 3; const { data, isLoading, isError } = useQuery( ["trainer-detail", trainerId], () => getTrainerInfo(trainerId as string), @@ -46,22 +49,42 @@ export default function DetailTrainer({ trainerId }: { trainerId: string | null }, ); + const { data: reviewStat } = useQuery(["review-stat"], () => getReviewStat(trainerId as string), { + enabled: !!trainerId, + cacheTime: 5 * 60 * 1000, + staleTime: 5 * 60 * 1000, + }); + const { + data: reviewList, + isLoading: isReviewLoading, + isError: isReviewError, + } = useQuery<ReviewResult>( + ["reviews", currentPage], + () => getReviews(trainerId as string, { page: currentPage, limit: pageSize }), + { + enabled: !!trainerId, + keepPreviousData: true, + }, + ); + const { data: favoriteInfo, isLoading: isFavoriteLoading, isError: isFavoriteError, } = useQuery(["favorite"], () => getFavorite(trainerId as string), { enabled: !!trainerId }); - if (isError || isFavoriteError) return <div>error!!</div>; + if (isError || isReviewError || isFavoriteError) return <div>error!!</div>; const trainerInfo = data?.profile; + const reviews = reviewList?.reviews || []; + const totalCount = reviewList?.totalCount || 0; return ( <div className={clsx( "relative flex flex-col justify-between gap-16 m-auto mt-[2.4rem] mb-16 px-8", "pc:flex-row pc:gap-0 pc:mt-[5.6rem] pc:max-w-[144rem]", - "tablet:max-w-[74.4rem] mobile:max-w-[37.5rem]", + "tablet:max-w-[74.4rem] mobile:max-w-auto", )} > <div className={"flex flex-col gap-[2.4rem] w-full pc:gap-16 pc:pr-[10rem]"}> @@ -73,8 +96,12 @@ export default function DetailTrainer({ trainerId }: { trainerId: string | null <HorizontalLine width="100%" /> <TrainerInfo profile={trainerInfo} /> {/* ๋ฆฌ๋ทฐ ๋ฆฌ์ŠคํŠธ api ์—ฐ๊ฒฐํ•ด์•ผํ•จ */} - <TrainerReview reviewList={trainerInfo} /> - <Pagination currentPage={currentPage} totalPages={5} onPageChange={setCurrentPage} /> + <TrainerReview reviewList={reviews} reviewStat={reviewStat} totalCount={totalCount} /> + <Pagination + currentPage={currentPage} + totalPages={Math.ceil(totalCount / pageSize)} + onPageChange={setCurrentPage} + /> </div> <div className="flex flex-col gap-[2.4rem] pc:gap-16"> <TrainerControl profile={trainerInfo} /> @@ -83,7 +110,7 @@ export default function DetailTrainer({ trainerId }: { trainerId: string | null <ShareSNS label="๋‚˜๋งŒ ์•Œ๊ธฐ์—” ์•„์‰ฌ์šด ๊ฐ•์‚ฌ๋‹˜์ธ๊ฐ€์š”?" trainerInfo={trainerInfo} /> </div> </div> - {isLoading || (isFavoriteLoading && <Loading />)} + {(isLoading || isReviewLoading || isFavoriteLoading) && <Loading />} </div> ); }
Unknown
๋„ต ์ˆ˜์ •ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค!