code stringlengths 41 34.3k | lang stringclasses 8
values | review stringlengths 1 4.74k |
|---|---|---|
@@ -0,0 +1,121 @@
+import React from 'react';
+import { Link } from 'react-router-dom';
+import { withRouter } from 'react-router';
+import './Login.scss';
+
+const REGEXP = {
+ emailRegExp:
+ /[a-zA-Z0-9.-_+!]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]{2,}(?:.[a-zA-Z0-9]{2,3})?/,
+ passwordRegExp: /[a-zA-Z0-9]{5,100}/,
+};
+
+class Login extends React.Component {
+ constructor(props) {
+ super(props);
+
+ this.state = { userId: '', userPw: '' };
+ }
+
+ validate = (value, regExp) => {
+ const reg = new RegExp(regExp);
+ return reg.test(value);
+ };
+
+ validateInputData = (id, pw) => {
+ return (
+ this.validate(id, REGEXP.emailRegExp) &&
+ this.validate(pw, REGEXP.passwordRegExp)
+ );
+ };
+
+ handleInput = e => {
+ const { name, value } = e.target;
+ this.setState({
+ [name]: value,
+ });
+ };
+
+ handleSubmit = e => {
+ e.preventDefault();
+
+ const { userId, userPw } = this.state;
+ if (!this.validateInputData(userId, userPw)) return;
+
+ this.props.history.push('/main');
+ };
+
+ render() {
+ const { userId, userPw } = this.state;
+
+ return (
+ <>
+ <section className="entire-container">
+ <div className="entire">
+ <div className="entire_top content">
+ <div className="login_container">
+ <h1>westagram</h1>
+ <div className="form_container">
+ <form onSubmit={this.handleSubmit}>
+ <input
+ type="text"
+ name="userId"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ value={userId}
+ onChange={this.handleInput}
+ />
+ <input
+ type="password"
+ name="userPw"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ value={userPw}
+ onChange={this.handleInput}
+ />
+ <Link to="/main">
+ <button
+ className="login-button"
+ type="submit"
+ disabled={!this.validateInputData(userId, userPw)}
+ onClick={this.handleSubmit}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ </Link>
+ </form>
+
+ <div className="line_container">
+ <div className="line"></div>
+ <div className="line-word">๋๋</div>
+ <div className="line"></div>
+ </div>
+
+ <button className="social-login-button">
+ <img
+ src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pg0KPCEtLSBHZW5lcmF0b3I6IEFkb2JlIElsbHVzdHJhdG9yIDE4LjAuMCwgU1ZHIEV4cG9ydCBQbHVnLUluIC4gU1ZHIFZlcnNpb246IDYuMDAgQnVpbGQgMCkgIC0tPg0KPCFET0NUWVBFIHN2ZyBQVUJMSUMgIi0vL1czQy8vRFREIFNWRyAxLjEvL0VOIiAiaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkIj4NCjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iQ2FwYV8xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4PSIwcHgiIHk9IjBweCINCgkgdmlld0JveD0iMCAwIDQ1NS43MyA0NTUuNzMiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ1NS43MyA0NTUuNzM7IiB4bWw6c3BhY2U9InByZXNlcnZlIj4NCjxwYXRoIHN0eWxlPSJmaWxsOiMzQTU1OUY7IiBkPSJNMCwwdjQ1NS43M2gyNDIuNzA0VjI3OS42OTFoLTU5LjMzdi03MS44NjRoNTkuMzN2LTYwLjM1M2MwLTQzLjg5MywzNS41ODItNzkuNDc1LDc5LjQ3NS03OS40NzUNCgloNjIuMDI1djY0LjYyMmgtNDQuMzgyYy0xMy45NDcsMC0yNS4yNTQsMTEuMzA3LTI1LjI1NCwyNS4yNTR2NDkuOTUzaDY4LjUyMWwtOS40Nyw3MS44NjRoLTU5LjA1MVY0NTUuNzNINDU1LjczVjBIMHoiLz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjwvc3ZnPg0K"
+ alt="facebook button"
+ />
+ <span>Facebook์ผ๋ก ๋ก๊ทธ์ธ</span>
+ </button>
+ </div>
+
+ <Link to="/" className="search-password">
+ ๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?
+ </Link>
+ </div>
+ </div>
+
+ <div className="entire_bottom content">
+ <p>
+ ๊ณ์ ์ด ์์ผ์ ๊ฐ์?
+ <a href="https://www.instagram.com/accounts/emailsignup/">
+ ๊ฐ์
ํ๊ธฐ
+ </a>
+ </p>
+ </div>
+ </div>
+ </section>
+ </>
+ );
+ }
+}
+
+export default withRouter(Login); | JavaScript | validateInputData ๋ฅผ ํธ์ถํ๊ณ ๊ณ์์ง๋ง ์ด ํจ์๋ ์คํ๋๊ธฐ๋ง ํ๊ณ ๋ฆฌํด๊ฐ์ ์ด๋์๋ ํ์ฉํ์ง ์๊ณ ์๋ ๊ฒ ๊ฐ์ต๋๋ค!
์ค์ง์ ์ผ๋ก ์ด๋ค ์๋ฏธ๋ ์๋ ์ฝ๋๊ฐ์ต๋๋ค! |
@@ -0,0 +1,121 @@
+import React from 'react';
+import { Link } from 'react-router-dom';
+import { withRouter } from 'react-router';
+import './Login.scss';
+
+const REGEXP = {
+ emailRegExp:
+ /[a-zA-Z0-9.-_+!]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]{2,}(?:.[a-zA-Z0-9]{2,3})?/,
+ passwordRegExp: /[a-zA-Z0-9]{5,100}/,
+};
+
+class Login extends React.Component {
+ constructor(props) {
+ super(props);
+
+ this.state = { userId: '', userPw: '' };
+ }
+
+ validate = (value, regExp) => {
+ const reg = new RegExp(regExp);
+ return reg.test(value);
+ };
+
+ validateInputData = (id, pw) => {
+ return (
+ this.validate(id, REGEXP.emailRegExp) &&
+ this.validate(pw, REGEXP.passwordRegExp)
+ );
+ };
+
+ handleInput = e => {
+ const { name, value } = e.target;
+ this.setState({
+ [name]: value,
+ });
+ };
+
+ handleSubmit = e => {
+ e.preventDefault();
+
+ const { userId, userPw } = this.state;
+ if (!this.validateInputData(userId, userPw)) return;
+
+ this.props.history.push('/main');
+ };
+
+ render() {
+ const { userId, userPw } = this.state;
+
+ return (
+ <>
+ <section className="entire-container">
+ <div className="entire">
+ <div className="entire_top content">
+ <div className="login_container">
+ <h1>westagram</h1>
+ <div className="form_container">
+ <form onSubmit={this.handleSubmit}>
+ <input
+ type="text"
+ name="userId"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ value={userId}
+ onChange={this.handleInput}
+ />
+ <input
+ type="password"
+ name="userPw"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ value={userPw}
+ onChange={this.handleInput}
+ />
+ <Link to="/main">
+ <button
+ className="login-button"
+ type="submit"
+ disabled={!this.validateInputData(userId, userPw)}
+ onClick={this.handleSubmit}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ </Link>
+ </form>
+
+ <div className="line_container">
+ <div className="line"></div>
+ <div className="line-word">๋๋</div>
+ <div className="line"></div>
+ </div>
+
+ <button className="social-login-button">
+ <img
+ src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pg0KPCEtLSBHZW5lcmF0b3I6IEFkb2JlIElsbHVzdHJhdG9yIDE4LjAuMCwgU1ZHIEV4cG9ydCBQbHVnLUluIC4gU1ZHIFZlcnNpb246IDYuMDAgQnVpbGQgMCkgIC0tPg0KPCFET0NUWVBFIHN2ZyBQVUJMSUMgIi0vL1czQy8vRFREIFNWRyAxLjEvL0VOIiAiaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkIj4NCjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iQ2FwYV8xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4PSIwcHgiIHk9IjBweCINCgkgdmlld0JveD0iMCAwIDQ1NS43MyA0NTUuNzMiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ1NS43MyA0NTUuNzM7IiB4bWw6c3BhY2U9InByZXNlcnZlIj4NCjxwYXRoIHN0eWxlPSJmaWxsOiMzQTU1OUY7IiBkPSJNMCwwdjQ1NS43M2gyNDIuNzA0VjI3OS42OTFoLTU5LjMzdi03MS44NjRoNTkuMzN2LTYwLjM1M2MwLTQzLjg5MywzNS41ODItNzkuNDc1LDc5LjQ3NS03OS40NzUNCgloNjIuMDI1djY0LjYyMmgtNDQuMzgyYy0xMy45NDcsMC0yNS4yNTQsMTEuMzA3LTI1LjI1NCwyNS4yNTR2NDkuOTUzaDY4LjUyMWwtOS40Nyw3MS44NjRoLTU5LjA1MVY0NTUuNzNINDU1LjczVjBIMHoiLz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjwvc3ZnPg0K"
+ alt="facebook button"
+ />
+ <span>Facebook์ผ๋ก ๋ก๊ทธ์ธ</span>
+ </button>
+ </div>
+
+ <Link to="/" className="search-password">
+ ๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?
+ </Link>
+ </div>
+ </div>
+
+ <div className="entire_bottom content">
+ <p>
+ ๊ณ์ ์ด ์์ผ์ ๊ฐ์?
+ <a href="https://www.instagram.com/accounts/emailsignup/">
+ ๊ฐ์
ํ๊ธฐ
+ </a>
+ </p>
+ </div>
+ </div>
+ </section>
+ </>
+ );
+ }
+}
+
+export default withRouter(Login); | JavaScript | `const {name, value} = e.target;` ์ผ๋ก ๊ตฌ์กฐ๋ถํดํด์ ์ฌ์ฉํ์๋ฉด ์ข ๋ ๊ฐ๊ฒฐํ๊ฒ ๋ค์! |
@@ -0,0 +1,121 @@
+import React from 'react';
+import { Link } from 'react-router-dom';
+import { withRouter } from 'react-router';
+import './Login.scss';
+
+const REGEXP = {
+ emailRegExp:
+ /[a-zA-Z0-9.-_+!]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]{2,}(?:.[a-zA-Z0-9]{2,3})?/,
+ passwordRegExp: /[a-zA-Z0-9]{5,100}/,
+};
+
+class Login extends React.Component {
+ constructor(props) {
+ super(props);
+
+ this.state = { userId: '', userPw: '' };
+ }
+
+ validate = (value, regExp) => {
+ const reg = new RegExp(regExp);
+ return reg.test(value);
+ };
+
+ validateInputData = (id, pw) => {
+ return (
+ this.validate(id, REGEXP.emailRegExp) &&
+ this.validate(pw, REGEXP.passwordRegExp)
+ );
+ };
+
+ handleInput = e => {
+ const { name, value } = e.target;
+ this.setState({
+ [name]: value,
+ });
+ };
+
+ handleSubmit = e => {
+ e.preventDefault();
+
+ const { userId, userPw } = this.state;
+ if (!this.validateInputData(userId, userPw)) return;
+
+ this.props.history.push('/main');
+ };
+
+ render() {
+ const { userId, userPw } = this.state;
+
+ return (
+ <>
+ <section className="entire-container">
+ <div className="entire">
+ <div className="entire_top content">
+ <div className="login_container">
+ <h1>westagram</h1>
+ <div className="form_container">
+ <form onSubmit={this.handleSubmit}>
+ <input
+ type="text"
+ name="userId"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ value={userId}
+ onChange={this.handleInput}
+ />
+ <input
+ type="password"
+ name="userPw"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ value={userPw}
+ onChange={this.handleInput}
+ />
+ <Link to="/main">
+ <button
+ className="login-button"
+ type="submit"
+ disabled={!this.validateInputData(userId, userPw)}
+ onClick={this.handleSubmit}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ </Link>
+ </form>
+
+ <div className="line_container">
+ <div className="line"></div>
+ <div className="line-word">๋๋</div>
+ <div className="line"></div>
+ </div>
+
+ <button className="social-login-button">
+ <img
+ src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pg0KPCEtLSBHZW5lcmF0b3I6IEFkb2JlIElsbHVzdHJhdG9yIDE4LjAuMCwgU1ZHIEV4cG9ydCBQbHVnLUluIC4gU1ZHIFZlcnNpb246IDYuMDAgQnVpbGQgMCkgIC0tPg0KPCFET0NUWVBFIHN2ZyBQVUJMSUMgIi0vL1czQy8vRFREIFNWRyAxLjEvL0VOIiAiaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkIj4NCjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iQ2FwYV8xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4PSIwcHgiIHk9IjBweCINCgkgdmlld0JveD0iMCAwIDQ1NS43MyA0NTUuNzMiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ1NS43MyA0NTUuNzM7IiB4bWw6c3BhY2U9InByZXNlcnZlIj4NCjxwYXRoIHN0eWxlPSJmaWxsOiMzQTU1OUY7IiBkPSJNMCwwdjQ1NS43M2gyNDIuNzA0VjI3OS42OTFoLTU5LjMzdi03MS44NjRoNTkuMzN2LTYwLjM1M2MwLTQzLjg5MywzNS41ODItNzkuNDc1LDc5LjQ3NS03OS40NzUNCgloNjIuMDI1djY0LjYyMmgtNDQuMzgyYy0xMy45NDcsMC0yNS4yNTQsMTEuMzA3LTI1LjI1NCwyNS4yNTR2NDkuOTUzaDY4LjUyMWwtOS40Nyw3MS44NjRoLTU5LjA1MVY0NTUuNzNINDU1LjczVjBIMHoiLz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjwvc3ZnPg0K"
+ alt="facebook button"
+ />
+ <span>Facebook์ผ๋ก ๋ก๊ทธ์ธ</span>
+ </button>
+ </div>
+
+ <Link to="/" className="search-password">
+ ๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?
+ </Link>
+ </div>
+ </div>
+
+ <div className="entire_bottom content">
+ <p>
+ ๊ณ์ ์ด ์์ผ์ ๊ฐ์?
+ <a href="https://www.instagram.com/accounts/emailsignup/">
+ ๊ฐ์
ํ๊ธฐ
+ </a>
+ </p>
+ </div>
+ </div>
+ </section>
+ </>
+ );
+ }
+}
+
+export default withRouter(Login); | JavaScript | ๐
state๊ฐ๋ ๊ตฌ์กฐ๋ถํดํด์ ์ฌ์ฉํ๋ฉด ์ข ๋ ๊ฐ๊ฒฐํด๋ณด์ผ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,121 @@
+import React from 'react';
+import { Link } from 'react-router-dom';
+import { withRouter } from 'react-router';
+import './Login.scss';
+
+const REGEXP = {
+ emailRegExp:
+ /[a-zA-Z0-9.-_+!]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]{2,}(?:.[a-zA-Z0-9]{2,3})?/,
+ passwordRegExp: /[a-zA-Z0-9]{5,100}/,
+};
+
+class Login extends React.Component {
+ constructor(props) {
+ super(props);
+
+ this.state = { userId: '', userPw: '' };
+ }
+
+ validate = (value, regExp) => {
+ const reg = new RegExp(regExp);
+ return reg.test(value);
+ };
+
+ validateInputData = (id, pw) => {
+ return (
+ this.validate(id, REGEXP.emailRegExp) &&
+ this.validate(pw, REGEXP.passwordRegExp)
+ );
+ };
+
+ handleInput = e => {
+ const { name, value } = e.target;
+ this.setState({
+ [name]: value,
+ });
+ };
+
+ handleSubmit = e => {
+ e.preventDefault();
+
+ const { userId, userPw } = this.state;
+ if (!this.validateInputData(userId, userPw)) return;
+
+ this.props.history.push('/main');
+ };
+
+ render() {
+ const { userId, userPw } = this.state;
+
+ return (
+ <>
+ <section className="entire-container">
+ <div className="entire">
+ <div className="entire_top content">
+ <div className="login_container">
+ <h1>westagram</h1>
+ <div className="form_container">
+ <form onSubmit={this.handleSubmit}>
+ <input
+ type="text"
+ name="userId"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ value={userId}
+ onChange={this.handleInput}
+ />
+ <input
+ type="password"
+ name="userPw"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ value={userPw}
+ onChange={this.handleInput}
+ />
+ <Link to="/main">
+ <button
+ className="login-button"
+ type="submit"
+ disabled={!this.validateInputData(userId, userPw)}
+ onClick={this.handleSubmit}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ </Link>
+ </form>
+
+ <div className="line_container">
+ <div className="line"></div>
+ <div className="line-word">๋๋</div>
+ <div className="line"></div>
+ </div>
+
+ <button className="social-login-button">
+ <img
+ src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pg0KPCEtLSBHZW5lcmF0b3I6IEFkb2JlIElsbHVzdHJhdG9yIDE4LjAuMCwgU1ZHIEV4cG9ydCBQbHVnLUluIC4gU1ZHIFZlcnNpb246IDYuMDAgQnVpbGQgMCkgIC0tPg0KPCFET0NUWVBFIHN2ZyBQVUJMSUMgIi0vL1czQy8vRFREIFNWRyAxLjEvL0VOIiAiaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkIj4NCjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iQ2FwYV8xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4PSIwcHgiIHk9IjBweCINCgkgdmlld0JveD0iMCAwIDQ1NS43MyA0NTUuNzMiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ1NS43MyA0NTUuNzM7IiB4bWw6c3BhY2U9InByZXNlcnZlIj4NCjxwYXRoIHN0eWxlPSJmaWxsOiMzQTU1OUY7IiBkPSJNMCwwdjQ1NS43M2gyNDIuNzA0VjI3OS42OTFoLTU5LjMzdi03MS44NjRoNTkuMzN2LTYwLjM1M2MwLTQzLjg5MywzNS41ODItNzkuNDc1LDc5LjQ3NS03OS40NzUNCgloNjIuMDI1djY0LjYyMmgtNDQuMzgyYy0xMy45NDcsMC0yNS4yNTQsMTEuMzA3LTI1LjI1NCwyNS4yNTR2NDkuOTUzaDY4LjUyMWwtOS40Nyw3MS44NjRoLTU5LjA1MVY0NTUuNzNINDU1LjczVjBIMHoiLz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjwvc3ZnPg0K"
+ alt="facebook button"
+ />
+ <span>Facebook์ผ๋ก ๋ก๊ทธ์ธ</span>
+ </button>
+ </div>
+
+ <Link to="/" className="search-password">
+ ๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?
+ </Link>
+ </div>
+ </div>
+
+ <div className="entire_bottom content">
+ <p>
+ ๊ณ์ ์ด ์์ผ์ ๊ฐ์?
+ <a href="https://www.instagram.com/accounts/emailsignup/">
+ ๊ฐ์
ํ๊ธฐ
+ </a>
+ </p>
+ </div>
+ </div>
+ </section>
+ </>
+ );
+ }
+}
+
+export default withRouter(Login); | JavaScript | ๊ฑด์ฐ๋์ด ๋ฆฌ๋ทฐ ์ ๋จ๊ฒจ์ฃผ์
จ๋ค์ ํ์ธํ๊ณ ๋ฐ์ํด๋ณด์ธ์!๐ |
@@ -0,0 +1,121 @@
+import React from 'react';
+import { Link } from 'react-router-dom';
+import { withRouter } from 'react-router';
+import './Login.scss';
+
+const REGEXP = {
+ emailRegExp:
+ /[a-zA-Z0-9.-_+!]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]{2,}(?:.[a-zA-Z0-9]{2,3})?/,
+ passwordRegExp: /[a-zA-Z0-9]{5,100}/,
+};
+
+class Login extends React.Component {
+ constructor(props) {
+ super(props);
+
+ this.state = { userId: '', userPw: '' };
+ }
+
+ validate = (value, regExp) => {
+ const reg = new RegExp(regExp);
+ return reg.test(value);
+ };
+
+ validateInputData = (id, pw) => {
+ return (
+ this.validate(id, REGEXP.emailRegExp) &&
+ this.validate(pw, REGEXP.passwordRegExp)
+ );
+ };
+
+ handleInput = e => {
+ const { name, value } = e.target;
+ this.setState({
+ [name]: value,
+ });
+ };
+
+ handleSubmit = e => {
+ e.preventDefault();
+
+ const { userId, userPw } = this.state;
+ if (!this.validateInputData(userId, userPw)) return;
+
+ this.props.history.push('/main');
+ };
+
+ render() {
+ const { userId, userPw } = this.state;
+
+ return (
+ <>
+ <section className="entire-container">
+ <div className="entire">
+ <div className="entire_top content">
+ <div className="login_container">
+ <h1>westagram</h1>
+ <div className="form_container">
+ <form onSubmit={this.handleSubmit}>
+ <input
+ type="text"
+ name="userId"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ value={userId}
+ onChange={this.handleInput}
+ />
+ <input
+ type="password"
+ name="userPw"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ value={userPw}
+ onChange={this.handleInput}
+ />
+ <Link to="/main">
+ <button
+ className="login-button"
+ type="submit"
+ disabled={!this.validateInputData(userId, userPw)}
+ onClick={this.handleSubmit}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ </Link>
+ </form>
+
+ <div className="line_container">
+ <div className="line"></div>
+ <div className="line-word">๋๋</div>
+ <div className="line"></div>
+ </div>
+
+ <button className="social-login-button">
+ <img
+ src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pg0KPCEtLSBHZW5lcmF0b3I6IEFkb2JlIElsbHVzdHJhdG9yIDE4LjAuMCwgU1ZHIEV4cG9ydCBQbHVnLUluIC4gU1ZHIFZlcnNpb246IDYuMDAgQnVpbGQgMCkgIC0tPg0KPCFET0NUWVBFIHN2ZyBQVUJMSUMgIi0vL1czQy8vRFREIFNWRyAxLjEvL0VOIiAiaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkIj4NCjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iQ2FwYV8xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4PSIwcHgiIHk9IjBweCINCgkgdmlld0JveD0iMCAwIDQ1NS43MyA0NTUuNzMiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ1NS43MyA0NTUuNzM7IiB4bWw6c3BhY2U9InByZXNlcnZlIj4NCjxwYXRoIHN0eWxlPSJmaWxsOiMzQTU1OUY7IiBkPSJNMCwwdjQ1NS43M2gyNDIuNzA0VjI3OS42OTFoLTU5LjMzdi03MS44NjRoNTkuMzN2LTYwLjM1M2MwLTQzLjg5MywzNS41ODItNzkuNDc1LDc5LjQ3NS03OS40NzUNCgloNjIuMDI1djY0LjYyMmgtNDQuMzgyYy0xMy45NDcsMC0yNS4yNTQsMTEuMzA3LTI1LjI1NCwyNS4yNTR2NDkuOTUzaDY4LjUyMWwtOS40Nyw3MS44NjRoLTU5LjA1MVY0NTUuNzNINDU1LjczVjBIMHoiLz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjwvc3ZnPg0K"
+ alt="facebook button"
+ />
+ <span>Facebook์ผ๋ก ๋ก๊ทธ์ธ</span>
+ </button>
+ </div>
+
+ <Link to="/" className="search-password">
+ ๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?
+ </Link>
+ </div>
+ </div>
+
+ <div className="entire_bottom content">
+ <p>
+ ๊ณ์ ์ด ์์ผ์ ๊ฐ์?
+ <a href="https://www.instagram.com/accounts/emailsignup/">
+ ๊ฐ์
ํ๊ธฐ
+ </a>
+ </p>
+ </div>
+ </div>
+ </section>
+ </>
+ );
+ }
+}
+
+export default withRouter(Login); | JavaScript | ์ ์ด์ boolean์ ๋ฆฌํดํ๋ ํจ์์ด๊ธฐ ๋๋ฌธ์ not ์ฐ์ฐ์๋ฅผ ํ์ฉํด์
```suggestion
const isDisabled = !this.validateInputData(userId, userPw)
```
button tag์์ ํ๋ฒ๋ง ์ฌ์ฉ๋๋ ๊ฐ์ด๋ผ๋ฉด ๋ฐ๋ก ๋ณ์์ ์ธ ํ ๋น๊ณผ์ ๊ฑฐ์น ํ์ ์์ด ๋ฒํผ ํ๊ทธ ๋ด์ ๋ฐ๋ก ์ ์ด์ค๋ ๋ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,121 @@
+import React from 'react';
+import { Link } from 'react-router-dom';
+import { withRouter } from 'react-router';
+import './Login.scss';
+
+const REGEXP = {
+ emailRegExp:
+ /[a-zA-Z0-9.-_+!]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]{2,}(?:.[a-zA-Z0-9]{2,3})?/,
+ passwordRegExp: /[a-zA-Z0-9]{5,100}/,
+};
+
+class Login extends React.Component {
+ constructor(props) {
+ super(props);
+
+ this.state = { userId: '', userPw: '' };
+ }
+
+ validate = (value, regExp) => {
+ const reg = new RegExp(regExp);
+ return reg.test(value);
+ };
+
+ validateInputData = (id, pw) => {
+ return (
+ this.validate(id, REGEXP.emailRegExp) &&
+ this.validate(pw, REGEXP.passwordRegExp)
+ );
+ };
+
+ handleInput = e => {
+ const { name, value } = e.target;
+ this.setState({
+ [name]: value,
+ });
+ };
+
+ handleSubmit = e => {
+ e.preventDefault();
+
+ const { userId, userPw } = this.state;
+ if (!this.validateInputData(userId, userPw)) return;
+
+ this.props.history.push('/main');
+ };
+
+ render() {
+ const { userId, userPw } = this.state;
+
+ return (
+ <>
+ <section className="entire-container">
+ <div className="entire">
+ <div className="entire_top content">
+ <div className="login_container">
+ <h1>westagram</h1>
+ <div className="form_container">
+ <form onSubmit={this.handleSubmit}>
+ <input
+ type="text"
+ name="userId"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ value={userId}
+ onChange={this.handleInput}
+ />
+ <input
+ type="password"
+ name="userPw"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ value={userPw}
+ onChange={this.handleInput}
+ />
+ <Link to="/main">
+ <button
+ className="login-button"
+ type="submit"
+ disabled={!this.validateInputData(userId, userPw)}
+ onClick={this.handleSubmit}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ </Link>
+ </form>
+
+ <div className="line_container">
+ <div className="line"></div>
+ <div className="line-word">๋๋</div>
+ <div className="line"></div>
+ </div>
+
+ <button className="social-login-button">
+ <img
+ src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pg0KPCEtLSBHZW5lcmF0b3I6IEFkb2JlIElsbHVzdHJhdG9yIDE4LjAuMCwgU1ZHIEV4cG9ydCBQbHVnLUluIC4gU1ZHIFZlcnNpb246IDYuMDAgQnVpbGQgMCkgIC0tPg0KPCFET0NUWVBFIHN2ZyBQVUJMSUMgIi0vL1czQy8vRFREIFNWRyAxLjEvL0VOIiAiaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkIj4NCjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iQ2FwYV8xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4PSIwcHgiIHk9IjBweCINCgkgdmlld0JveD0iMCAwIDQ1NS43MyA0NTUuNzMiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ1NS43MyA0NTUuNzM7IiB4bWw6c3BhY2U9InByZXNlcnZlIj4NCjxwYXRoIHN0eWxlPSJmaWxsOiMzQTU1OUY7IiBkPSJNMCwwdjQ1NS43M2gyNDIuNzA0VjI3OS42OTFoLTU5LjMzdi03MS44NjRoNTkuMzN2LTYwLjM1M2MwLTQzLjg5MywzNS41ODItNzkuNDc1LDc5LjQ3NS03OS40NzUNCgloNjIuMDI1djY0LjYyMmgtNDQuMzgyYy0xMy45NDcsMC0yNS4yNTQsMTEuMzA3LTI1LjI1NCwyNS4yNTR2NDkuOTUzaDY4LjUyMWwtOS40Nyw3MS44NjRoLTU5LjA1MVY0NTUuNzNINDU1LjczVjBIMHoiLz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjwvc3ZnPg0K"
+ alt="facebook button"
+ />
+ <span>Facebook์ผ๋ก ๋ก๊ทธ์ธ</span>
+ </button>
+ </div>
+
+ <Link to="/" className="search-password">
+ ๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?
+ </Link>
+ </div>
+ </div>
+
+ <div className="entire_bottom content">
+ <p>
+ ๊ณ์ ์ด ์์ผ์ ๊ฐ์?
+ <a href="https://www.instagram.com/accounts/emailsignup/">
+ ๊ฐ์
ํ๊ธฐ
+ </a>
+ </p>
+ </div>
+ </div>
+ </section>
+ </>
+ );
+ }
+}
+
+export default withRouter(Login); | JavaScript | ```suggestion
disabled={!this.validateInputData(userId, userPw)}
```
์์ ๋ฌ์๋๋ฆฐ ์ฝ๋ฉํธ์ ์ด์ด์ง๋ ๋ด์ฉ์
๋๋ค! |
@@ -0,0 +1,156 @@
+@import '../Styles/common.scss';
+
+.entire-container {
+ @include flex-set(row, center, center);
+ width: 100%;
+ height: 100vh;
+ background-color: $background-default-color;
+
+ .entire {
+ width: 350px;
+ background-color: $background-default-color;
+
+ .entire_top {
+ height: 380px;
+
+ &.content {
+ padding: 10px 0;
+ margin: 0 0 10px;
+ border: $border-default-set;
+
+ .login_container {
+ @include flex-set(column, center, center);
+
+ h1 {
+ width: 175px;
+ height: 51px;
+ line-height: 51px;
+ margin: 22px auto 12px;
+ font-family: 'Lobster', cursive;
+ @include font-set(40px, 100, null);
+ }
+
+ .form_container {
+ @include flex-set(column);
+ margin: 20px 0 0;
+
+ form {
+ @include flex-set(column);
+
+ input {
+ width: 268px;
+ height: 38px;
+ padding: 9px 0 7px 8px;
+ margin: 0 0 7px 0;
+ border: $border-default-set;
+
+ background: $background-default-color;
+ color: #8e8e8e;
+
+ @include font-set($font-small-size, inherit, 36px);
+ overflow: hidden;
+ outline: 0;
+ text-overflow: ellipsis;
+ }
+
+ a {
+ margin: 9px 0 18px;
+
+ .login-button {
+ width: 268px;
+ height: 30px;
+ background-color: rgb(0, 149, 246);
+ border-radius: 4px;
+ color: #fff;
+ font-weight: $font-bold-weight;
+ opacity: 1;
+
+ &:disabled {
+ cursor: default;
+ opacity: 0.3;
+ }
+ }
+ }
+ }
+
+ .line_container {
+ display: flex;
+ width: 268px;
+ margin: 0 0 28px 0;
+
+ .line {
+ position: relative;
+ top: 0.45em;
+ height: 1px;
+ flex-grow: 1;
+ background-color: #dbdbdb;
+ }
+
+ .line-word {
+ color: #8e8e8e;
+ @include font-set($font-small-size, $font-bold-weight, 15px);
+ margin: 0 25px;
+ }
+ }
+
+ .social-login-button {
+ display: inline;
+ margin-bottom: 20px;
+ border: none;
+ background-color: #fff;
+
+ &:hover {
+ cursor: pointer;
+ }
+
+ img {
+ position: relative;
+ top: 3px;
+ display: inline-block;
+ width: 16px;
+ height: 16px;
+ margin-right: 8px;
+ }
+
+ span {
+ color: rgb(56, 81, 133);
+ @include font-set($font-default-size, $font-bold-weight);
+ }
+ }
+ }
+
+ .search-password {
+ color: #00376b;
+ text-align: center;
+ }
+ }
+ }
+ }
+
+ .entire_bottom {
+ @include flex-set();
+ height: 63px;
+ color: $font-default-color;
+
+ @include font-set($font-default-size, inherit, 63px);
+ text-align: center;
+
+ &.content {
+ padding: 10px 0;
+ margin: 0 0 10px;
+ border: $border-default-set;
+ }
+
+ p {
+ color: $font-default-color;
+ font-size: $font-default-size;
+
+ a {
+ color: #0095f6;
+ font-weight: 600;
+ text-decoration: none;
+ }
+ }
+ }
+ }
+} | Unknown | ์ปดํฌ๋ํธ ์ด๋ฆ์ผ๋ก nesting ์ ์ฉํด์ฃผ์ธ์!
์ด๋ ๊ฒ ๋๋ฉด ๋ค๋ฅธ ์ปดํฌ๋ํธ๋ค์ ์คํ์ผ์๋ ์ํฅ์ ๋ฏธ์น ์ ์์ต๋๋ค! |
@@ -0,0 +1,156 @@
+@import '../Styles/common.scss';
+
+.entire-container {
+ @include flex-set(row, center, center);
+ width: 100%;
+ height: 100vh;
+ background-color: $background-default-color;
+
+ .entire {
+ width: 350px;
+ background-color: $background-default-color;
+
+ .entire_top {
+ height: 380px;
+
+ &.content {
+ padding: 10px 0;
+ margin: 0 0 10px;
+ border: $border-default-set;
+
+ .login_container {
+ @include flex-set(column, center, center);
+
+ h1 {
+ width: 175px;
+ height: 51px;
+ line-height: 51px;
+ margin: 22px auto 12px;
+ font-family: 'Lobster', cursive;
+ @include font-set(40px, 100, null);
+ }
+
+ .form_container {
+ @include flex-set(column);
+ margin: 20px 0 0;
+
+ form {
+ @include flex-set(column);
+
+ input {
+ width: 268px;
+ height: 38px;
+ padding: 9px 0 7px 8px;
+ margin: 0 0 7px 0;
+ border: $border-default-set;
+
+ background: $background-default-color;
+ color: #8e8e8e;
+
+ @include font-set($font-small-size, inherit, 36px);
+ overflow: hidden;
+ outline: 0;
+ text-overflow: ellipsis;
+ }
+
+ a {
+ margin: 9px 0 18px;
+
+ .login-button {
+ width: 268px;
+ height: 30px;
+ background-color: rgb(0, 149, 246);
+ border-radius: 4px;
+ color: #fff;
+ font-weight: $font-bold-weight;
+ opacity: 1;
+
+ &:disabled {
+ cursor: default;
+ opacity: 0.3;
+ }
+ }
+ }
+ }
+
+ .line_container {
+ display: flex;
+ width: 268px;
+ margin: 0 0 28px 0;
+
+ .line {
+ position: relative;
+ top: 0.45em;
+ height: 1px;
+ flex-grow: 1;
+ background-color: #dbdbdb;
+ }
+
+ .line-word {
+ color: #8e8e8e;
+ @include font-set($font-small-size, $font-bold-weight, 15px);
+ margin: 0 25px;
+ }
+ }
+
+ .social-login-button {
+ display: inline;
+ margin-bottom: 20px;
+ border: none;
+ background-color: #fff;
+
+ &:hover {
+ cursor: pointer;
+ }
+
+ img {
+ position: relative;
+ top: 3px;
+ display: inline-block;
+ width: 16px;
+ height: 16px;
+ margin-right: 8px;
+ }
+
+ span {
+ color: rgb(56, 81, 133);
+ @include font-set($font-default-size, $font-bold-weight);
+ }
+ }
+ }
+
+ .search-password {
+ color: #00376b;
+ text-align: center;
+ }
+ }
+ }
+ }
+
+ .entire_bottom {
+ @include flex-set();
+ height: 63px;
+ color: $font-default-color;
+
+ @include font-set($font-default-size, inherit, 63px);
+ text-align: center;
+
+ &.content {
+ padding: 10px 0;
+ margin: 0 0 10px;
+ border: $border-default-set;
+ }
+
+ p {
+ color: $font-default-color;
+ font-size: $font-default-size;
+
+ a {
+ color: #0095f6;
+ font-weight: 600;
+ text-decoration: none;
+ }
+ }
+ }
+ }
+} | Unknown | ๊ณตํต์ ์ผ๋ก ์ ์ฉ๋์ด์ผ ํ๋ ์์ฑ์ด๋ผ๋ฉด common์ ๋ฃ์ด์ฃผ์๋ ๊ฒ ๋ง์ต๋๋ค! |
@@ -0,0 +1,156 @@
+@import '../Styles/common.scss';
+
+.entire-container {
+ @include flex-set(row, center, center);
+ width: 100%;
+ height: 100vh;
+ background-color: $background-default-color;
+
+ .entire {
+ width: 350px;
+ background-color: $background-default-color;
+
+ .entire_top {
+ height: 380px;
+
+ &.content {
+ padding: 10px 0;
+ margin: 0 0 10px;
+ border: $border-default-set;
+
+ .login_container {
+ @include flex-set(column, center, center);
+
+ h1 {
+ width: 175px;
+ height: 51px;
+ line-height: 51px;
+ margin: 22px auto 12px;
+ font-family: 'Lobster', cursive;
+ @include font-set(40px, 100, null);
+ }
+
+ .form_container {
+ @include flex-set(column);
+ margin: 20px 0 0;
+
+ form {
+ @include flex-set(column);
+
+ input {
+ width: 268px;
+ height: 38px;
+ padding: 9px 0 7px 8px;
+ margin: 0 0 7px 0;
+ border: $border-default-set;
+
+ background: $background-default-color;
+ color: #8e8e8e;
+
+ @include font-set($font-small-size, inherit, 36px);
+ overflow: hidden;
+ outline: 0;
+ text-overflow: ellipsis;
+ }
+
+ a {
+ margin: 9px 0 18px;
+
+ .login-button {
+ width: 268px;
+ height: 30px;
+ background-color: rgb(0, 149, 246);
+ border-radius: 4px;
+ color: #fff;
+ font-weight: $font-bold-weight;
+ opacity: 1;
+
+ &:disabled {
+ cursor: default;
+ opacity: 0.3;
+ }
+ }
+ }
+ }
+
+ .line_container {
+ display: flex;
+ width: 268px;
+ margin: 0 0 28px 0;
+
+ .line {
+ position: relative;
+ top: 0.45em;
+ height: 1px;
+ flex-grow: 1;
+ background-color: #dbdbdb;
+ }
+
+ .line-word {
+ color: #8e8e8e;
+ @include font-set($font-small-size, $font-bold-weight, 15px);
+ margin: 0 25px;
+ }
+ }
+
+ .social-login-button {
+ display: inline;
+ margin-bottom: 20px;
+ border: none;
+ background-color: #fff;
+
+ &:hover {
+ cursor: pointer;
+ }
+
+ img {
+ position: relative;
+ top: 3px;
+ display: inline-block;
+ width: 16px;
+ height: 16px;
+ margin-right: 8px;
+ }
+
+ span {
+ color: rgb(56, 81, 133);
+ @include font-set($font-default-size, $font-bold-weight);
+ }
+ }
+ }
+
+ .search-password {
+ color: #00376b;
+ text-align: center;
+ }
+ }
+ }
+ }
+
+ .entire_bottom {
+ @include flex-set();
+ height: 63px;
+ color: $font-default-color;
+
+ @include font-set($font-default-size, inherit, 63px);
+ text-align: center;
+
+ &.content {
+ padding: 10px 0;
+ margin: 0 0 10px;
+ border: $border-default-set;
+ }
+
+ p {
+ color: $font-default-color;
+ font-size: $font-default-size;
+
+ a {
+ color: #0095f6;
+ font-weight: 600;
+ text-decoration: none;
+ }
+ }
+ }
+ }
+} | Unknown | mixin ์ ํ์ฉํด์ฃผ์
จ๋ค์! |
@@ -0,0 +1,12 @@
+package develop.baminchan;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class SidedishApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(SidedishApplication.class, args);
+ }
+} | Java | Security ์ค์ ์ด ๋ณ๋ ํด๋์ค๋ก ๋
๋ฆฝํ๋ฉด ์กฐ๊ธ ๋ ์ข์ ๊ฒ ๊ฐ๋ค์. |
@@ -0,0 +1,75 @@
+package develop.baminchan.controller;
+
+import develop.baminchan.dto.BanchanDto;
+import develop.baminchan.dto.CategoryDto;
+import develop.baminchan.dto.banchan.BanchanDetailDto;
+import develop.baminchan.entity.Banchan;
+import develop.baminchan.service.BanchanService;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.*;
+
+import java.util.List;
+
+@RestController
+@RequestMapping("/api")
+public class BanchanController {
+
+ private BanchanService banchanService;
+
+ public BanchanController(BanchanService banchanService) {
+ this.banchanService = banchanService;
+ }
+
+ @GetMapping("/main")
+ public ResponseEntity<Message> findMain() {
+ List<BanchanDto> banchanDtoList = banchanService.findBanchansByTag("main");
+ Message message = new Message(Message.OK, banchanDtoList);
+ return new ResponseEntity(message, HttpStatus.OK);
+ }
+
+ @GetMapping("/soup")
+ public ResponseEntity<Message> findSoup() {
+ List<BanchanDto> banchanDtoList = banchanService.findBanchansByTag("soup");
+ Message message = new Message(Message.OK, banchanDtoList);
+ return new ResponseEntity(message, HttpStatus.OK);
+ }
+
+ @GetMapping("/side")
+ public ResponseEntity<Message> findSide() {
+ List<BanchanDto> banchanDtoList = banchanService.findBanchansByTag("side");
+ Message message = new Message(Message.OK, banchanDtoList);
+ return new ResponseEntity(message, HttpStatus.OK);
+ }
+ @GetMapping("/main/{detail_hash}")
+ public BanchanDto findOneMain(@PathVariable String detail_hash) {
+ BanchanDto banchanDto = banchanService.findBanchanByDetailHash(detail_hash);
+ return banchanDto;
+ }
+
+ @GetMapping("/soup/{detail_hash}")
+ public BanchanDto findOneSoup(@PathVariable String detail_hash) {
+ BanchanDto banchanDto = banchanService.findBanchanByDetailHash(detail_hash);
+ return banchanDto;
+ }
+
+ @GetMapping("/side/{detail_hash}")
+ public BanchanDto findOneSide(@PathVariable String detail_hash) {
+ BanchanDto banchanDto = banchanService.findBanchanByDetailHash(detail_hash);
+ return banchanDto;
+ }
+
+
+ @GetMapping("/detail/{detail_hash}")
+ public BanchanDetailDto findOneDetail(@PathVariable String detail_hash) {
+ BanchanDetailDto banchanDetailDto = banchanService.findBanchanDetailByDetailHash(detail_hash);
+ System.out.println(banchanDetailDto);
+ return banchanDetailDto;
+ }
+
+ @PostMapping("/create")
+ public String create(@RequestBody Banchan banchan) {
+ banchanService.createBanchan(banchan);
+ return "success";
+ }
+} | Java | `@PathVariable` ์์ path variable name์ ์ค์ ํ ์ ์๋ ํ๋๊ฐ ์์ ๊ฑฐ๋ผ ์๊ฐํฉ๋๋ค.
์ด๋ ํ ์๊ฐ์๋ ์๋ฐ์ ๊ธฐ๋ณธ์ ์ฝ๋ฉ ์ปจ๋ฒค์
์ ๊ณ์ ์ค์ํด์ฃผ์ธ์. |
@@ -0,0 +1,24 @@
+package develop.baminchan.controller;
+
+public class Message {
+ public static final int OK = 200;
+ public static final int BAD_REQUEST = 400;
+ public static final int NOT_FOUND = 404;
+ public static final int INTERNAL_SERVER_ERROR = 500;
+
+ private int statusCode;
+ private Object body;
+
+ public Message(int statusCode, Object body) {
+ this.statusCode = statusCode;
+ this.body = body;
+ }
+
+ public int getStatusCode() {
+ return statusCode;
+ }
+
+ public Object getBody() {
+ return body;
+ }
+} | Java | `enum` ์ผ๋ก ๊ด๋ฆฌํด๋ณด์๋ฉด ์ด๋จ๊น์? |
@@ -0,0 +1,78 @@
+package develop.baminchan.dto;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import develop.baminchan.entity.Banchan;
+
+import java.util.Set;
+
+import static develop.baminchan.dto.util.StringConvertor.convertToSet;
+
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class BanchanDto {
+ private String detail_hash;
+ private String image;
+ private String alt;
+ private Set<String> delivery_type;
+ private String title;
+ private String description;
+ private String n_price;
+ private String s_price;
+ private Set<String> badge;
+
+ protected BanchanDto() {
+
+ }
+
+ private BanchanDto(Banchan banchan) {
+ this.detail_hash = banchan.getDetail_hash();
+ this.image = banchan.getImage();
+ this.alt = banchan.getAlt();
+ this.delivery_type = convertToSet(banchan.getDelivery_type());
+ this.title = banchan.getTitle();
+ this.description = banchan.getDescription();
+ this.n_price = banchan.getN_price();
+ this.s_price = banchan.getS_price();
+ this.badge = convertToSet(banchan.getBadge());
+ }
+
+ // Entity -> DTO
+ public static BanchanDto of(Banchan banchan) {
+ return new BanchanDto(banchan);
+ }
+
+ public String getDetail_hash() {
+ return detail_hash;
+ }
+
+ public String getImage() {
+ return image;
+ }
+
+ public String getAlt() {
+ return alt;
+ }
+
+ public Set<String> getDelivery_type() {
+ return delivery_type;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public String getN_price() {
+ return n_price;
+ }
+
+ public String getS_price() {
+ return s_price;
+ }
+
+ public Set<String> getBadge() {
+ return badge;
+ }
+} | Java | `@JsonProperty` ๋ฅผ ํตํด JSON field์ ์ด๋ฆ ์ ํด์ฃผ์๋ฉด ๋ ๊ฒ ๊ฐ์์.
์ธ๋์ค์ฝ์ด๋ ์๋ฐ ์ฝ๋์ ์์์ผ๋ฉด ํฉ๋๋ค. |
@@ -0,0 +1,78 @@
+package develop.baminchan.dto;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import develop.baminchan.entity.Banchan;
+
+import java.util.Set;
+
+import static develop.baminchan.dto.util.StringConvertor.convertToSet;
+
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class BanchanDto {
+ private String detail_hash;
+ private String image;
+ private String alt;
+ private Set<String> delivery_type;
+ private String title;
+ private String description;
+ private String n_price;
+ private String s_price;
+ private Set<String> badge;
+
+ protected BanchanDto() {
+
+ }
+
+ private BanchanDto(Banchan banchan) {
+ this.detail_hash = banchan.getDetail_hash();
+ this.image = banchan.getImage();
+ this.alt = banchan.getAlt();
+ this.delivery_type = convertToSet(banchan.getDelivery_type());
+ this.title = banchan.getTitle();
+ this.description = banchan.getDescription();
+ this.n_price = banchan.getN_price();
+ this.s_price = banchan.getS_price();
+ this.badge = convertToSet(banchan.getBadge());
+ }
+
+ // Entity -> DTO
+ public static BanchanDto of(Banchan banchan) {
+ return new BanchanDto(banchan);
+ }
+
+ public String getDetail_hash() {
+ return detail_hash;
+ }
+
+ public String getImage() {
+ return image;
+ }
+
+ public String getAlt() {
+ return alt;
+ }
+
+ public Set<String> getDelivery_type() {
+ return delivery_type;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public String getN_price() {
+ return n_price;
+ }
+
+ public String getS_price() {
+ return s_price;
+ }
+
+ public Set<String> getBadge() {
+ return badge;
+ }
+} | Java | `private` ์ผ๋ก ๊ฐ๋ ค๋จ์ผ๋ฏ๋ก ๋ชจ๋ ํ๋์ ํด๋นํ๋ ํ๋ผ๋ฉํฐ๋ฅผ ๋ค ์ ์ธํด์ฃผ์
๋ ๋ฉ๋๋ค.
๋ ๊ทธ๋ ๊ฒ ํด์ผ ์ถํ ํ์ฅ์ฑ ์ธก๋ฉด์์๋ ์ข์ ๊ฑฐ๋ผ ์๊ฐํฉ๋๋ค.
`Banchan` ์ ๋ฐ์์ ํ๋์ฉ ์ ๋ณด๋ฅผ ๊บผ๋ด๋ ์ฑ
์์ `.of()` ์๊ฒ ๋งก๊ธฐ๊ณ ์์ฑ์์์ ๋จ์ ๊ฐ ํ ๋น์ ์ง์คํ๋ฉด ์ด๋จ๊น์. |
@@ -0,0 +1,45 @@
+package develop.baminchan.dto;
+
+import develop.baminchan.entity.Category;
+import org.springframework.data.annotation.Id;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class CategoryDto {
+ @Id
+ private int id;
+
+ private String category_id;
+ private String name;
+
+ private List<BanchanDto> items = new ArrayList<>();
+
+ public CategoryDto(String category_id, String name) {
+ this.category_id = category_id;
+ this.name = name;
+ }
+
+ public CategoryDto(Category category, List<BanchanDto> banchanDtoList) {
+ this.category_id = category.getCategory_id();
+ this.name = category.getName();
+ this.items = banchanDtoList;
+ }
+
+ // Entity -> DTO
+ public static CategoryDto of(Category category, List<BanchanDto> banchanDtoList) {
+ return new CategoryDto(category, banchanDtoList);
+ }
+
+ public String getCategory_id() {
+ return category_id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public List<BanchanDto> getItems() {
+ return items;
+ }
+} | Java | DTO์ธ๋ฐ `@Id`.... ๊ด์ฐฎ์๊น์? |
@@ -0,0 +1,20 @@
+package develop.baminchan.dto.util;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+
+public class StringConvertor {
+ private StringConvertor() {
+ }
+
+ public static Set<String> convertToSet(String column) {
+ if (column == null) {
+ return null;
+ }
+ Set<String> set = new HashSet<>();
+ String[] arr = column.split(", ");
+ set.addAll(Arrays.asList(arr));
+ return set;
+ }
+} | Java | [์ด ๋งํฌ](https://docs.spring.io/spring-data/jdbc/docs/current/reference/html/#jdbc.custom-converters) ๋ฅผ ์ฐธ๊ณ ํด์ฃผ์๊ณ ํ์ค ์คํ์ ๋ง๋ ํด๋์ค๋ก ์ ํ์ ๋ถํ๋๋ฆด๊ฒ์. |
@@ -0,0 +1,35 @@
+package develop.baminchan.entity;
+
+import org.springframework.data.annotation.Id;
+
+public class Order {
+ @Id
+ private Long id;
+
+ private String client_id;
+ private String detail_hash;
+ private int quantity;
+
+ public Order(Long id, String client_id, String detail_hash, int quantity) {
+ this.id = id;
+ this.client_id = client_id;
+ this.detail_hash = detail_hash;
+ this.quantity = quantity;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public String getClient_id() {
+ return client_id;
+ }
+
+ public String getDetail_hash() {
+ return detail_hash;
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+} | Java | ๊ตณ์ด ์ฝ์ด๋ฅผ ์ฌ์ฉํ์ค ํ์๋ ์์ด ๋ณด์ด๊ธฐ๋ ํฉ๋๋ค.
ํ
์ด๋ธ ์์๋ ์ด ์ด๋ฆ์ผ๋ก ์นผ๋ผ์ด ๋ค์ด๊ฐ์๋์? ๊ทธ๋ ๋ค๋ฉด ํ ๋ค์์ธ `quantity` ๋ก์ ์ ํ์ ์ ์๋๋ฆฝ๋๋ค. |
@@ -0,0 +1,57 @@
+package develop.baminchan.service;
+
+import develop.baminchan.dto.BanchanDto;
+import develop.baminchan.dto.CategoryDto;
+import develop.baminchan.entity.Banchan;
+import develop.baminchan.entity.Category;
+import develop.baminchan.repository.BanchanRepository;
+import develop.baminchan.repository.CategoryRepository;
+import org.springframework.stereotype.Service;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+@Service
+public class CategoryService {
+ private CategoryRepository categoryRepository;
+ private BanchanRepository banchanRepository;
+
+ public CategoryService(CategoryRepository categoryRepository, BanchanRepository banchanRepository) {
+ this.categoryRepository = categoryRepository;
+ this.banchanRepository = banchanRepository;
+ }
+
+ public List<CategoryDto> findAllBestBanchansByCategories() {
+ Iterable<Category> categoryList = categoryRepository.findAll();
+ Set<String> setOfCategoryIds = new HashSet<>();
+ for (Category category : categoryList) {
+ setOfCategoryIds.add(category.getCategory_id());
+ }
+ System.out.println(setOfCategoryIds); //ํ
์คํธ // null๋ ๋ค์ด๊ฐ๋?
+
+ List<CategoryDto> categoryDtoList = new ArrayList<>();
+ for (String category_id : setOfCategoryIds) {
+ categoryDtoList.add(findBestBanchansByCategory(category_id));
+ }
+ return categoryDtoList;
+ }
+
+ public CategoryDto findBestBanchansByCategory(String category_id) {
+ Category category = categoryRepository.findCategoryByCategory_id(category_id);
+ CategoryDto categoryDto = CategoryDto.of(category, findBanchanListByCategoryId(category_id));
+ return categoryDto;
+ }
+
+ private List<BanchanDto> findBanchanListByCategoryId(String catrgory_id) {
+ List<BanchanDto> banchanDtoList = new ArrayList<>();
+ List<Banchan> banchanList = new ArrayList<>();
+
+ banchanList = banchanRepository.findBanchansByCategory_id(catrgory_id);
+ for (int i = 0; i < banchanList.size(); i++) {
+ banchanDtoList.add(BanchanDto.of(banchanList.get(i)));
+ }
+ return banchanDtoList;
+ }
+} | Java | `logger` ์ฌ์ฉํด์ฃผ์ธ์. |
@@ -0,0 +1,57 @@
+package develop.baminchan.service;
+
+import develop.baminchan.dto.BanchanDto;
+import develop.baminchan.dto.CategoryDto;
+import develop.baminchan.entity.Banchan;
+import develop.baminchan.entity.Category;
+import develop.baminchan.repository.BanchanRepository;
+import develop.baminchan.repository.CategoryRepository;
+import org.springframework.stereotype.Service;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+@Service
+public class CategoryService {
+ private CategoryRepository categoryRepository;
+ private BanchanRepository banchanRepository;
+
+ public CategoryService(CategoryRepository categoryRepository, BanchanRepository banchanRepository) {
+ this.categoryRepository = categoryRepository;
+ this.banchanRepository = banchanRepository;
+ }
+
+ public List<CategoryDto> findAllBestBanchansByCategories() {
+ Iterable<Category> categoryList = categoryRepository.findAll();
+ Set<String> setOfCategoryIds = new HashSet<>();
+ for (Category category : categoryList) {
+ setOfCategoryIds.add(category.getCategory_id());
+ }
+ System.out.println(setOfCategoryIds); //ํ
์คํธ // null๋ ๋ค์ด๊ฐ๋?
+
+ List<CategoryDto> categoryDtoList = new ArrayList<>();
+ for (String category_id : setOfCategoryIds) {
+ categoryDtoList.add(findBestBanchansByCategory(category_id));
+ }
+ return categoryDtoList;
+ }
+
+ public CategoryDto findBestBanchansByCategory(String category_id) {
+ Category category = categoryRepository.findCategoryByCategory_id(category_id);
+ CategoryDto categoryDto = CategoryDto.of(category, findBanchanListByCategoryId(category_id));
+ return categoryDto;
+ }
+
+ private List<BanchanDto> findBanchanListByCategoryId(String catrgory_id) {
+ List<BanchanDto> banchanDtoList = new ArrayList<>();
+ List<Banchan> banchanList = new ArrayList<>();
+
+ banchanList = banchanRepository.findBanchansByCategory_id(catrgory_id);
+ for (int i = 0; i < banchanList.size(); i++) {
+ banchanDtoList.add(BanchanDto.of(banchanList.get(i)));
+ }
+ return banchanDtoList;
+ }
+} | Java | `.stream().map()` ์ฌ์ฉ์ผ๋ก ์์ for loop์ด๋ ์ฌ๊ธฐ๊น์ง ์์จ ์ ์์ด ๋ณด์
๋๋ค. |
@@ -0,0 +1,57 @@
+package develop.baminchan.service;
+
+import develop.baminchan.dto.BanchanDto;
+import develop.baminchan.dto.CategoryDto;
+import develop.baminchan.entity.Banchan;
+import develop.baminchan.entity.Category;
+import develop.baminchan.repository.BanchanRepository;
+import develop.baminchan.repository.CategoryRepository;
+import org.springframework.stereotype.Service;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+@Service
+public class CategoryService {
+ private CategoryRepository categoryRepository;
+ private BanchanRepository banchanRepository;
+
+ public CategoryService(CategoryRepository categoryRepository, BanchanRepository banchanRepository) {
+ this.categoryRepository = categoryRepository;
+ this.banchanRepository = banchanRepository;
+ }
+
+ public List<CategoryDto> findAllBestBanchansByCategories() {
+ Iterable<Category> categoryList = categoryRepository.findAll();
+ Set<String> setOfCategoryIds = new HashSet<>();
+ for (Category category : categoryList) {
+ setOfCategoryIds.add(category.getCategory_id());
+ }
+ System.out.println(setOfCategoryIds); //ํ
์คํธ // null๋ ๋ค์ด๊ฐ๋?
+
+ List<CategoryDto> categoryDtoList = new ArrayList<>();
+ for (String category_id : setOfCategoryIds) {
+ categoryDtoList.add(findBestBanchansByCategory(category_id));
+ }
+ return categoryDtoList;
+ }
+
+ public CategoryDto findBestBanchansByCategory(String category_id) {
+ Category category = categoryRepository.findCategoryByCategory_id(category_id);
+ CategoryDto categoryDto = CategoryDto.of(category, findBanchanListByCategoryId(category_id));
+ return categoryDto;
+ }
+
+ private List<BanchanDto> findBanchanListByCategoryId(String catrgory_id) {
+ List<BanchanDto> banchanDtoList = new ArrayList<>();
+ List<Banchan> banchanList = new ArrayList<>();
+
+ banchanList = banchanRepository.findBanchansByCategory_id(catrgory_id);
+ for (int i = 0; i < banchanList.size(); i++) {
+ banchanDtoList.add(BanchanDto.of(banchanList.get(i)));
+ }
+ return banchanDtoList;
+ }
+} | Java | ์ฌ๊ธฐ๋ `.stream().map()` ์ผ๋ก ๋ฐ๊ฟ ์ ์์ต๋๋ค. |
@@ -0,0 +1,20 @@
+package develop.baminchan.dto.util;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+
+public class StringConvertor {
+ private StringConvertor() {
+ }
+
+ public static Set<String> convertToSet(String column) {
+ if (column == null) {
+ return null;
+ }
+ Set<String> set = new HashSet<>();
+ String[] arr = column.split(", ");
+ set.addAll(Arrays.asList(arr));
+ return set;
+ }
+} | Java | ๋ฐ์ดํฐ ๋ณํ์ ์ํ ์ปจ๋ฒํฐ์ ๋ํ ํ์ค ์คํ์ด ์์๊ตฐ์..์คํ๋ง ๋ฌธ์ ์ ์ฒด์ ์ผ๋ก ๊ผญ ํ๋ฒ ์ฝ์ด๋ด์ผ๊ฒ ๋ค์.
๊ฐ์ฌํฉ๋๋ค. |
@@ -0,0 +1,94 @@
+package develop.baminchan.entity;
+
+import develop.baminchan.entity.banchan.BanchanDetail;
+import org.springframework.data.annotation.Id;
+import org.springframework.data.relational.core.mapping.Embedded;
+
+public class Banchan {
+ @Id
+ private Long id;
+
+ private String detail_hash;
+ private String image;
+ private String alt;
+ private String delivery_type;
+ private String title;
+ private String description;
+ private String n_price;
+ private String s_price;
+ private String badge;
+
+ private String tag;
+ private String category_id;
+
+ @Embedded.Nullable
+ private BanchanDetail banchanDetail;
+
+ public Banchan(Long id, String detail_hash, String image, String alt, String delivery_type, String title, String description, String n_price, String s_price, String badge, String tag, String category_id, BanchanDetail banchanDetail) {
+ this.id = id;
+ this.detail_hash = detail_hash;
+ this.image = image;
+ this.alt = alt;
+ this.delivery_type = delivery_type;
+ this.title = title;
+ this.description = description;
+ this.n_price = n_price;
+ this.s_price = s_price;
+ this.badge = badge;
+ this.tag = tag;
+ this.category_id = category_id;
+ this.banchanDetail = banchanDetail;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public String getDetail_hash() {
+ return detail_hash;
+ }
+
+ public String getImage() {
+ return image;
+ }
+
+ public String getAlt() {
+ return alt;
+ }
+
+ public String getDelivery_type() {
+ return delivery_type;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public String getN_price() {
+ return n_price;
+ }
+
+ public String getS_price() {
+ return s_price;
+ }
+
+ public String getBadge() {
+ return badge;
+ }
+
+ public String getTag() {
+ return tag;
+ }
+
+ public String getCategory_id() {
+ return category_id;
+ }
+
+ public BanchanDetail getBanchanDetail() {
+ return banchanDetail;
+ }
+} | Java | ๋ค๋ฅธ ๋ฆฌ๋ทฐ์์ ์ด๋ฐ ๋ฅ์ ์์ฑ์๋ฅผ ๊ต์ฅํ ์ซ์ดํ์ ๋ค๊ณ ํ์๋๋ฐ ์ฌ๊ธฐ๋ ๋๊ฐ์ ๋ถ๋ถ ๋ง๋์? |
@@ -0,0 +1,80 @@
+import React from 'react';
+import Comment from './Comment';
+import './CommentList.scss';
+
+class CommentList extends React.Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ commentInput: '',
+ newComment: [],
+ nickname: '',
+ commentList: [],
+ commentValue: '',
+ };
+ }
+
+ componentDidMount() {
+ fetch('http://localhost:3000/data/commentData.json', {
+ method: 'GET', // GET method๋ ๊ธฐ๋ณธ๊ฐ์ด๋ผ์ ์๋ต์ด ๊ฐ๋ฅํฉ๋๋ค.
+ }) // ์์์ฝ๋์์๋ ์ดํด๋ฅผ ๋๊ธฐ ์ํด ๋ช
์์ ์ผ๋ก ๊ธฐ์
ํด๋์ต๋๋ค.
+ .then(res => res.json())
+ .then(data => {
+ this.setState({
+ commentList: data,
+ });
+ });
+ }
+
+ checkInput = e => {
+ this.setState({
+ commentInput: e.target.value,
+ });
+ };
+
+ inputToComment = () => {
+ const { newComment, commentInput } = this.state;
+ this.setState({
+ nickname: 'wecode_bootcamp',
+ newComment: newComment.concat(commentInput),
+ });
+ };
+
+ enterPress = e => {
+ if (e.key === 'Enter') {
+ this.inputToComment();
+ }
+ e.target.value = '';
+ };
+
+ render() {
+ const { commentValue, commentList } = this.state;
+ return (
+ <div className="commentList">
+ {commentList.map(comment => {
+ return (
+ <Comment
+ key={comment.id}
+ nickname={comment.userName}
+ comment={comment.content}
+ />
+ );
+ })}
+
+ <div className="newText">
+ <input
+ id="typingText"
+ value={commentValue}
+ onChange={this.checkInput}
+ onKeyPress={this.enterPress}
+ type="text"
+ placeholder="๋๊ธ ๋ฌ๊ธฐ...."
+ />
+ <button onClick={this.checkInput}>๊ฒ์</button>
+ </div>
+ </div>
+ );
+ }
+}
+
+export default CommentList; | JavaScript | ๋น๊ตฌ์กฐํ ํ ๋น์ ์ ์ฉํ๋ฉด ๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,23 @@
+import React from 'react';
+import './Comment.scss';
+
+class NewComment extends React.Component {
+ render() {
+ // const newArray = this.props.newComment.map((commentarray, index) => (
+ // <li key={index}>
+ // <span className="newCommentid">{this.props.nickname}</span>
+ // <span className="newComments">{commentarray}</span>
+ // </li>
+ // ));
+ return (
+ <div className="comment">
+ <div className="newComment">
+ <span className="newCommentid">{this.props.nickname}</span>
+ <span className="newComments">{this.props.comment}</span>
+ </div>
+ </div>
+ );
+ }
+}
+
+export default NewComment; | JavaScript | - state ๋ฅผ ์ฌ์ฉํ์ง ์๋๋ค๋ฉด, constructor ์ ์ ์ธ์ด ํ์ ์์ต๋๋ค! |
@@ -0,0 +1,15 @@
+.comment {
+ .newComment {
+ margin-bottom: 5px;
+ }
+
+ .newCommentid {
+ font-weight: bold;
+ margin-bottom: 0;
+ }
+
+ .newComments {
+ font-weight: normal;
+ margin-left: 5px;
+ }
+} | Unknown | - `.comment` ์๋๋ก ๋ค์คํ
ํด์ฃผ์ธ์! |
@@ -0,0 +1,80 @@
+import React from 'react';
+import Comment from './Comment';
+import './CommentList.scss';
+
+class CommentList extends React.Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ commentInput: '',
+ newComment: [],
+ nickname: '',
+ commentList: [],
+ commentValue: '',
+ };
+ }
+
+ componentDidMount() {
+ fetch('http://localhost:3000/data/commentData.json', {
+ method: 'GET', // GET method๋ ๊ธฐ๋ณธ๊ฐ์ด๋ผ์ ์๋ต์ด ๊ฐ๋ฅํฉ๋๋ค.
+ }) // ์์์ฝ๋์์๋ ์ดํด๋ฅผ ๋๊ธฐ ์ํด ๋ช
์์ ์ผ๋ก ๊ธฐ์
ํด๋์ต๋๋ค.
+ .then(res => res.json())
+ .then(data => {
+ this.setState({
+ commentList: data,
+ });
+ });
+ }
+
+ checkInput = e => {
+ this.setState({
+ commentInput: e.target.value,
+ });
+ };
+
+ inputToComment = () => {
+ const { newComment, commentInput } = this.state;
+ this.setState({
+ nickname: 'wecode_bootcamp',
+ newComment: newComment.concat(commentInput),
+ });
+ };
+
+ enterPress = e => {
+ if (e.key === 'Enter') {
+ this.inputToComment();
+ }
+ e.target.value = '';
+ };
+
+ render() {
+ const { commentValue, commentList } = this.state;
+ return (
+ <div className="commentList">
+ {commentList.map(comment => {
+ return (
+ <Comment
+ key={comment.id}
+ nickname={comment.userName}
+ comment={comment.content}
+ />
+ );
+ })}
+
+ <div className="newText">
+ <input
+ id="typingText"
+ value={commentValue}
+ onChange={this.checkInput}
+ onKeyPress={this.enterPress}
+ type="text"
+ placeholder="๋๊ธ ๋ฌ๊ธฐ...."
+ />
+ <button onClick={this.checkInput}>๊ฒ์</button>
+ </div>
+ </div>
+ );
+ }
+}
+
+export default CommentList; | JavaScript | - ๊ตฌ์กฐ ๋ถํด ํ ๋น ํด์ฃผ์ธ์!
```suggestion
inputToComment = () => {
const { comment, commentInput } = this.state;
this.setState({
id: 'wecode_bootcamp',
comment: comment.concat(commentInput),
});
};
``` |
@@ -0,0 +1,23 @@
+import React from 'react';
+import './Comment.scss';
+
+class NewComment extends React.Component {
+ render() {
+ // const newArray = this.props.newComment.map((commentarray, index) => (
+ // <li key={index}>
+ // <span className="newCommentid">{this.props.nickname}</span>
+ // <span className="newComments">{commentarray}</span>
+ // </li>
+ // ));
+ return (
+ <div className="comment">
+ <div className="newComment">
+ <span className="newCommentid">{this.props.nickname}</span>
+ <span className="newComments">{this.props.comment}</span>
+ </div>
+ </div>
+ );
+ }
+}
+
+export default NewComment; | JavaScript | - ์ปดํฌ๋ํธ์ ๋์ผํ๊ฒ ํด๋์ค๋ค์ ์ง์ด์ฃผ์๊ณ , ์ฒซ๊ธ์๋ฅผ ๋๋ฌธ์๋ก ์์ฑํ๋ ์ปจ๋ฒค์
์ ์ปดํฌ๋ํธ๋ฅผ ๋ค์ด๋ฐ ํ๊ธฐ ์ํ ์ปจ๋ฒค์
์
๋๋ค!
```suggestion
<div className="comment">
``` |
@@ -0,0 +1,80 @@
+import React from 'react';
+import Comment from './Comment';
+import './CommentList.scss';
+
+class CommentList extends React.Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ commentInput: '',
+ newComment: [],
+ nickname: '',
+ commentList: [],
+ commentValue: '',
+ };
+ }
+
+ componentDidMount() {
+ fetch('http://localhost:3000/data/commentData.json', {
+ method: 'GET', // GET method๋ ๊ธฐ๋ณธ๊ฐ์ด๋ผ์ ์๋ต์ด ๊ฐ๋ฅํฉ๋๋ค.
+ }) // ์์์ฝ๋์์๋ ์ดํด๋ฅผ ๋๊ธฐ ์ํด ๋ช
์์ ์ผ๋ก ๊ธฐ์
ํด๋์ต๋๋ค.
+ .then(res => res.json())
+ .then(data => {
+ this.setState({
+ commentList: data,
+ });
+ });
+ }
+
+ checkInput = e => {
+ this.setState({
+ commentInput: e.target.value,
+ });
+ };
+
+ inputToComment = () => {
+ const { newComment, commentInput } = this.state;
+ this.setState({
+ nickname: 'wecode_bootcamp',
+ newComment: newComment.concat(commentInput),
+ });
+ };
+
+ enterPress = e => {
+ if (e.key === 'Enter') {
+ this.inputToComment();
+ }
+ e.target.value = '';
+ };
+
+ render() {
+ const { commentValue, commentList } = this.state;
+ return (
+ <div className="commentList">
+ {commentList.map(comment => {
+ return (
+ <Comment
+ key={comment.id}
+ nickname={comment.userName}
+ comment={comment.content}
+ />
+ );
+ })}
+
+ <div className="newText">
+ <input
+ id="typingText"
+ value={commentValue}
+ onChange={this.checkInput}
+ onKeyPress={this.enterPress}
+ type="text"
+ placeholder="๋๊ธ ๋ฌ๊ธฐ...."
+ />
+ <button onClick={this.checkInput}>๊ฒ์</button>
+ </div>
+ </div>
+ );
+ }
+}
+
+export default CommentList; | JavaScript | - id ๋ผ๋ ๊ฐ์ ๋ฌด์จ ์ฉ๋๋ฅผ ์ํด ์์ฑํด ์ฃผ์ ๊ฑธ๊น์? id ๋ ๊ผญ ํ์ํ ๋ถ๋ถ์ด ์๋๋ผ๋ฉด ์ฌ์ฉ์ ์ง์ํด์ฃผ์ธ์! id ๊ฐ์ ํ๋ก์ ํธ ๋ด์์ ์ ์ผํด์ผ ํฉ๋๋ค.
- id ๋ฅผ ์ฌ์ฉํ๋ ๊ฒฝ์ฐ๋ ์๋ฅผ ๋ค์ด, google map api ๋ฅผ ์ฌ์ฉํด์ ์ง๋๋ฅผ ๊ทธ๋ฆด๋, ์ง๋๋ฅผ ๊ทธ๋ฆด html element ๋ฅผ ํน์ ํ ๋ ์ฌ์ฉ๋๊ณค ํฉ๋๋ค. |
@@ -0,0 +1,80 @@
+import React from 'react';
+import Comment from './Comment';
+import './CommentList.scss';
+
+class CommentList extends React.Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ commentInput: '',
+ newComment: [],
+ nickname: '',
+ commentList: [],
+ commentValue: '',
+ };
+ }
+
+ componentDidMount() {
+ fetch('http://localhost:3000/data/commentData.json', {
+ method: 'GET', // GET method๋ ๊ธฐ๋ณธ๊ฐ์ด๋ผ์ ์๋ต์ด ๊ฐ๋ฅํฉ๋๋ค.
+ }) // ์์์ฝ๋์์๋ ์ดํด๋ฅผ ๋๊ธฐ ์ํด ๋ช
์์ ์ผ๋ก ๊ธฐ์
ํด๋์ต๋๋ค.
+ .then(res => res.json())
+ .then(data => {
+ this.setState({
+ commentList: data,
+ });
+ });
+ }
+
+ checkInput = e => {
+ this.setState({
+ commentInput: e.target.value,
+ });
+ };
+
+ inputToComment = () => {
+ const { newComment, commentInput } = this.state;
+ this.setState({
+ nickname: 'wecode_bootcamp',
+ newComment: newComment.concat(commentInput),
+ });
+ };
+
+ enterPress = e => {
+ if (e.key === 'Enter') {
+ this.inputToComment();
+ }
+ e.target.value = '';
+ };
+
+ render() {
+ const { commentValue, commentList } = this.state;
+ return (
+ <div className="commentList">
+ {commentList.map(comment => {
+ return (
+ <Comment
+ key={comment.id}
+ nickname={comment.userName}
+ comment={comment.content}
+ />
+ );
+ })}
+
+ <div className="newText">
+ <input
+ id="typingText"
+ value={commentValue}
+ onChange={this.checkInput}
+ onKeyPress={this.enterPress}
+ type="text"
+ placeholder="๋๊ธ ๋ฌ๊ธฐ...."
+ />
+ <button onClick={this.checkInput}>๊ฒ์</button>
+ </div>
+ </div>
+ );
+ }
+}
+
+export default CommentList; | JavaScript | - ์ฌ๊ธฐ๋ id ๋ฅผ ์ฌ์ฉํ์ง ์๋๋ฐ ๋ถํ์ํ๊ฒ ์ฌ์ฉํ๋ ๊ฒ ๊ฐ์ต๋๋ค! ์ง์์ฃผ์ธ์~ |
@@ -1,13 +1,92 @@
import React from 'react';
+import { withRouter } from 'react-router-dom';
+import './Login.scss';
class LoginAh extends React.Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ idInput: '',
+ pwInput: '',
+ };
+ }
+
+ loginTest = () => {
+ fetch('users/login', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ email: this.state.idInput,
+ password: this.state.pwInput,
+ }),
+ })
+ .then(response => response.json())
+ .then(response => {
+ if (response.token) {
+ localStorage.setItem('token', response.token);
+ this.props.history.push('/MainAh');
+ } else {
+ alert('์์ด๋/๋น๋ฐ๋ฒํธ๊ฐ ํ๋ ธ์ต๋๋ค!');
+ }
+ });
+ };
+ handleInput = event => {
+ const { name, value } = event.target;
+ this.setState({
+ [name]: value,
+ });
+ };
+
+ goToMain = () => {
+ this.props.history.push('/MainAh');
+ };
+
render() {
+ const { idInput, pwInput } = this.state;
+ const isButtonActive = idInput.includes('@') && pwInput.length >= 5;
return (
- <div>
- <p>๋ค์ฌ</p>
+ <div className="Login">
+ <div className="container">
+ <div className="loginContainer">
+ <p>westagram</p>
+ <div className="idContainer">
+ <input
+ onChange={this.handleInput}
+ name="idInput"
+ type="text"
+ className="inputId"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ />
+ </div>
+ <div className="passwordContainer">
+ <input
+ onChange={this.handleInput}
+ name="pwInput"
+ type="password"
+ className="inputPassword"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ />
+ </div>
+ <button
+ disabled={!isButtonActive}
+ className={`loginButton ${
+ isButtonActive ? 'loginButtonOn' : 'loginButtonOff'
+ }`}
+ // onClick={this.goToMain}
+ onClick={this.loginTest}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div>
+ <a href="google.com">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </div>
+ </div>
</div>
);
}
}
-export default LoginAh;
+export default withRouter(LoginAh); | JavaScript | - constructor ์ ์ธ์ ๊ฐ์ฅ ์์ ์์น์์ผ์ฃผ์ธ์! |
@@ -1,13 +1,92 @@
import React from 'react';
+import { withRouter } from 'react-router-dom';
+import './Login.scss';
class LoginAh extends React.Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ idInput: '',
+ pwInput: '',
+ };
+ }
+
+ loginTest = () => {
+ fetch('users/login', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ email: this.state.idInput,
+ password: this.state.pwInput,
+ }),
+ })
+ .then(response => response.json())
+ .then(response => {
+ if (response.token) {
+ localStorage.setItem('token', response.token);
+ this.props.history.push('/MainAh');
+ } else {
+ alert('์์ด๋/๋น๋ฐ๋ฒํธ๊ฐ ํ๋ ธ์ต๋๋ค!');
+ }
+ });
+ };
+ handleInput = event => {
+ const { name, value } = event.target;
+ this.setState({
+ [name]: value,
+ });
+ };
+
+ goToMain = () => {
+ this.props.history.push('/MainAh');
+ };
+
render() {
+ const { idInput, pwInput } = this.state;
+ const isButtonActive = idInput.includes('@') && pwInput.length >= 5;
return (
- <div>
- <p>๋ค์ฌ</p>
+ <div className="Login">
+ <div className="container">
+ <div className="loginContainer">
+ <p>westagram</p>
+ <div className="idContainer">
+ <input
+ onChange={this.handleInput}
+ name="idInput"
+ type="text"
+ className="inputId"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ />
+ </div>
+ <div className="passwordContainer">
+ <input
+ onChange={this.handleInput}
+ name="pwInput"
+ type="password"
+ className="inputPassword"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ />
+ </div>
+ <button
+ disabled={!isButtonActive}
+ className={`loginButton ${
+ isButtonActive ? 'loginButtonOn' : 'loginButtonOff'
+ }`}
+ // onClick={this.goToMain}
+ onClick={this.loginTest}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div>
+ <a href="google.com">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </div>
+ </div>
</div>
);
}
}
-export default LoginAh;
+export default withRouter(LoginAh); | JavaScript | - defaultColor ์ disabled ๋ state ๋ก ๊ด๋ฆฌํ๊ธฐ์๋ ๋ถ์ ์ ํ ๊ฐ ๊ฐ์ต๋๋ค. idInput ๊ณผ pwInput ๋ฅผ ์ฌ์ฉํด์ ๊ณ์ฐํ ์ ์๋ ๊ฐ์ด๊ธฐ ๋๋ฌธ์
๋๋ค!
- ์ด๋ค ๊ธฐ์ค์ผ๋ก state ๋ฅผ ๋ง๋ค์ด์ผ ํ๋์ง์ ๋ํด์๋ ์๋ ๋ฌธ์๋ฅผ ์ฐธ๊ณ ํด์ฃผ์ธ์!
- https://ko.reactjs.org/docs/thinking-in-react.html#step-3-identify-the-minimal-but-complete-representation-of-ui-state
- state ๋ก ๊ด๋ฆฌํ ํ์๊ฐ ์๋ ๊ฐ๋ค์ state ๋ฅผ ๋ง๋ค์ง ์๋๋ก ํด์ฃผ์ธ์. ๊ฐ์ ์์ ํ๊ธฐ ์ํด์ , setState ๋ฅผ ์ฌ์ฉํด์ผํ๊ณ , ์ด๋ ์ผ์ด๋์ง ์์๋ ๋๋ ๋ถํ์ํ ๋ ๋๋ง์ ๋ฐ์์ํค๊ธฐ ๋๋ฌธ์
๋๋ค. |
@@ -1,13 +1,92 @@
import React from 'react';
+import { withRouter } from 'react-router-dom';
+import './Login.scss';
class LoginAh extends React.Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ idInput: '',
+ pwInput: '',
+ };
+ }
+
+ loginTest = () => {
+ fetch('users/login', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ email: this.state.idInput,
+ password: this.state.pwInput,
+ }),
+ })
+ .then(response => response.json())
+ .then(response => {
+ if (response.token) {
+ localStorage.setItem('token', response.token);
+ this.props.history.push('/MainAh');
+ } else {
+ alert('์์ด๋/๋น๋ฐ๋ฒํธ๊ฐ ํ๋ ธ์ต๋๋ค!');
+ }
+ });
+ };
+ handleInput = event => {
+ const { name, value } = event.target;
+ this.setState({
+ [name]: value,
+ });
+ };
+
+ goToMain = () => {
+ this.props.history.push('/MainAh');
+ };
+
render() {
+ const { idInput, pwInput } = this.state;
+ const isButtonActive = idInput.includes('@') && pwInput.length >= 5;
return (
- <div>
- <p>๋ค์ฌ</p>
+ <div className="Login">
+ <div className="container">
+ <div className="loginContainer">
+ <p>westagram</p>
+ <div className="idContainer">
+ <input
+ onChange={this.handleInput}
+ name="idInput"
+ type="text"
+ className="inputId"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ />
+ </div>
+ <div className="passwordContainer">
+ <input
+ onChange={this.handleInput}
+ name="pwInput"
+ type="password"
+ className="inputPassword"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ />
+ </div>
+ <button
+ disabled={!isButtonActive}
+ className={`loginButton ${
+ isButtonActive ? 'loginButtonOn' : 'loginButtonOff'
+ }`}
+ // onClick={this.goToMain}
+ onClick={this.loginTest}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div>
+ <a href="google.com">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </div>
+ </div>
</div>
);
}
}
-export default LoginAh;
+export default withRouter(LoginAh); | JavaScript | - ๊ตฌ์กฐ ๋ถํด ํ ๋น ํ์ฉํด ์ฃผ์๋ฉด ๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค!
```suggestion
const { name, value } = event.target;
this.setState({
[name]: value,
});
``` |
@@ -1,13 +1,92 @@
import React from 'react';
+import { withRouter } from 'react-router-dom';
+import './Login.scss';
class LoginAh extends React.Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ idInput: '',
+ pwInput: '',
+ };
+ }
+
+ loginTest = () => {
+ fetch('users/login', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ email: this.state.idInput,
+ password: this.state.pwInput,
+ }),
+ })
+ .then(response => response.json())
+ .then(response => {
+ if (response.token) {
+ localStorage.setItem('token', response.token);
+ this.props.history.push('/MainAh');
+ } else {
+ alert('์์ด๋/๋น๋ฐ๋ฒํธ๊ฐ ํ๋ ธ์ต๋๋ค!');
+ }
+ });
+ };
+ handleInput = event => {
+ const { name, value } = event.target;
+ this.setState({
+ [name]: value,
+ });
+ };
+
+ goToMain = () => {
+ this.props.history.push('/MainAh');
+ };
+
render() {
+ const { idInput, pwInput } = this.state;
+ const isButtonActive = idInput.includes('@') && pwInput.length >= 5;
return (
- <div>
- <p>๋ค์ฌ</p>
+ <div className="Login">
+ <div className="container">
+ <div className="loginContainer">
+ <p>westagram</p>
+ <div className="idContainer">
+ <input
+ onChange={this.handleInput}
+ name="idInput"
+ type="text"
+ className="inputId"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ />
+ </div>
+ <div className="passwordContainer">
+ <input
+ onChange={this.handleInput}
+ name="pwInput"
+ type="password"
+ className="inputPassword"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ />
+ </div>
+ <button
+ disabled={!isButtonActive}
+ className={`loginButton ${
+ isButtonActive ? 'loginButtonOn' : 'loginButtonOff'
+ }`}
+ // onClick={this.goToMain}
+ onClick={this.loginTest}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div>
+ <a href="google.com">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </div>
+ </div>
</div>
);
}
}
-export default LoginAh;
+export default withRouter(LoginAh); | JavaScript | - defaultColor ์ disabled ๋ฅผ state ์์ ๊ด๋ฆฌํ์ง ์๋๋ก ํ๋ค๋ฉด, ์ด ๋ก์ง ๋ถ๋ถ์ ๋ ์ด์ ํ์ ์์ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -1,13 +1,92 @@
import React from 'react';
+import { withRouter } from 'react-router-dom';
+import './Login.scss';
class LoginAh extends React.Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ idInput: '',
+ pwInput: '',
+ };
+ }
+
+ loginTest = () => {
+ fetch('users/login', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ email: this.state.idInput,
+ password: this.state.pwInput,
+ }),
+ })
+ .then(response => response.json())
+ .then(response => {
+ if (response.token) {
+ localStorage.setItem('token', response.token);
+ this.props.history.push('/MainAh');
+ } else {
+ alert('์์ด๋/๋น๋ฐ๋ฒํธ๊ฐ ํ๋ ธ์ต๋๋ค!');
+ }
+ });
+ };
+ handleInput = event => {
+ const { name, value } = event.target;
+ this.setState({
+ [name]: value,
+ });
+ };
+
+ goToMain = () => {
+ this.props.history.push('/MainAh');
+ };
+
render() {
+ const { idInput, pwInput } = this.state;
+ const isButtonActive = idInput.includes('@') && pwInput.length >= 5;
return (
- <div>
- <p>๋ค์ฌ</p>
+ <div className="Login">
+ <div className="container">
+ <div className="loginContainer">
+ <p>westagram</p>
+ <div className="idContainer">
+ <input
+ onChange={this.handleInput}
+ name="idInput"
+ type="text"
+ className="inputId"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ />
+ </div>
+ <div className="passwordContainer">
+ <input
+ onChange={this.handleInput}
+ name="pwInput"
+ type="password"
+ className="inputPassword"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ />
+ </div>
+ <button
+ disabled={!isButtonActive}
+ className={`loginButton ${
+ isButtonActive ? 'loginButtonOn' : 'loginButtonOff'
+ }`}
+ // onClick={this.goToMain}
+ onClick={this.loginTest}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div>
+ <a href="google.com">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </div>
+ </div>
</div>
);
}
}
-export default LoginAh;
+export default withRouter(LoginAh); | JavaScript | - idInput ๊ณผ pwInput ์ ์ฌ์ฉํด์ ๋ฐ๋ก ๊ฐ์ ๊ณ์ฐํ ์ ์์ต๋๋ค. ์ฝ๋๋ ๋ค์๊ณผ ๊ฐ์ต๋๋ค. ์ฐธ๊ณ ํด์ฃผ์ธ์!
- inline ์คํ์ผ๋ง์ ์ฃผ์๋ ๊ฒ์ ๊ผญ ํ์ํ ๊ฒฝ์ฐ๊ฐ ์๋๋ผ๋ฉด ์ง์ํด์ฃผ์๊ณ , className ์ ๋์ ์ผ๋ก ๋ถ์ฌํ๋ ๊ฒ์ผ๋ก ์คํ์ผ๋ง ํด์ฃผ์ธ์!
- inline ์คํ์ผ๋ง์ ์ฌ์ฉํ์๋ ๊ฒฝ์ฐ๋, ์ฌ๋ผ์ด๋๋ฅผ ๊ตฌํ๊ณผ ๊ฐ์ด ์คํ์ผ๋ง์ด ๋งค์ฐ ๋ง์ด ์ง์์ ์ผ๋ก ๋ณํด์ผ ํ๋ ์ํฉ์ ์ฌ์ฉํด ์ฃผ์๋ ๊ฒ๋๋ค!
```jsx
render () {
const { idInput, pwInput } = this.state;
isButtonActive = idInput.includes('@') && pwInput.length >= 5
return (
...
<button
disabled={!isButtonActive}
className={`loginButton ${isButtonActive ? 'active' : ''}`}
onClick={this.goToMain}
>
...
)
}
``` |
@@ -0,0 +1,46 @@
+@import url('https://fonts.googleapis.com/css2?family=Lobster&display=swap');
+@import '../../../styles/variable.scss';
+
+.Login {
+ .container {
+ width: 2000px;
+ max-width: 100vw;
+
+ .loginContainer {
+ width: 350px;
+ height: 400px;
+ margin: 25vh auto;
+ border: 2px solid lightgrey;
+ text-align: center;
+
+ p {
+ margin: 50px auto;
+ font-family: 'Lobster';
+ font-size: 40px;
+ }
+
+ .inputId {
+ @include idpwContainer;
+ }
+
+ .inputPassword {
+ @include idpwContainer;
+ }
+
+ .loginButtonOn {
+ @include loginButton;
+ background-color: blue;
+ }
+
+ .loginButtonOff {
+ @include loginButton;
+ background-color: skyblue;
+ }
+
+ a {
+ text-decoration: none;
+ color: blue;
+ }
+ }
+ }
+} | Unknown | - common.scss ์ ์ ํฉํ๋ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,46 @@
+@import url('https://fonts.googleapis.com/css2?family=Lobster&display=swap');
+@import '../../../styles/variable.scss';
+
+.Login {
+ .container {
+ width: 2000px;
+ max-width: 100vw;
+
+ .loginContainer {
+ width: 350px;
+ height: 400px;
+ margin: 25vh auto;
+ border: 2px solid lightgrey;
+ text-align: center;
+
+ p {
+ margin: 50px auto;
+ font-family: 'Lobster';
+ font-size: 40px;
+ }
+
+ .inputId {
+ @include idpwContainer;
+ }
+
+ .inputPassword {
+ @include idpwContainer;
+ }
+
+ .loginButtonOn {
+ @include loginButton;
+ background-color: blue;
+ }
+
+ .loginButtonOff {
+ @include loginButton;
+ background-color: skyblue;
+ }
+
+ a {
+ text-decoration: none;
+ color: blue;
+ }
+ }
+ }
+} | Unknown | - mixin ์ variable.scss ์ ๊ฐ์ ๋ณ๋์ ํ์ผ์ ํ๋ ๋ ๋ง๋ค์ด์ ๊ทธ๊ณณ์์ ์ผ๊ด์ ์ผ๋ก ๊ด๋ฆฌํด์ฃผ์ธ์! |
@@ -0,0 +1,46 @@
+@import url('https://fonts.googleapis.com/css2?family=Lobster&display=swap');
+@import '../../../styles/variable.scss';
+
+.Login {
+ .container {
+ width: 2000px;
+ max-width: 100vw;
+
+ .loginContainer {
+ width: 350px;
+ height: 400px;
+ margin: 25vh auto;
+ border: 2px solid lightgrey;
+ text-align: center;
+
+ p {
+ margin: 50px auto;
+ font-family: 'Lobster';
+ font-size: 40px;
+ }
+
+ .inputId {
+ @include idpwContainer;
+ }
+
+ .inputPassword {
+ @include idpwContainer;
+ }
+
+ .loginButtonOn {
+ @include loginButton;
+ background-color: blue;
+ }
+
+ .loginButtonOff {
+ @include loginButton;
+ background-color: skyblue;
+ }
+
+ a {
+ text-decoration: none;
+ color: blue;
+ }
+ }
+ }
+} | Unknown | - ์คํ์ผ๋ง์ ๋ถ์ฌํ๊ธฐ ์ํจ์ผ๋ก๋ className ์ผ๋ก๋ ์ถฉ๋ถํฉ๋๋ค. id ๋ฅผ ์ฌ์ฉํ์ค ์ด์ ๊ฐ ์์ต๋๋ค. |
@@ -1,13 +1,108 @@
import React from 'react';
+import { withRouter } from 'react-router-dom';
+import Nav from '../../../components/Nav/Nav';
+import CommentList from '../Comment/CommentList';
+import './Main.scss';
class MainAh extends React.Component {
render() {
return (
- <div>
- <p>๋ช
์ฑ</p>
+ <div className="MainAh">
+ <Nav />
+ <div className="mainContainer">
+ <div className="feedsContainer">
+ <article>
+ <div className="feedsTop">
+ <img
+ className="profileImage"
+ src="/images/baeyoonah/Main/mark.png"
+ alt=""
+ />
+ <span className="feedsId">wecode-bootcamp</span>
+ </div>
+ <img src="/images/baeyoonah/Main/liberty.jpg" alt="" />
+ <div className="feedsIcon">
+ <ul>
+ <li>
+ <img src="/images/baeyoonah/Main/redheart.png" alt="" />
+ </li>
+ <li>
+ <img src="/images/baeyoonah/Main/what.png" alt="" />
+ </li>
+ <li>
+ <img src="/images/baeyoonah/Main/share.png" alt="" />
+ </li>
+ </ul>
+ <img src="/images/baeyoonah/Main/tag.png" alt="" />
+ </div>
+ <div className="feedsContent">
+ <div>
+ <img src="/images/baeyoonah/Main/mark.png" alt="" />
+ <span className="feedsId">ainworld</span>
+ <span className="feedsText">๋ ์ธ 4๋ช
์ด ์ข์ํฉ๋๋ค.</span>
+ </div>
+ <CommentList />
+ </div>
+ </article>
+ </div>
+ <div className="mainRightContainer">
+ <div className="mainRightTop">
+ <img src="/images/baeyoonah/Main/mark.png" alt="" />
+ <span className="siteId">wecode_bootcamp</span>
+ <p className="mainRightIdInfo">Wecode | ์์ฝ๋</p>
+ </div>
+
+ <div className="storyContainer">
+ <div className="storyMenu">
+ <span className="storyId">์คํ ๋ฆฌ</span>
+ <span className="storyIdInfo">๋ชจ๋๋ณด๊ธฐ</span>
+ </div>
+ <div className="storyContent">
+ <img src="/images/baeyoonah/Main/mark.png" alt="" />
+ <span className="siteId">_yms_s</span>
+ <p className="siteIdInfo">16๋ถ ์ </p>
+ </div>
+ <div className="storyContent">
+ <img src="/images/baeyoonah/Main/mark.png" alt="" />
+ <span className="siteId">_yms_s</span>
+ <p className="siteIdInfo">16๋ถ ์ </p>
+ </div>
+ <div className="storyContent">
+ <img src="/images/baeyoonah/Main/mark.png" alt="" />
+ <span className="siteId">_yms_s</span>
+ <p className="siteIdInfo">16๋ถ ์ </p>
+ </div>
+ </div>
+
+ <div className="follow">
+ <div className="storyMenu">
+ <span className="storyId">ํ์๋์ ์ํ ์ถ์ฒ</span>
+ <span className="storyIdInfo">๋ชจ๋ ๋ณด๊ธฐ</span>
+ </div>
+ <div className="storyContent">
+ <img src="/images/baeyoonah/Main/mark.png" alt="" />
+ <span className="siteId">ioaaaaaahye</span>
+ <p className="siteIdInfo">_legenda๋ ์ธ 2๋ช
์ด ...</p>
+ <button className="followBtn">ํ๋ก์ฐ</button>
+ </div>
+ <div className="storyContent">
+ <img src="/images/baeyoonah/Main/mark.png" alt="" />
+ <span className="siteId">ioaaaaaahye</span>
+ <p className="siteIdInfo">_legenda๋ ์ธ 2๋ช
์ด ...</p>
+ <button className="followBtn">ํ๋ก์ฐ</button>
+ </div>
+ <div className="storyContent">
+ <img src="/images/baeyoonah/Main/mark.png" alt="" />
+ <span className="siteId">ioaaaaaahye</span>
+ <p className="siteIdInfo">_legenda๋ ์ธ 2๋ช
์ด ...</p>
+ <button className="followBtn">ํ๋ก์ฐ</button>
+ </div>
+ </div>
+ </div>
+ </div>
</div>
);
}
}
-export default MainAh;
+export default withRouter(MainAh); | JavaScript | - ๋ฐ๋ณต์ ์ธ ๊ตฌ์กฐ๊ฐ ๋ณด์ด๋ค์! ๊ทธ๋ฆฌ๊ณ ์ฌ์ค ์ด ๋ถ๋ถ์ ๋ฐฑ์๋์์ ์ ๋ณด๋ฅผ ๋ฐ์์์ ํ๋ฉด์ ๊ทธ๋ฆฌ๋ ๊ฒ์ด๋ฏ๋ก, ๋ชฉ์
๋ฐ์ดํฐ๋ฅผ ๊ตฌ์ฑํ์
์ map ํจ์๋ฅผ ์ฌ์ฉํ์ฌ ๊ตฌํํด์ฃผ์๋๊ฒ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -1,13 +1,108 @@
import React from 'react';
+import { withRouter } from 'react-router-dom';
+import Nav from '../../../components/Nav/Nav';
+import CommentList from '../Comment/CommentList';
+import './Main.scss';
class MainAh extends React.Component {
render() {
return (
- <div>
- <p>๋ช
์ฑ</p>
+ <div className="MainAh">
+ <Nav />
+ <div className="mainContainer">
+ <div className="feedsContainer">
+ <article>
+ <div className="feedsTop">
+ <img
+ className="profileImage"
+ src="/images/baeyoonah/Main/mark.png"
+ alt=""
+ />
+ <span className="feedsId">wecode-bootcamp</span>
+ </div>
+ <img src="/images/baeyoonah/Main/liberty.jpg" alt="" />
+ <div className="feedsIcon">
+ <ul>
+ <li>
+ <img src="/images/baeyoonah/Main/redheart.png" alt="" />
+ </li>
+ <li>
+ <img src="/images/baeyoonah/Main/what.png" alt="" />
+ </li>
+ <li>
+ <img src="/images/baeyoonah/Main/share.png" alt="" />
+ </li>
+ </ul>
+ <img src="/images/baeyoonah/Main/tag.png" alt="" />
+ </div>
+ <div className="feedsContent">
+ <div>
+ <img src="/images/baeyoonah/Main/mark.png" alt="" />
+ <span className="feedsId">ainworld</span>
+ <span className="feedsText">๋ ์ธ 4๋ช
์ด ์ข์ํฉ๋๋ค.</span>
+ </div>
+ <CommentList />
+ </div>
+ </article>
+ </div>
+ <div className="mainRightContainer">
+ <div className="mainRightTop">
+ <img src="/images/baeyoonah/Main/mark.png" alt="" />
+ <span className="siteId">wecode_bootcamp</span>
+ <p className="mainRightIdInfo">Wecode | ์์ฝ๋</p>
+ </div>
+
+ <div className="storyContainer">
+ <div className="storyMenu">
+ <span className="storyId">์คํ ๋ฆฌ</span>
+ <span className="storyIdInfo">๋ชจ๋๋ณด๊ธฐ</span>
+ </div>
+ <div className="storyContent">
+ <img src="/images/baeyoonah/Main/mark.png" alt="" />
+ <span className="siteId">_yms_s</span>
+ <p className="siteIdInfo">16๋ถ ์ </p>
+ </div>
+ <div className="storyContent">
+ <img src="/images/baeyoonah/Main/mark.png" alt="" />
+ <span className="siteId">_yms_s</span>
+ <p className="siteIdInfo">16๋ถ ์ </p>
+ </div>
+ <div className="storyContent">
+ <img src="/images/baeyoonah/Main/mark.png" alt="" />
+ <span className="siteId">_yms_s</span>
+ <p className="siteIdInfo">16๋ถ ์ </p>
+ </div>
+ </div>
+
+ <div className="follow">
+ <div className="storyMenu">
+ <span className="storyId">ํ์๋์ ์ํ ์ถ์ฒ</span>
+ <span className="storyIdInfo">๋ชจ๋ ๋ณด๊ธฐ</span>
+ </div>
+ <div className="storyContent">
+ <img src="/images/baeyoonah/Main/mark.png" alt="" />
+ <span className="siteId">ioaaaaaahye</span>
+ <p className="siteIdInfo">_legenda๋ ์ธ 2๋ช
์ด ...</p>
+ <button className="followBtn">ํ๋ก์ฐ</button>
+ </div>
+ <div className="storyContent">
+ <img src="/images/baeyoonah/Main/mark.png" alt="" />
+ <span className="siteId">ioaaaaaahye</span>
+ <p className="siteIdInfo">_legenda๋ ์ธ 2๋ช
์ด ...</p>
+ <button className="followBtn">ํ๋ก์ฐ</button>
+ </div>
+ <div className="storyContent">
+ <img src="/images/baeyoonah/Main/mark.png" alt="" />
+ <span className="siteId">ioaaaaaahye</span>
+ <p className="siteIdInfo">_legenda๋ ์ธ 2๋ช
์ด ...</p>
+ <button className="followBtn">ํ๋ก์ฐ</button>
+ </div>
+ </div>
+ </div>
+ </div>
</div>
);
}
}
-export default MainAh;
+export default withRouter(MainAh); | JavaScript | - ์ฌ๊ธฐ๋ ์์ ๋์ผํฉ๋๋ค! |
@@ -0,0 +1,201 @@
+body {
+ margin: 0;
+}
+@import url('https://fonts.googleapis.com/css2?family=Lobster&display=swap');
+
+.MainAh {
+ .mainContainer {
+ display: flex;
+ position: relative;
+ justify-content: center;
+ width: 2000px;
+ max-width: 100vw;
+ height: 2000px;
+ background-color: #fafafa;
+ }
+
+ .feedsContainer {
+ position: absolute;
+ left: 15%;
+ margin-top: 50px;
+ width: 45%;
+ border: 2px solid lightgrey;
+ background-color: white;
+
+ p {
+ margin: 0;
+ }
+ }
+
+ .feedsTop {
+ margin: 15px 0;
+ }
+
+ article {
+ width: 100%;
+ .profileImage {
+ vertical-align: middle;
+ margin-left: 15px;
+ margin-right: 10px;
+ width: 30px;
+ height: 30px;
+ }
+
+ img {
+ width: 100%;
+ }
+ }
+
+ .feedsIcon {
+ display: flex;
+ justify-content: space-between;
+ margin-top: 5px;
+
+ ul {
+ display: flex;
+ margin: 0;
+ padding-left: 10px;
+ }
+ li {
+ list-style: none;
+ margin-right: 10px;
+ }
+ img {
+ margin-right: 10px;
+ width: 30px;
+ height: 30px;
+ }
+ }
+
+ .feedsContent {
+ padding: 10px;
+ border-bottom: 2px solid lightgrey;
+
+ img {
+ margin-right: 5px;
+ width: 15px;
+ height: 15px;
+ }
+
+ .feedsId {
+ font-weight: bold;
+ }
+ .feedsText {
+ margin-left: 10px;
+ font-weight: normal;
+ }
+ }
+
+ .newText {
+ margin: 15px 0px 15px 10px;
+
+ input {
+ width: 90%;
+ border: none;
+ color: black;
+ }
+ button {
+ border: none;
+ background-color: white;
+ color: skyblue;
+ }
+ }
+
+ .mainRightContainer {
+ display: flex;
+ flex-direction: column;
+ position: fixed;
+ left: 63%;
+ margin-top: 50px;
+ width: 20%;
+
+ img {
+ width: 40px;
+ height: 40px;
+ }
+
+ .mainRightIdInfo {
+ position: absolute;
+ top: 20px;
+ left: 5px;
+ margin: 0;
+ margin-left: 50px;
+ color: grey;
+ }
+ }
+ .mainRightTop {
+ margin-bottom: 10px;
+
+ img {
+ vertical-align: middle;
+ margin-right: 10px;
+ width: 45px;
+ height: 45px;
+ }
+ }
+
+ .storyContainer {
+ border: 2px solid lightgrey;
+ margin-top: 10px;
+ background-color: white;
+ }
+ // story, follow ๊ณตํต ์ฌ์ฉ
+ .storyMenu {
+ display: flex;
+ justify-content: space-between;
+ margin: 15px;
+ }
+ .storyContent {
+ margin: 15px;
+ position: relative;
+
+ img {
+ vertical-align: middle;
+ margin-right: 15px;
+ width: 35px;
+ height: 35px;
+ }
+ }
+ // ํน์ ์ปจํ
์ด๋ ์์ ๋ค์ด๊ฐ์์ง ์๊ณ ๊ณตํต์ผ๋ก ์ฐ๋์ค
+ .siteId {
+ position: absolute;
+ top: 2px;
+ font-weight: bold;
+ }
+
+ .siteIdInfo {
+ position: absolute;
+ top: 20px;
+ left: 5px;
+ margin: 0;
+ margin-left: 45px;
+ color: grey;
+ }
+
+ .storyId {
+ color: grey;
+ margin: 0;
+ }
+
+ .storyIdinfo {
+ font-weight: bold;
+ }
+
+ .follow {
+ margin-top: 15px;
+ border: 2px solid lightgrey;
+ background-color: white;
+
+ .followBtn {
+ position: absolute;
+ top: 10px;
+ right: 0;
+ float: right;
+ padding: 0;
+ border: none;
+ background-color: white;
+ color: blue;
+ font-size: 15px;
+ }
+ }
+} | Unknown | - reset.scss ์ ์ ํฉํด ๋ณด์ด๋ค์! |
@@ -0,0 +1,80 @@
+import React from 'react';
+import Comment from './Comment';
+import './CommentList.scss';
+
+class CommentList extends React.Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ commentInput: '',
+ newComment: [],
+ nickname: '',
+ commentList: [],
+ commentValue: '',
+ };
+ }
+
+ componentDidMount() {
+ fetch('http://localhost:3000/data/commentData.json', {
+ method: 'GET', // GET method๋ ๊ธฐ๋ณธ๊ฐ์ด๋ผ์ ์๋ต์ด ๊ฐ๋ฅํฉ๋๋ค.
+ }) // ์์์ฝ๋์์๋ ์ดํด๋ฅผ ๋๊ธฐ ์ํด ๋ช
์์ ์ผ๋ก ๊ธฐ์
ํด๋์ต๋๋ค.
+ .then(res => res.json())
+ .then(data => {
+ this.setState({
+ commentList: data,
+ });
+ });
+ }
+
+ checkInput = e => {
+ this.setState({
+ commentInput: e.target.value,
+ });
+ };
+
+ inputToComment = () => {
+ const { newComment, commentInput } = this.state;
+ this.setState({
+ nickname: 'wecode_bootcamp',
+ newComment: newComment.concat(commentInput),
+ });
+ };
+
+ enterPress = e => {
+ if (e.key === 'Enter') {
+ this.inputToComment();
+ }
+ e.target.value = '';
+ };
+
+ render() {
+ const { commentValue, commentList } = this.state;
+ return (
+ <div className="commentList">
+ {commentList.map(comment => {
+ return (
+ <Comment
+ key={comment.id}
+ nickname={comment.userName}
+ comment={comment.content}
+ />
+ );
+ })}
+
+ <div className="newText">
+ <input
+ id="typingText"
+ value={commentValue}
+ onChange={this.checkInput}
+ onKeyPress={this.enterPress}
+ type="text"
+ placeholder="๋๊ธ ๋ฌ๊ธฐ...."
+ />
+ <button onClick={this.checkInput}>๊ฒ์</button>
+ </div>
+ </div>
+ );
+ }
+}
+
+export default CommentList; | JavaScript | ์ ์ฉ์๋ฃ~! ๋ค์ฌ๋ ์ต๊ณ ! |
@@ -0,0 +1,23 @@
+import React from 'react';
+import './Comment.scss';
+
+class NewComment extends React.Component {
+ render() {
+ // const newArray = this.props.newComment.map((commentarray, index) => (
+ // <li key={index}>
+ // <span className="newCommentid">{this.props.nickname}</span>
+ // <span className="newComments">{commentarray}</span>
+ // </li>
+ // ));
+ return (
+ <div className="comment">
+ <div className="newComment">
+ <span className="newCommentid">{this.props.nickname}</span>
+ <span className="newComments">{this.props.comment}</span>
+ </div>
+ </div>
+ );
+ }
+}
+
+export default NewComment; | JavaScript | ์ง์ ์ต๋๋ค! |
@@ -0,0 +1,15 @@
+.comment {
+ .newComment {
+ margin-bottom: 5px;
+ }
+
+ .newCommentid {
+ font-weight: bold;
+ margin-bottom: 0;
+ }
+
+ .newComments {
+ font-weight: normal;
+ margin-left: 5px;
+ }
+} | Unknown | ์์ ํ์ต๋๋ค! |
@@ -0,0 +1,80 @@
+import React from 'react';
+import Comment from './Comment';
+import './CommentList.scss';
+
+class CommentList extends React.Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ commentInput: '',
+ newComment: [],
+ nickname: '',
+ commentList: [],
+ commentValue: '',
+ };
+ }
+
+ componentDidMount() {
+ fetch('http://localhost:3000/data/commentData.json', {
+ method: 'GET', // GET method๋ ๊ธฐ๋ณธ๊ฐ์ด๋ผ์ ์๋ต์ด ๊ฐ๋ฅํฉ๋๋ค.
+ }) // ์์์ฝ๋์์๋ ์ดํด๋ฅผ ๋๊ธฐ ์ํด ๋ช
์์ ์ผ๋ก ๊ธฐ์
ํด๋์ต๋๋ค.
+ .then(res => res.json())
+ .then(data => {
+ this.setState({
+ commentList: data,
+ });
+ });
+ }
+
+ checkInput = e => {
+ this.setState({
+ commentInput: e.target.value,
+ });
+ };
+
+ inputToComment = () => {
+ const { newComment, commentInput } = this.state;
+ this.setState({
+ nickname: 'wecode_bootcamp',
+ newComment: newComment.concat(commentInput),
+ });
+ };
+
+ enterPress = e => {
+ if (e.key === 'Enter') {
+ this.inputToComment();
+ }
+ e.target.value = '';
+ };
+
+ render() {
+ const { commentValue, commentList } = this.state;
+ return (
+ <div className="commentList">
+ {commentList.map(comment => {
+ return (
+ <Comment
+ key={comment.id}
+ nickname={comment.userName}
+ comment={comment.content}
+ />
+ );
+ })}
+
+ <div className="newText">
+ <input
+ id="typingText"
+ value={commentValue}
+ onChange={this.checkInput}
+ onKeyPress={this.enterPress}
+ type="text"
+ placeholder="๋๊ธ ๋ฌ๊ธฐ...."
+ />
+ <button onClick={this.checkInput}>๊ฒ์</button>
+ </div>
+ </div>
+ );
+ }
+}
+
+export default CommentList; | JavaScript | ์ ์ฉํ์ต๋๋ค. ๊ตฌ์กฐ ๋ถํด ํ ๋น์ด ์ต์ํ์ง์์ ์จ์ผํ ๊ณณ์ ์ ๊ตฌ๋ถํ์ง ๋ชปํ๋๊ฒ ๊ฐ์ต๋๋ค.. ใ
|
@@ -0,0 +1,23 @@
+import React from 'react';
+import './Comment.scss';
+
+class NewComment extends React.Component {
+ render() {
+ // const newArray = this.props.newComment.map((commentarray, index) => (
+ // <li key={index}>
+ // <span className="newCommentid">{this.props.nickname}</span>
+ // <span className="newComments">{commentarray}</span>
+ // </li>
+ // ));
+ return (
+ <div className="comment">
+ <div className="newComment">
+ <span className="newCommentid">{this.props.nickname}</span>
+ <span className="newComments">{this.props.comment}</span>
+ </div>
+ </div>
+ );
+ }
+}
+
+export default NewComment; | JavaScript | ์ ์ด๋ฐ ์ค์๋ฅผ ... ์์ ํ์ต๋๋ค! |
@@ -0,0 +1,80 @@
+import React from 'react';
+import Comment from './Comment';
+import './CommentList.scss';
+
+class CommentList extends React.Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ commentInput: '',
+ newComment: [],
+ nickname: '',
+ commentList: [],
+ commentValue: '',
+ };
+ }
+
+ componentDidMount() {
+ fetch('http://localhost:3000/data/commentData.json', {
+ method: 'GET', // GET method๋ ๊ธฐ๋ณธ๊ฐ์ด๋ผ์ ์๋ต์ด ๊ฐ๋ฅํฉ๋๋ค.
+ }) // ์์์ฝ๋์์๋ ์ดํด๋ฅผ ๋๊ธฐ ์ํด ๋ช
์์ ์ผ๋ก ๊ธฐ์
ํด๋์ต๋๋ค.
+ .then(res => res.json())
+ .then(data => {
+ this.setState({
+ commentList: data,
+ });
+ });
+ }
+
+ checkInput = e => {
+ this.setState({
+ commentInput: e.target.value,
+ });
+ };
+
+ inputToComment = () => {
+ const { newComment, commentInput } = this.state;
+ this.setState({
+ nickname: 'wecode_bootcamp',
+ newComment: newComment.concat(commentInput),
+ });
+ };
+
+ enterPress = e => {
+ if (e.key === 'Enter') {
+ this.inputToComment();
+ }
+ e.target.value = '';
+ };
+
+ render() {
+ const { commentValue, commentList } = this.state;
+ return (
+ <div className="commentList">
+ {commentList.map(comment => {
+ return (
+ <Comment
+ key={comment.id}
+ nickname={comment.userName}
+ comment={comment.content}
+ />
+ );
+ })}
+
+ <div className="newText">
+ <input
+ id="typingText"
+ value={commentValue}
+ onChange={this.checkInput}
+ onKeyPress={this.enterPress}
+ type="text"
+ placeholder="๋๊ธ ๋ฌ๊ธฐ...."
+ />
+ <button onClick={this.checkInput}>๊ฒ์</button>
+ </div>
+ </div>
+ );
+ }
+}
+
+export default CommentList; | JavaScript | ์์์ ๋ฐ์์จ 'wecode-bootcamp' ๋ผ๋ id ๊ฐ์ ๋ฐ์์ค๊ธฐ ์ํด ์ฌ์ฉํ๋๋ฐ, ํ์คํ id ๋ผ๋๊ฒ์ ์ ์ ์น ์์ nickname ์ผ๋ก ์์ ํ์ต๋๋ค! |
@@ -0,0 +1,80 @@
+import React from 'react';
+import Comment from './Comment';
+import './CommentList.scss';
+
+class CommentList extends React.Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ commentInput: '',
+ newComment: [],
+ nickname: '',
+ commentList: [],
+ commentValue: '',
+ };
+ }
+
+ componentDidMount() {
+ fetch('http://localhost:3000/data/commentData.json', {
+ method: 'GET', // GET method๋ ๊ธฐ๋ณธ๊ฐ์ด๋ผ์ ์๋ต์ด ๊ฐ๋ฅํฉ๋๋ค.
+ }) // ์์์ฝ๋์์๋ ์ดํด๋ฅผ ๋๊ธฐ ์ํด ๋ช
์์ ์ผ๋ก ๊ธฐ์
ํด๋์ต๋๋ค.
+ .then(res => res.json())
+ .then(data => {
+ this.setState({
+ commentList: data,
+ });
+ });
+ }
+
+ checkInput = e => {
+ this.setState({
+ commentInput: e.target.value,
+ });
+ };
+
+ inputToComment = () => {
+ const { newComment, commentInput } = this.state;
+ this.setState({
+ nickname: 'wecode_bootcamp',
+ newComment: newComment.concat(commentInput),
+ });
+ };
+
+ enterPress = e => {
+ if (e.key === 'Enter') {
+ this.inputToComment();
+ }
+ e.target.value = '';
+ };
+
+ render() {
+ const { commentValue, commentList } = this.state;
+ return (
+ <div className="commentList">
+ {commentList.map(comment => {
+ return (
+ <Comment
+ key={comment.id}
+ nickname={comment.userName}
+ comment={comment.content}
+ />
+ );
+ })}
+
+ <div className="newText">
+ <input
+ id="typingText"
+ value={commentValue}
+ onChange={this.checkInput}
+ onKeyPress={this.enterPress}
+ type="text"
+ placeholder="๋๊ธ ๋ฌ๊ธฐ...."
+ />
+ <button onClick={this.checkInput}>๊ฒ์</button>
+ </div>
+ </div>
+ );
+ }
+}
+
+export default CommentList; | JavaScript | ์ง์ ์ต๋๋ค! |
@@ -1,13 +1,92 @@
import React from 'react';
+import { withRouter } from 'react-router-dom';
+import './Login.scss';
class LoginAh extends React.Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ idInput: '',
+ pwInput: '',
+ };
+ }
+
+ loginTest = () => {
+ fetch('users/login', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ email: this.state.idInput,
+ password: this.state.pwInput,
+ }),
+ })
+ .then(response => response.json())
+ .then(response => {
+ if (response.token) {
+ localStorage.setItem('token', response.token);
+ this.props.history.push('/MainAh');
+ } else {
+ alert('์์ด๋/๋น๋ฐ๋ฒํธ๊ฐ ํ๋ ธ์ต๋๋ค!');
+ }
+ });
+ };
+ handleInput = event => {
+ const { name, value } = event.target;
+ this.setState({
+ [name]: value,
+ });
+ };
+
+ goToMain = () => {
+ this.props.history.push('/MainAh');
+ };
+
render() {
+ const { idInput, pwInput } = this.state;
+ const isButtonActive = idInput.includes('@') && pwInput.length >= 5;
return (
- <div>
- <p>๋ค์ฌ</p>
+ <div className="Login">
+ <div className="container">
+ <div className="loginContainer">
+ <p>westagram</p>
+ <div className="idContainer">
+ <input
+ onChange={this.handleInput}
+ name="idInput"
+ type="text"
+ className="inputId"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ />
+ </div>
+ <div className="passwordContainer">
+ <input
+ onChange={this.handleInput}
+ name="pwInput"
+ type="password"
+ className="inputPassword"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ />
+ </div>
+ <button
+ disabled={!isButtonActive}
+ className={`loginButton ${
+ isButtonActive ? 'loginButtonOn' : 'loginButtonOff'
+ }`}
+ // onClick={this.goToMain}
+ onClick={this.loginTest}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div>
+ <a href="google.com">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </div>
+ </div>
</div>
);
}
}
-export default LoginAh;
+export default withRouter(LoginAh); | JavaScript | ์์ ํ์ต๋๋ค! |
@@ -1,13 +1,92 @@
import React from 'react';
+import { withRouter } from 'react-router-dom';
+import './Login.scss';
class LoginAh extends React.Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ idInput: '',
+ pwInput: '',
+ };
+ }
+
+ loginTest = () => {
+ fetch('users/login', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ email: this.state.idInput,
+ password: this.state.pwInput,
+ }),
+ })
+ .then(response => response.json())
+ .then(response => {
+ if (response.token) {
+ localStorage.setItem('token', response.token);
+ this.props.history.push('/MainAh');
+ } else {
+ alert('์์ด๋/๋น๋ฐ๋ฒํธ๊ฐ ํ๋ ธ์ต๋๋ค!');
+ }
+ });
+ };
+ handleInput = event => {
+ const { name, value } = event.target;
+ this.setState({
+ [name]: value,
+ });
+ };
+
+ goToMain = () => {
+ this.props.history.push('/MainAh');
+ };
+
render() {
+ const { idInput, pwInput } = this.state;
+ const isButtonActive = idInput.includes('@') && pwInput.length >= 5;
return (
- <div>
- <p>๋ค์ฌ</p>
+ <div className="Login">
+ <div className="container">
+ <div className="loginContainer">
+ <p>westagram</p>
+ <div className="idContainer">
+ <input
+ onChange={this.handleInput}
+ name="idInput"
+ type="text"
+ className="inputId"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ />
+ </div>
+ <div className="passwordContainer">
+ <input
+ onChange={this.handleInput}
+ name="pwInput"
+ type="password"
+ className="inputPassword"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ />
+ </div>
+ <button
+ disabled={!isButtonActive}
+ className={`loginButton ${
+ isButtonActive ? 'loginButtonOn' : 'loginButtonOff'
+ }`}
+ // onClick={this.goToMain}
+ onClick={this.loginTest}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div>
+ <a href="google.com">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </div>
+ </div>
</div>
);
}
}
-export default LoginAh;
+export default withRouter(LoginAh); | JavaScript | defaultColor๋ ์์ ์ง์ฐ๊ณ ์ผํญ์ฐ์ฐ์๋ฅผ ์ด์ฉํ ํด๊ฒฐ๋ฐฉ๋ฒ์ ๋ฐ์ ์ฃผ์
์ ๊ทธ๊ฑฐ๋ก ์์ ๋ณํ๊น์ง ์ ์ฉํ์์ต๋๋ค. ์ํ๊ฐ ๋ณํ๋ค๊ณ ์๊ฐ๋๋๊ฒ์ ์๊พธ state๋ฅผ ์ด์ฉํ๊ฒ ๋๋๊ฑฐ ๊ฐ์ ๋ ๊ณต๋ถํ๊ฒ ์ต๋๋ค. |
@@ -1,13 +1,92 @@
import React from 'react';
+import { withRouter } from 'react-router-dom';
+import './Login.scss';
class LoginAh extends React.Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ idInput: '',
+ pwInput: '',
+ };
+ }
+
+ loginTest = () => {
+ fetch('users/login', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ email: this.state.idInput,
+ password: this.state.pwInput,
+ }),
+ })
+ .then(response => response.json())
+ .then(response => {
+ if (response.token) {
+ localStorage.setItem('token', response.token);
+ this.props.history.push('/MainAh');
+ } else {
+ alert('์์ด๋/๋น๋ฐ๋ฒํธ๊ฐ ํ๋ ธ์ต๋๋ค!');
+ }
+ });
+ };
+ handleInput = event => {
+ const { name, value } = event.target;
+ this.setState({
+ [name]: value,
+ });
+ };
+
+ goToMain = () => {
+ this.props.history.push('/MainAh');
+ };
+
render() {
+ const { idInput, pwInput } = this.state;
+ const isButtonActive = idInput.includes('@') && pwInput.length >= 5;
return (
- <div>
- <p>๋ค์ฌ</p>
+ <div className="Login">
+ <div className="container">
+ <div className="loginContainer">
+ <p>westagram</p>
+ <div className="idContainer">
+ <input
+ onChange={this.handleInput}
+ name="idInput"
+ type="text"
+ className="inputId"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ />
+ </div>
+ <div className="passwordContainer">
+ <input
+ onChange={this.handleInput}
+ name="pwInput"
+ type="password"
+ className="inputPassword"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ />
+ </div>
+ <button
+ disabled={!isButtonActive}
+ className={`loginButton ${
+ isButtonActive ? 'loginButtonOn' : 'loginButtonOff'
+ }`}
+ // onClick={this.goToMain}
+ onClick={this.loginTest}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div>
+ <a href="google.com">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </div>
+ </div>
</div>
);
}
}
-export default LoginAh;
+export default withRouter(LoginAh); | JavaScript | ์์ ํ์ต๋๋ค! |
@@ -1,13 +1,92 @@
import React from 'react';
+import { withRouter } from 'react-router-dom';
+import './Login.scss';
class LoginAh extends React.Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ idInput: '',
+ pwInput: '',
+ };
+ }
+
+ loginTest = () => {
+ fetch('users/login', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ email: this.state.idInput,
+ password: this.state.pwInput,
+ }),
+ })
+ .then(response => response.json())
+ .then(response => {
+ if (response.token) {
+ localStorage.setItem('token', response.token);
+ this.props.history.push('/MainAh');
+ } else {
+ alert('์์ด๋/๋น๋ฐ๋ฒํธ๊ฐ ํ๋ ธ์ต๋๋ค!');
+ }
+ });
+ };
+ handleInput = event => {
+ const { name, value } = event.target;
+ this.setState({
+ [name]: value,
+ });
+ };
+
+ goToMain = () => {
+ this.props.history.push('/MainAh');
+ };
+
render() {
+ const { idInput, pwInput } = this.state;
+ const isButtonActive = idInput.includes('@') && pwInput.length >= 5;
return (
- <div>
- <p>๋ค์ฌ</p>
+ <div className="Login">
+ <div className="container">
+ <div className="loginContainer">
+ <p>westagram</p>
+ <div className="idContainer">
+ <input
+ onChange={this.handleInput}
+ name="idInput"
+ type="text"
+ className="inputId"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ />
+ </div>
+ <div className="passwordContainer">
+ <input
+ onChange={this.handleInput}
+ name="pwInput"
+ type="password"
+ className="inputPassword"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ />
+ </div>
+ <button
+ disabled={!isButtonActive}
+ className={`loginButton ${
+ isButtonActive ? 'loginButtonOn' : 'loginButtonOff'
+ }`}
+ // onClick={this.goToMain}
+ onClick={this.loginTest}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div>
+ <a href="google.com">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </div>
+ </div>
</div>
);
}
}
-export default LoginAh;
+export default withRouter(LoginAh); | JavaScript | ํ๋จ์ ์ฃผ์ ํด๊ฒฐ๋ฒ์ผ๋ก ์์ ํ์ต๋๋ค! |
@@ -1,13 +1,92 @@
import React from 'react';
+import { withRouter } from 'react-router-dom';
+import './Login.scss';
class LoginAh extends React.Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ idInput: '',
+ pwInput: '',
+ };
+ }
+
+ loginTest = () => {
+ fetch('users/login', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ email: this.state.idInput,
+ password: this.state.pwInput,
+ }),
+ })
+ .then(response => response.json())
+ .then(response => {
+ if (response.token) {
+ localStorage.setItem('token', response.token);
+ this.props.history.push('/MainAh');
+ } else {
+ alert('์์ด๋/๋น๋ฐ๋ฒํธ๊ฐ ํ๋ ธ์ต๋๋ค!');
+ }
+ });
+ };
+ handleInput = event => {
+ const { name, value } = event.target;
+ this.setState({
+ [name]: value,
+ });
+ };
+
+ goToMain = () => {
+ this.props.history.push('/MainAh');
+ };
+
render() {
+ const { idInput, pwInput } = this.state;
+ const isButtonActive = idInput.includes('@') && pwInput.length >= 5;
return (
- <div>
- <p>๋ค์ฌ</p>
+ <div className="Login">
+ <div className="container">
+ <div className="loginContainer">
+ <p>westagram</p>
+ <div className="idContainer">
+ <input
+ onChange={this.handleInput}
+ name="idInput"
+ type="text"
+ className="inputId"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ />
+ </div>
+ <div className="passwordContainer">
+ <input
+ onChange={this.handleInput}
+ name="pwInput"
+ type="password"
+ className="inputPassword"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ />
+ </div>
+ <button
+ disabled={!isButtonActive}
+ className={`loginButton ${
+ isButtonActive ? 'loginButtonOn' : 'loginButtonOff'
+ }`}
+ // onClick={this.goToMain}
+ onClick={this.loginTest}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div>
+ <a href="google.com">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </div>
+ </div>
</div>
);
}
}
-export default LoginAh;
+export default withRouter(LoginAh); | JavaScript | ์ ๋ง ๊ฐ์ฌํฉ๋๋ค. ๋ฌด์กฐ๊ฑด constructor ๋จ์์ ๋ณํ์ํค๋ ์ค ์๊ณ ๊ทธ๊ณณ์์๋ง ํด๊ฒฐํ๋ ค๊ณ ํ๋๋ฐ render์์ ๋ณ๊ฒฝํ๋ฉด ๋ ๊ฐ๋จํ๊ฒ ๋๋ ๊ฒ ๊ฐ์ต๋๋ค. inline ์คํ์ผ๋ง ์ง์ํ๊ฒ ์ต๋๋ค!!! |
@@ -6,25 +6,33 @@ import { css } from '@emotion/react';
import Rating from '@/components/Rating';
import Profile from '../Profile';
import { formatDate } from '@/utils/format';
+import useModalStore from '@/stores/useModalStore';
+import useDeleteReview from '@/hooks/query/useDeleteReview';
+import ConfirmModal from '@/components/ConfirmModal';
interface ReviewCardProps {
review: Review;
- onDelete?: () => void;
showTitle: boolean;
showUser: boolean;
showDate: boolean;
showDelete: boolean;
}
-const ReviewCard = ({
- review,
- onDelete,
- showTitle,
- showUser,
- showDate,
- showDelete,
-}: ReviewCardProps) => {
- // console.log(review.imgSrc.map((src, index) => src);
+const ReviewCard = ({ review, showTitle, showUser, showDate, showDelete }: ReviewCardProps) => {
+ const setModalName = useModalStore((state) => state.setModalName);
+ const { mutate } = useDeleteReview();
+
+ const handleDelete = () => {
+ mutate(
+ { reviewId: review.reviewId },
+ {
+ onSuccess: () => {
+ setModalName(null);
+ },
+ },
+ );
+ };
+
return (
<div css={reviewStyle}>
<div className="titleStyle">
@@ -52,7 +60,21 @@ const ReviewCard = ({
<Rating rating={Number(review.rating)} />
</div>
</div>
- {showDelete && <DeleteIcon onDelete={onDelete || (() => {})} />}
+ {showDelete && (
+ <ConfirmModal
+ modalId={`my.review.delete.${review.reviewId}`}
+ onConfirm={handleDelete}
+ trigger={
+ <DeleteIcon onClick={() => setModalName(`my.review.delete.${review.reviewId}`)} />
+ }
+ message={
+ <div css={modalStyle}>
+ <p className="modalText">์ ๋ง ๋ฆฌ๋ทฐ๋ฅผ ์ญ์ ํ์๊ฒ ์ต๋๊น?</p>
+ <p className="modalSubText">์ ์ ํ์ ์ ์ญ์ ๋์ง ์์ต๋๋ค</p>
+ </div>
+ }
+ />
+ )}
</div>
<div
css={css`
@@ -134,15 +156,16 @@ const reviewStyle = css`
.imgContainer {
display: flex;
justify-content: center;
- width: 110px;
- height: 120px;
+ width: 120px;
+ height: 100px;
margin-bottom: 16px;
border-radius: 5px;
overflow: hidden;
}
img {
width: 100%;
+ object-fit: cover;
}
.ratingContainer {
@@ -155,3 +178,17 @@ const reviewStyle = css`
transform: translateY(-3px);
}
`;
+
+const modalStyle = css`
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ .modalText {
+ font-weight: 600;
+ }
+
+ .modalSubText {
+ font-size: 14px;
+ color: #999;
+ }
+`; | Unknown | _:hammer_and_wrench: Refactor suggestion_
**์๋ฌ ์ฒ๋ฆฌ ๋ก์ง ์ถ๊ฐ ํ์**
`handleDelete` ํจ์์์ mutation ์คํจ ์์ ์๋ฌ ์ฒ๋ฆฌ๊ฐ ๋๋ฝ๋์ด ์์ต๋๋ค.
๋ค์๊ณผ ๊ฐ์ด `onError` ํธ๋ค๋ฌ๋ฅผ ์ถ๊ฐํ๋ ๊ฒ์ ์ ์ํฉ๋๋ค:
```diff
const handleDelete = () => {
mutate(
{ reviewId: review.reviewId },
{
onSuccess: () => {
setModalName(null);
},
+ onError: (error) => {
+ console.error('๋ฆฌ๋ทฐ ์ญ์ ์คํจ:', error);
+ // ์๋ฌ ๋ฉ์์ง๋ฅผ ์ฌ์ฉ์์๊ฒ ํ์ํ๋ ๋ก์ง ์ถ๊ฐ
+ },
},
);
};
```
<!-- suggestion_start -->
<details>
<summary>๐ Committable suggestion</summary>
> โผ๏ธ **IMPORTANT**
> Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
`````suggestion
const ReviewCard = ({ review, showTitle, showUser, showDate, showDelete }: ReviewCardProps) => {
const setModalName = useModalStore((state) => state.setModalName);
const { mutate } = useDeleteReview();
const handleDelete = () => {
mutate(
{ reviewId: review.reviewId },
{
onSuccess: () => {
setModalName(null);
},
onError: (error) => {
console.error('๋ฆฌ๋ทฐ ์ญ์ ์คํจ:', error);
// ์๋ฌ ๋ฉ์์ง๋ฅผ ์ฌ์ฉ์์๊ฒ ํ์ํ๋ ๋ก์ง ์ถ๊ฐ
},
},
);
};
`````
</details>
<!-- suggestion_end -->
<!-- This is an auto-generated comment by CodeRabbit --> |
@@ -0,0 +1,15 @@
+{
+ "arrowParens": "always",
+ "bracketSpacing": true,
+ "jsxBracketSameLine": false,
+ "jsxSingleQuote": false,
+ "printWidth": 80,
+ "proseWrap": "always",
+ "quoteProps": "as-needed",
+ "semi": true,
+ "singleQuote": false,
+ "tabWidth": 2,
+ "trailingComma": "es5",
+ "useTabs": false,
+ "endOfLine": "auto"
+}
\ No newline at end of file | Unknown | EOL์ด ์๋ค์ |
@@ -10,7 +10,17 @@
"@babel/core": "^7.23.0",
"@babel/preset-env": "^7.22.20",
"babel-jest": "^29.7.0",
- "jest": "29.6.0"
+ "eslint": "^8.56.0",
+ "eslint-config-airbnb": "^19.0.4",
+ "eslint-config-prettier": "^9.1.0",
+ "eslint-plugin-import": "^2.29.1",
+ "eslint-plugin-jsx-a11y": "^6.8.0",
+ "eslint-plugin-prettier": "^5.1.3",
+ "eslint-plugin-react": "^7.33.2",
+ "eslint-plugin-react-hooks": "^4.6.0",
+ "husky": "^9.0.7",
+ "jest": "29.6.0",
+ "prettier": "^3.2.4"
},
"scripts": {
"test": "jest" | Unknown | ์ค.. husky๊น์ง |
@@ -0,0 +1,28 @@
+import GameMessage from "./GameMessage.js";
+import { VALID_INPUT_LENGTH } from "./gameConstants.js";
+
+class Validator {
+ static isValidInput(input) {
+ if (!this.isNumber(input))
+ throw new Error(GameMessage.INVALID_INPUT_NOT_A_NUMBER);
+ if (!this.isValidLength(input))
+ throw new Error(GameMessage.INVALID_INPUT_NOT_A_CORRECT_LENGTH);
+ if (!this.isValidLength(input))
+ throw new Error(GameMessage.INVALID_INPUT_IS_DUPLICATED);
+ return true;
+ }
+
+ static isNumber(input) {
+ return !Number.isNaN(input);
+ }
+
+ static isValidLength(input) {
+ return input.length === VALID_INPUT_LENGTH;
+ }
+
+ static isDuplicate(input) {
+ return [...new Set(input)].length === VALID_INPUT_LENGTH;
+ }
+}
+
+export default Validator; | JavaScript | 3์ด๋ผ๋ ์ซ์๋ ์ด๋ค ์๋ฏธ๋ฅผ ๊ฐ์ง๊ณ ์๋ ์ซ์ ๊ฐ์๋ฐ์,
์ด๋ฌํ ์ซ์๊ฐ ์ซ์ ๊ทธ๋๋ก ์กด์ฌํ๋ ๊ฒ์ ํํ ๋งค์ง๋๋ฒ๋ผ๊ณ ๋ถ๋ฆ
๋๋ค.
๋ฐ๋ผ์ ์ด๋ฌํ ์ซ์๋ ๋ค์์ ์ด์ ๋ก ์์ํ ํด์ฃผ๋ ๊ฒ์ด ์ข์ต๋๋ค.
1. ์์๋ก ์ซ์์ผ๊ตฌ ๊ฒ์์ ์ซ์๊ฐฏ์๊ฐ 4๋ก ๋์ด๋ฌ๋ค. ๊ทธ๋ ๋ค๋ฉด ๋ชจ๋ ํ์ผ์ ๋ค์ ธ์ 3์ 4๋ก ๊ณ ์ณ์ผํ๋ค. (๋ณ๊ฒฝ์ ์ฉ์ดํ์ง ์๋ค.)
2. ์ฒ์ ์จ๋ณด๋ฉ ํ๋ ์ฌ๋์ ์ด ์ซ์์ ์๋ฏธ๋ฅผ ํ์
ํ๊ธฐ ํ๋ค๋ค. ์ฝ๋ ๊ฐ๋
์ฑ์ด ์ค์ด๋ ๋ค. |
@@ -0,0 +1,28 @@
+import GameMessage from "./GameMessage.js";
+import { VALID_INPUT_LENGTH } from "./gameConstants.js";
+
+class Validator {
+ static isValidInput(input) {
+ if (!this.isNumber(input))
+ throw new Error(GameMessage.INVALID_INPUT_NOT_A_NUMBER);
+ if (!this.isValidLength(input))
+ throw new Error(GameMessage.INVALID_INPUT_NOT_A_CORRECT_LENGTH);
+ if (!this.isValidLength(input))
+ throw new Error(GameMessage.INVALID_INPUT_IS_DUPLICATED);
+ return true;
+ }
+
+ static isNumber(input) {
+ return !Number.isNaN(input);
+ }
+
+ static isValidLength(input) {
+ return input.length === VALID_INPUT_LENGTH;
+ }
+
+ static isDuplicate(input) {
+ return [...new Set(input)].length === VALID_INPUT_LENGTH;
+ }
+}
+
+export default Validator; | JavaScript | 1. ์ฝ๋๋ฅผ ๋ค์๊ณผ ๊ฐ์ด ๊ณ ์น๋ฉด ๋ ์ค์ด๋ญ๋๋ค ใ
ใ
```suggestion
const newArr = [...new Set(input)]
```
2. newArr์ด๋ผ๋ ์์๋ช
์ด ์ด๋ค ์๋ฏธ๋ฅผ ๋ด๊ณ ์๋ ์ด๋ฆ์ธ๊ฐ์? ์๋ฏธ๊ฐ ์๊ณ , ๋จ๋ฐ์ฑ์ผ๋ก ์ฌ์ฉ๋๋ ์ธก๋ฉด์์
์ด๋ ๊ฒ ์์ฑํด๋ ๋ ๊ฒ ๊ฐ์์.
```js
isDuplicate(input) {
if ([...new Set(input)].length !== 3) throw new Error(GameMessage.INVALID_INPUT_IS_DUPLICATED)
return true;
}
``` |
@@ -0,0 +1,28 @@
+import GameMessage from "./GameMessage.js";
+import { VALID_INPUT_LENGTH } from "./gameConstants.js";
+
+class Validator {
+ static isValidInput(input) {
+ if (!this.isNumber(input))
+ throw new Error(GameMessage.INVALID_INPUT_NOT_A_NUMBER);
+ if (!this.isValidLength(input))
+ throw new Error(GameMessage.INVALID_INPUT_NOT_A_CORRECT_LENGTH);
+ if (!this.isValidLength(input))
+ throw new Error(GameMessage.INVALID_INPUT_IS_DUPLICATED);
+ return true;
+ }
+
+ static isNumber(input) {
+ return !Number.isNaN(input);
+ }
+
+ static isValidLength(input) {
+ return input.length === VALID_INPUT_LENGTH;
+ }
+
+ static isDuplicate(input) {
+ return [...new Set(input)].length === VALID_INPUT_LENGTH;
+ }
+}
+
+export default Validator; | JavaScript | 1. ๊ฐ์ธ์ ์ธ ๊ฒฌํด๋ก๋ ๊ฒ์ฆํจ์์์๋ ํด๋น input์ด ์ ํจํ์ง/์ํ์ง(boolean) ํ๊ฐํ ๋ค์,
์ด ๊ฒฐ๊ณผ์ ๋ฐ๋ผ ์๋ฌ๋ฅผ ๋์ ธ์ฃผ๋ ํจํด์ ์ ํธํฉ๋๋ค.
๋ค์ ๋งํ๋ฉด ์๋ฌ๋ฅผ ๋์ ธ์ฃผ๋ ๋ถ๋ถ์ ์ด ํจ์(is..)๋ฅผ ํธ์ถํ๋ ๋ถ๋ถ์ผ๋ก ๋๊ธฐ๋ ๋ฐฉ์์ผ๋ก ํ๊ณคํฉ๋๋ค
2. ์ด๊ฒ static method๊ฐ ์๋ method์ผ ์ด์ ๊ฐ ์๋์? |
@@ -0,0 +1,28 @@
+import GameMessage from "./GameMessage.js";
+import { VALID_INPUT_LENGTH } from "./gameConstants.js";
+
+class Validator {
+ static isValidInput(input) {
+ if (!this.isNumber(input))
+ throw new Error(GameMessage.INVALID_INPUT_NOT_A_NUMBER);
+ if (!this.isValidLength(input))
+ throw new Error(GameMessage.INVALID_INPUT_NOT_A_CORRECT_LENGTH);
+ if (!this.isValidLength(input))
+ throw new Error(GameMessage.INVALID_INPUT_IS_DUPLICATED);
+ return true;
+ }
+
+ static isNumber(input) {
+ return !Number.isNaN(input);
+ }
+
+ static isValidLength(input) {
+ return input.length === VALID_INPUT_LENGTH;
+ }
+
+ static isDuplicate(input) {
+ return [...new Set(input)].length === VALID_INPUT_LENGTH;
+ }
+}
+
+export default Validator; | JavaScript | ํ์์๋ ์ฃผ์์ ์ง์ฐ๋ฉด ์ข๊ฒ ์ต๋๋ค ! |
@@ -0,0 +1,28 @@
+import GameMessage from "./GameMessage.js";
+import { VALID_INPUT_LENGTH } from "./gameConstants.js";
+
+class Validator {
+ static isValidInput(input) {
+ if (!this.isNumber(input))
+ throw new Error(GameMessage.INVALID_INPUT_NOT_A_NUMBER);
+ if (!this.isValidLength(input))
+ throw new Error(GameMessage.INVALID_INPUT_NOT_A_CORRECT_LENGTH);
+ if (!this.isValidLength(input))
+ throw new Error(GameMessage.INVALID_INPUT_IS_DUPLICATED);
+ return true;
+ }
+
+ static isNumber(input) {
+ return !Number.isNaN(input);
+ }
+
+ static isValidLength(input) {
+ return input.length === VALID_INPUT_LENGTH;
+ }
+
+ static isDuplicate(input) {
+ return [...new Set(input)].length === VALID_INPUT_LENGTH;
+ }
+}
+
+export default Validator; | JavaScript | boolean์ ๋ฆฌํดํ ๋๋ ๋ฉ์๋์ prefix์ is, has๋ฅผ ๋ถ์ฌ์ฃผ๋ ๊ฒ์ด ๊ด๋ก์
๋๋คใ
_ใ
|
@@ -0,0 +1,49 @@
+import { Random } from "@woowacourse/mission-utils";
+import {
+ VALID_INPUT_LENGTH,
+ MIN_RANDOM_NUMBER,
+ MAX_RANDOM_NUMBER,
+} from "./gameConstants.js";
+
+class Computer {
+ #solution;
+
+ seeSolution() {
+ return this.#solution;
+ }
+
+ makeSolution() {
+ const computer = [];
+ while (computer.length < VALID_INPUT_LENGTH) {
+ const number = Random.pickNumberInRange(
+ MIN_RANDOM_NUMBER,
+ MAX_RANDOM_NUMBER
+ );
+ if (!computer.includes(number)) {
+ computer.push(number);
+ }
+ }
+ this.#solution = computer;
+ }
+
+ assessUserInput(input) {
+ let strike = 0;
+ let ball = 0;
+ const userInput = input.split("").map(Number);
+ userInput.forEach((item, index) => {
+ if (
+ this.#solution.indexOf(item) === index &&
+ this.#solution.includes(item)
+ )
+ strike += 1;
+ else if (
+ this.#solution.indexOf(item) !== index &&
+ this.#solution.includes(item)
+ )
+ ball += 1;
+ });
+ return { strike, ball };
+ }
+}
+
+export default Computer; | JavaScript | ์ด๋ค ๊ตฌ๋ฌธ์๋ ์ธ๋ฏธ์ฝ๋ก ์ด ์๊ณ , ์ด๋ค ๊ตฌ๋ฌธ์๋ ์ธ๋ฏธ์ฝ๋ก ์ด ์์ง ์๋ค์.
๋ ์ค ํ๋๋ง ํ์๋ ๊ฑธ ์ถ์ฒ๋๋ฆฌ๊ณ , ๊ฐ์ ํ๊ณ ์ถ๋ค๋ฉด prettier๋ฑ์ ์ด์ฉํด๋ณด์ธ์. |
@@ -0,0 +1,49 @@
+import { Random } from "@woowacourse/mission-utils";
+import {
+ VALID_INPUT_LENGTH,
+ MIN_RANDOM_NUMBER,
+ MAX_RANDOM_NUMBER,
+} from "./gameConstants.js";
+
+class Computer {
+ #solution;
+
+ seeSolution() {
+ return this.#solution;
+ }
+
+ makeSolution() {
+ const computer = [];
+ while (computer.length < VALID_INPUT_LENGTH) {
+ const number = Random.pickNumberInRange(
+ MIN_RANDOM_NUMBER,
+ MAX_RANDOM_NUMBER
+ );
+ if (!computer.includes(number)) {
+ computer.push(number);
+ }
+ }
+ this.#solution = computer;
+ }
+
+ assessUserInput(input) {
+ let strike = 0;
+ let ball = 0;
+ const userInput = input.split("").map(Number);
+ userInput.forEach((item, index) => {
+ if (
+ this.#solution.indexOf(item) === index &&
+ this.#solution.includes(item)
+ )
+ strike += 1;
+ else if (
+ this.#solution.indexOf(item) !== index &&
+ this.#solution.includes(item)
+ )
+ ball += 1;
+ });
+ return { strike, ball };
+ }
+}
+
+export default Computer; | JavaScript | 1. ์ด๋ ๊ฒ๋ ๋ฉ๋๋ค.
```suggestion
const userInput = input.split("").map(Number);
```
2. ๋ฐฐ์ด์ด๋ฉด.. s๊ฐ ๋ถ์ผ๋ฉด ์ข์ง ์์๊น์? |
@@ -0,0 +1,49 @@
+import { Random } from "@woowacourse/mission-utils";
+import {
+ VALID_INPUT_LENGTH,
+ MIN_RANDOM_NUMBER,
+ MAX_RANDOM_NUMBER,
+} from "./gameConstants.js";
+
+class Computer {
+ #solution;
+
+ seeSolution() {
+ return this.#solution;
+ }
+
+ makeSolution() {
+ const computer = [];
+ while (computer.length < VALID_INPUT_LENGTH) {
+ const number = Random.pickNumberInRange(
+ MIN_RANDOM_NUMBER,
+ MAX_RANDOM_NUMBER
+ );
+ if (!computer.includes(number)) {
+ computer.push(number);
+ }
+ }
+ this.#solution = computer;
+ }
+
+ assessUserInput(input) {
+ let strike = 0;
+ let ball = 0;
+ const userInput = input.split("").map(Number);
+ userInput.forEach((item, index) => {
+ if (
+ this.#solution.indexOf(item) === index &&
+ this.#solution.includes(item)
+ )
+ strike += 1;
+ else if (
+ this.#solution.indexOf(item) !== index &&
+ this.#solution.includes(item)
+ )
+ ball += 1;
+ });
+ return { strike, ball };
+ }
+}
+
+export default Computer; | JavaScript | reduce๋ฅผ ์จ์๋ ๊ตฌํํ ์ ์๊ฒ ๋ค์
```js
const strikeAndBall = userInput.reduce((acc, cur) => {
if ((this.#solution.indexOf(item) === index) && this.#solution.includes(item)) return { ...acc, strike: acc.strike + 1 }
if ((this.#solution.indexOf(item) !== index) && this.#solution.includes(item)) return { ...acc, ball:acc.ball + 1}
return acc;
}, { strike: 0, ball: 0})
``` |
@@ -0,0 +1,15 @@
+{
+ "arrowParens": "always",
+ "bracketSpacing": true,
+ "jsxBracketSameLine": false,
+ "jsxSingleQuote": false,
+ "printWidth": 80,
+ "proseWrap": "always",
+ "quoteProps": "as-needed",
+ "semi": true,
+ "singleQuote": false,
+ "tabWidth": 2,
+ "trailingComma": "es5",
+ "useTabs": false,
+ "endOfLine": "auto"
+}
\ No newline at end of file | Unknown | ์ฝ๋๋ฅผ ๋ณด๋ฉด prettier๊ฐ ์ ์ฉ๋์ด์์ง ์์๋ฐ, ํ์ธํ๋ฒ ํด๋ณด์ธ์ฉ |
@@ -0,0 +1,49 @@
+import { Random } from "@woowacourse/mission-utils";
+import {
+ VALID_INPUT_LENGTH,
+ MIN_RANDOM_NUMBER,
+ MAX_RANDOM_NUMBER,
+} from "./gameConstants.js";
+
+class Computer {
+ #solution;
+
+ seeSolution() {
+ return this.#solution;
+ }
+
+ makeSolution() {
+ const computer = [];
+ while (computer.length < VALID_INPUT_LENGTH) {
+ const number = Random.pickNumberInRange(
+ MIN_RANDOM_NUMBER,
+ MAX_RANDOM_NUMBER
+ );
+ if (!computer.includes(number)) {
+ computer.push(number);
+ }
+ }
+ this.#solution = computer;
+ }
+
+ assessUserInput(input) {
+ let strike = 0;
+ let ball = 0;
+ const userInput = input.split("").map(Number);
+ userInput.forEach((item, index) => {
+ if (
+ this.#solution.indexOf(item) === index &&
+ this.#solution.includes(item)
+ )
+ strike += 1;
+ else if (
+ this.#solution.indexOf(item) !== index &&
+ this.#solution.includes(item)
+ )
+ ball += 1;
+ });
+ return { strike, ball };
+ }
+}
+
+export default Computer; | JavaScript | ์ด๊ฑธ ๋ฆฌํดํ๋ ์ด์ ๊ฐ ๋ญ๊ฐ์ ? |
@@ -1,5 +1,62 @@
+import { Console } from "@woowacourse/mission-utils";
+import User from "./User.js";
+import Computer from "./Computer.js";
+import Validator from "./Validator.js";
+import GameMessage from "./GameMessage.js";
+import { RETRY_RESPONSE, FULL_STRIKE } from "./gameConstants.js";
+
class App {
- async play() {}
+ constructor() {
+ this.user = new User();
+ this.computer = new Computer();
+ }
+
+ async play() {
+ this.computer.makeSolution();
+ Console.print(GameMessage.START_MESSAGE);
+ await this.mainLogic();
+ }
+
+ async mainLogic() {
+ await this.setUserInput();
+ this.printStrikeBall();
+ if (
+ this.computer.assessUserInput(this.user.getNumber()).strike !==
+ FULL_STRIKE
+ )
+ await this.mainLogic();
+ else {
+ const replayResponse = await Console.readLineAsync(
+ "๊ฒ์์ ์๋ก ์์ํ๋ ค๋ฉด 1, ์ข
๋ฃํ๋ ค๋ฉด 2๋ฅผ ์
๋ ฅํ์ธ์."
+ );
+ if (parseInt(replayResponse, 10) === RETRY_RESPONSE) {
+ this.computer.makeSolution();
+ this.mainLogic();
+ }
+ }
+ }
+
+ async setUserInput() {
+ const input = await Console.readLineAsync("์ซ์๋ฅผ ์
๋ ฅํด์ฃผ์ธ์ : ");
+ if (Validator.isValidInput(input)) {
+ this.user.setNumber(input);
+ }
+ }
+
+ printStrikeBall() {
+ const { strike, ball } = this.computer.assessUserInput(
+ this.user.getNumber()
+ );
+ if (strike === 0 && ball === 0) {
+ Console.print(GameMessage.NOTHING_MESSAGE);
+ } else if (strike > 0 && ball > 0) {
+ Console.print(`${strike}๋ณผ ${ball}์คํธ๋ผ์ดํฌ`);
+ } else if (strike === FULL_STRIKE) {
+ Console.print(GameMessage.SOLVED_MESSAGE);
+ } else {
+ Console.print(`${strike}์คํธ๋ผ์ดํฌ ${ball}๋ณผ`);
+ }
+ }
}
export default App; | JavaScript | indent๊ฐ.. |
@@ -1,5 +1,62 @@
+import { Console } from "@woowacourse/mission-utils";
+import User from "./User.js";
+import Computer from "./Computer.js";
+import Validator from "./Validator.js";
+import GameMessage from "./GameMessage.js";
+import { RETRY_RESPONSE, FULL_STRIKE } from "./gameConstants.js";
+
class App {
- async play() {}
+ constructor() {
+ this.user = new User();
+ this.computer = new Computer();
+ }
+
+ async play() {
+ this.computer.makeSolution();
+ Console.print(GameMessage.START_MESSAGE);
+ await this.mainLogic();
+ }
+
+ async mainLogic() {
+ await this.setUserInput();
+ this.printStrikeBall();
+ if (
+ this.computer.assessUserInput(this.user.getNumber()).strike !==
+ FULL_STRIKE
+ )
+ await this.mainLogic();
+ else {
+ const replayResponse = await Console.readLineAsync(
+ "๊ฒ์์ ์๋ก ์์ํ๋ ค๋ฉด 1, ์ข
๋ฃํ๋ ค๋ฉด 2๋ฅผ ์
๋ ฅํ์ธ์."
+ );
+ if (parseInt(replayResponse, 10) === RETRY_RESPONSE) {
+ this.computer.makeSolution();
+ this.mainLogic();
+ }
+ }
+ }
+
+ async setUserInput() {
+ const input = await Console.readLineAsync("์ซ์๋ฅผ ์
๋ ฅํด์ฃผ์ธ์ : ");
+ if (Validator.isValidInput(input)) {
+ this.user.setNumber(input);
+ }
+ }
+
+ printStrikeBall() {
+ const { strike, ball } = this.computer.assessUserInput(
+ this.user.getNumber()
+ );
+ if (strike === 0 && ball === 0) {
+ Console.print(GameMessage.NOTHING_MESSAGE);
+ } else if (strike > 0 && ball > 0) {
+ Console.print(`${strike}๋ณผ ${ball}์คํธ๋ผ์ดํฌ`);
+ } else if (strike === FULL_STRIKE) {
+ Console.print(GameMessage.SOLVED_MESSAGE);
+ } else {
+ Console.print(`${strike}์คํธ๋ผ์ดํฌ ${ball}๋ณผ`);
+ }
+ }
}
export default App; | JavaScript | ๋งค์ง๋๋ฒ๊ฐ ์ด์์ด์๋ค์ฉ |
@@ -1,5 +1,62 @@
+import { Console } from "@woowacourse/mission-utils";
+import User from "./User.js";
+import Computer from "./Computer.js";
+import Validator from "./Validator.js";
+import GameMessage from "./GameMessage.js";
+import { RETRY_RESPONSE, FULL_STRIKE } from "./gameConstants.js";
+
class App {
- async play() {}
+ constructor() {
+ this.user = new User();
+ this.computer = new Computer();
+ }
+
+ async play() {
+ this.computer.makeSolution();
+ Console.print(GameMessage.START_MESSAGE);
+ await this.mainLogic();
+ }
+
+ async mainLogic() {
+ await this.setUserInput();
+ this.printStrikeBall();
+ if (
+ this.computer.assessUserInput(this.user.getNumber()).strike !==
+ FULL_STRIKE
+ )
+ await this.mainLogic();
+ else {
+ const replayResponse = await Console.readLineAsync(
+ "๊ฒ์์ ์๋ก ์์ํ๋ ค๋ฉด 1, ์ข
๋ฃํ๋ ค๋ฉด 2๋ฅผ ์
๋ ฅํ์ธ์."
+ );
+ if (parseInt(replayResponse, 10) === RETRY_RESPONSE) {
+ this.computer.makeSolution();
+ this.mainLogic();
+ }
+ }
+ }
+
+ async setUserInput() {
+ const input = await Console.readLineAsync("์ซ์๋ฅผ ์
๋ ฅํด์ฃผ์ธ์ : ");
+ if (Validator.isValidInput(input)) {
+ this.user.setNumber(input);
+ }
+ }
+
+ printStrikeBall() {
+ const { strike, ball } = this.computer.assessUserInput(
+ this.user.getNumber()
+ );
+ if (strike === 0 && ball === 0) {
+ Console.print(GameMessage.NOTHING_MESSAGE);
+ } else if (strike > 0 && ball > 0) {
+ Console.print(`${strike}๋ณผ ${ball}์คํธ๋ผ์ดํฌ`);
+ } else if (strike === FULL_STRIKE) {
+ Console.print(GameMessage.SOLVED_MESSAGE);
+ } else {
+ Console.print(`${strike}์คํธ๋ผ์ดํฌ ${ball}๋ณผ`);
+ }
+ }
}
export default App; | JavaScript | ์ด๋ ๊ฒ eslint ๊ท์น์ ๋ฌด์ํ ๊ฑฐ๋ฉด eslint๋ฅผ ์ ์ฌ์ฉํ์๋์? |
@@ -1,20 +1,36 @@
package model;
+import java.util.ArrayList;
import java.util.List;
public class Lotto {
- private List<String> lottoNumbers;
+ private List<LottoNo> lottoNumbers;
- public Lotto(List<String> lottoNumbers) {
+ public Lotto(List<LottoNo> lottoNumbers) {
this.lottoNumbers = lottoNumbers;
}
- public int getCorrectNumberCount(List<String> winningNumber) {
- return (int) winningNumber.stream().filter((x) -> lottoNumbers.contains(x)).count();
+ public Lotto(String[] lottoNumbers) {
+ this.lottoNumbers = new ArrayList<>();
+ for (int i = 0; i < lottoNumbers.length; i++)
+ this.lottoNumbers.add(new LottoNo(Integer.parseInt(lottoNumbers[i])));
}
public String showLotto() {
- return lottoNumbers.toString();
+ List<String> lotto = new ArrayList<>();
+
+ for (LottoNo lottoNo : lottoNumbers)
+ lotto.add(lottoNo.getStringNumber());
+
+ return lotto.toString();
+ }
+
+ public int getCorrectCount(List<String> winningNumbers) {
+ return (int) lottoNumbers.stream().filter((x) -> winningNumbers.contains(x.getStringNumber())).count();
+ }
+
+ public boolean isContain(String stringNumber) {
+ return (int)lottoNumbers.stream().filter(x -> x.getStringNumber().equals(stringNumber)).count() != 0;
}
} | Java | ๋ก๋ ๋ฒํธ๋ฅผ Set ์ผ๋ก ๊ตฌํํ๋ ๊ฒ๊ณผ List ๋ก ๊ตฌํํ๋ ๊ฒ์ ๋น๊ตํด ๋ณด์์ ๋ ์ด๋ค ์ฅ๋จ์ ์ด ์์๊น์? ์ฌ๊ธฐ์๋ ์ด๋ค ์๋ฃ๊ตฌ์กฐ๊ฐ ์ด์ธ๋ฆด๊น์? |
@@ -1,20 +1,36 @@
package model;
+import java.util.ArrayList;
import java.util.List;
public class Lotto {
- private List<String> lottoNumbers;
+ private List<LottoNo> lottoNumbers;
- public Lotto(List<String> lottoNumbers) {
+ public Lotto(List<LottoNo> lottoNumbers) {
this.lottoNumbers = lottoNumbers;
}
- public int getCorrectNumberCount(List<String> winningNumber) {
- return (int) winningNumber.stream().filter((x) -> lottoNumbers.contains(x)).count();
+ public Lotto(String[] lottoNumbers) {
+ this.lottoNumbers = new ArrayList<>();
+ for (int i = 0; i < lottoNumbers.length; i++)
+ this.lottoNumbers.add(new LottoNo(Integer.parseInt(lottoNumbers[i])));
}
public String showLotto() {
- return lottoNumbers.toString();
+ List<String> lotto = new ArrayList<>();
+
+ for (LottoNo lottoNo : lottoNumbers)
+ lotto.add(lottoNo.getStringNumber());
+
+ return lotto.toString();
+ }
+
+ public int getCorrectCount(List<String> winningNumbers) {
+ return (int) lottoNumbers.stream().filter((x) -> winningNumbers.contains(x.getStringNumber())).count();
+ }
+
+ public boolean isContain(String stringNumber) {
+ return (int)lottoNumbers.stream().filter(x -> x.getStringNumber().equals(stringNumber)).count() != 0;
}
} | Java | ํ์ค์ด๋๋ผ๋ ๊ดํธ๋ฅผ ๋ถ์ฌ์ฃผ๋๊ฑธ ์ปจ๋ฒค์
์ผ๋ก ํฉ์๋ค.
์ด๊ฒ์ด ๊ฐ๊ฒฐํ๋๋ผ๋ ์ฝ๋ ์ฌ๋ ์
์ฅ์ผ๋ก ์ฝ๋๋ฅผ ๋ณด๋ฉด
๋น์ฐํ ์์ด์ผํ ๊ณณ์ ๋ฌด์ธ๊ฐ๊ฐ ๋น ์ง๊ฒ ๋๋ฉด ๊ฐ๋
์ฑ์ด ์ ํ๋ฉ๋๋ค. (์ฑ
์ฝ์ ๋์ ๋น์ท)
๊ทธ๋ฆฌ๊ณ ์์ฑ์์์ ๋ญ๊ฐ ๋ง์ ์ผ์ ํด์ฃผ๋๊ฒ ์์ฝ๋ค์ |
@@ -1,20 +1,36 @@
package model;
+import java.util.ArrayList;
import java.util.List;
public class Lotto {
- private List<String> lottoNumbers;
+ private List<LottoNo> lottoNumbers;
- public Lotto(List<String> lottoNumbers) {
+ public Lotto(List<LottoNo> lottoNumbers) {
this.lottoNumbers = lottoNumbers;
}
- public int getCorrectNumberCount(List<String> winningNumber) {
- return (int) winningNumber.stream().filter((x) -> lottoNumbers.contains(x)).count();
+ public Lotto(String[] lottoNumbers) {
+ this.lottoNumbers = new ArrayList<>();
+ for (int i = 0; i < lottoNumbers.length; i++)
+ this.lottoNumbers.add(new LottoNo(Integer.parseInt(lottoNumbers[i])));
}
public String showLotto() {
- return lottoNumbers.toString();
+ List<String> lotto = new ArrayList<>();
+
+ for (LottoNo lottoNo : lottoNumbers)
+ lotto.add(lottoNo.getStringNumber());
+
+ return lotto.toString();
+ }
+
+ public int getCorrectCount(List<String> winningNumbers) {
+ return (int) lottoNumbers.stream().filter((x) -> winningNumbers.contains(x.getStringNumber())).count();
+ }
+
+ public boolean isContain(String stringNumber) {
+ return (int)lottoNumbers.stream().filter(x -> x.getStringNumber().equals(stringNumber)).count() != 0;
}
} | Java | boolean์ int ๋ก ๋ณํํด์ฃผ๋ ์ด์ ๋ ๋ญ๊ฐ์? |
@@ -1,20 +1,36 @@
package model;
+import java.util.ArrayList;
import java.util.List;
public class Lotto {
- private List<String> lottoNumbers;
+ private List<LottoNo> lottoNumbers;
- public Lotto(List<String> lottoNumbers) {
+ public Lotto(List<LottoNo> lottoNumbers) {
this.lottoNumbers = lottoNumbers;
}
- public int getCorrectNumberCount(List<String> winningNumber) {
- return (int) winningNumber.stream().filter((x) -> lottoNumbers.contains(x)).count();
+ public Lotto(String[] lottoNumbers) {
+ this.lottoNumbers = new ArrayList<>();
+ for (int i = 0; i < lottoNumbers.length; i++)
+ this.lottoNumbers.add(new LottoNo(Integer.parseInt(lottoNumbers[i])));
}
public String showLotto() {
- return lottoNumbers.toString();
+ List<String> lotto = new ArrayList<>();
+
+ for (LottoNo lottoNo : lottoNumbers)
+ lotto.add(lottoNo.getStringNumber());
+
+ return lotto.toString();
+ }
+
+ public int getCorrectCount(List<String> winningNumbers) {
+ return (int) lottoNumbers.stream().filter((x) -> winningNumbers.contains(x.getStringNumber())).count();
+ }
+
+ public boolean isContain(String stringNumber) {
+ return (int)lottoNumbers.stream().filter(x -> x.getStringNumber().equals(stringNumber)).count() != 0;
}
} | Java | ์ด ๋ถ๋ถ ์ข ๋ ๊ฐ์ ํด๋ณด์ธ์ |
@@ -1,20 +1,36 @@
package model;
+import java.util.ArrayList;
import java.util.List;
public class Lotto {
- private List<String> lottoNumbers;
+ private List<LottoNo> lottoNumbers;
- public Lotto(List<String> lottoNumbers) {
+ public Lotto(List<LottoNo> lottoNumbers) {
this.lottoNumbers = lottoNumbers;
}
- public int getCorrectNumberCount(List<String> winningNumber) {
- return (int) winningNumber.stream().filter((x) -> lottoNumbers.contains(x)).count();
+ public Lotto(String[] lottoNumbers) {
+ this.lottoNumbers = new ArrayList<>();
+ for (int i = 0; i < lottoNumbers.length; i++)
+ this.lottoNumbers.add(new LottoNo(Integer.parseInt(lottoNumbers[i])));
}
public String showLotto() {
- return lottoNumbers.toString();
+ List<String> lotto = new ArrayList<>();
+
+ for (LottoNo lottoNo : lottoNumbers)
+ lotto.add(lottoNo.getStringNumber());
+
+ return lotto.toString();
+ }
+
+ public int getCorrectCount(List<String> winningNumbers) {
+ return (int) lottoNumbers.stream().filter((x) -> winningNumbers.contains(x.getStringNumber())).count();
+ }
+
+ public boolean isContain(String stringNumber) {
+ return (int)lottoNumbers.stream().filter(x -> x.getStringNumber().equals(stringNumber)).count() != 0;
}
} | Java | x ๋ฅผ ์ข ๋ ์๋ฏธ์๋ ๋ณ์์ด๋ฆ์ผ๋ก ์ง์์ผ๋ฉด ์ข์์ ๊ฒ ๊ฐ์ต๋๋ค.
๊ทธ๋ฆฌ๊ณ ๋ฉ์๋ ์ฒด์ด๋ ๋ฐฉ์์์๋ ๊ธธ์ด๊ฐ ๊ธธ์ด์ง๋ฉด IDE์์ ํ๋์ ํ์ธํ๊ธฐ ํ๋๋๊น
๊ฐ๋
์ฑ์ ์ํด ์ํฐ๋ก ๋ผ์ธ์ ๋ฆฌ๋ฅผ ์ด๋์ ๋ ํด์ฃผ๋ ๊ฒ์ด ์ข์ต๋๋ค.
์ด๋ฅผ ์ํ ์ปจ๋ฒค์
๋ intellij code style ์์ ์๋์ ๋ ฌ ์ค์ ํ ์ ์๊ธด ํฉ๋๋ค(์ ๋ ์ฌ์ฉ์ค) |
@@ -1,10 +1,8 @@
package model;
-import util.ListGenerator;
import util.SplitGenerator;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@@ -13,43 +11,44 @@ public class LottoMachine {
private static int LOTTO_NUMBER_RANGE = 45;
private static int LOTTO_NUMBER_COUNT = 6;
private static int LOTTO_PRICE = 1000;
- List<Lotto> lottos = new ArrayList<>();
- public List<String> buyLotto(int totalLottoPrice) {
- for (int i = 0; i < getLottoCount(totalLottoPrice); i++)
- lottos.add(new Lotto(getRandomNumbers(LOTTO_NUMBER_RANGE)));
- return showLottoHistory();
+ private int tryCount = 0;
+
+ public Lotto getAutoLotto() {
+ decreaseCount();
+ return new Lotto(getRandomNumbers(getNumbersInRange(LOTTO_NUMBER_RANGE)));
}
- private int getLottoCount(int totalPrice) {
- return totalPrice / LOTTO_PRICE;
+ public void inputMoney(int money) {
+ tryCount += money / LOTTO_PRICE;
}
- private List<String> getRandomNumbers(int range) {
- List<String> numbersInRange = ListGenerator.getNumbersInRange(range);
- Collections.shuffle(numbersInRange);
- return numbersInRange.subList(0, LOTTO_NUMBER_COUNT);
+ public boolean canLotto() {
+ return tryCount > 0;
}
- public int[] getStatistic(String winningNumber) {
- return createStatistic(toStringList(winningNumber));
+ private void decreaseCount() {
+ if (canLotto() == false)
+ throw new RuntimeException("๋ ๋ฃ์ด!!");
+ tryCount--;
}
- private List<String> toStringList(String winningNumber) {
- return Arrays.asList(SplitGenerator.splitWithSign(winningNumber, ", "));
+ private List<LottoNo> getNumbersInRange(int range) {
+ List<LottoNo> numbersInRange = new ArrayList<>();
+
+ for (int i = 1; i <= range; i++)
+ numbersInRange.add(new LottoNo(i));
+
+ return numbersInRange;
}
- private int[] createStatistic(List<String> winningNumber) {
- int[] statistic = new int[LOTTO_NUMBER_COUNT + 1];
- for (Lotto lotto : lottos)
- statistic[lotto.getCorrectNumberCount(winningNumber)]++;
- return statistic;
+ private List<LottoNo> getRandomNumbers(List<LottoNo> numbersInRange) {
+ Collections.shuffle(numbersInRange);
+ return numbersInRange.subList(0, LOTTO_NUMBER_COUNT);
}
- private List<String> showLottoHistory() {
- List<String> lottoHistory = new ArrayList<>();
- for (Lotto lotto : lottos)
- lottoHistory.add(lotto.showLotto());
- return lottoHistory;
+ public Lotto getDirectLotto(String numbers) {
+ decreaseCount();
+ return new Lotto(SplitGenerator.splitWithSign(numbers, ", "));
}
} | Java | getter ์ ํท๊ฐ๋ฆฌ๋ฏ๋ก calculateRandomNumbers ์ฒ๋ผ ๋ค๋ฅธ ๋จ์ด๋ฅผ ํ์ฉํด๋ณด์๋๊ฑธ ์ถ์ฒ |
@@ -1,20 +1,36 @@
package model;
+import java.util.ArrayList;
import java.util.List;
public class Lotto {
- private List<String> lottoNumbers;
+ private List<LottoNo> lottoNumbers;
- public Lotto(List<String> lottoNumbers) {
+ public Lotto(List<LottoNo> lottoNumbers) {
this.lottoNumbers = lottoNumbers;
}
- public int getCorrectNumberCount(List<String> winningNumber) {
- return (int) winningNumber.stream().filter((x) -> lottoNumbers.contains(x)).count();
+ public Lotto(String[] lottoNumbers) {
+ this.lottoNumbers = new ArrayList<>();
+ for (int i = 0; i < lottoNumbers.length; i++)
+ this.lottoNumbers.add(new LottoNo(Integer.parseInt(lottoNumbers[i])));
}
public String showLotto() {
- return lottoNumbers.toString();
+ List<String> lotto = new ArrayList<>();
+
+ for (LottoNo lottoNo : lottoNumbers)
+ lotto.add(lottoNo.getStringNumber());
+
+ return lotto.toString();
+ }
+
+ public int getCorrectCount(List<String> winningNumbers) {
+ return (int) lottoNumbers.stream().filter((x) -> winningNumbers.contains(x.getStringNumber())).count();
+ }
+
+ public boolean isContain(String stringNumber) {
+ return (int)lottoNumbers.stream().filter(x -> x.getStringNumber().equals(stringNumber)).count() != 0;
}
} | Java | int ๊ฐ์ผ๋ก ๋ฐํํ๋ ๋ฉ์๋๋ก ์ฒ์ ๊ตฌํํ์๋๋ฐ ๋ฆฌํฉํ ๋ง ๊ณผ์ ์์ boolean ํ์
์ผ๋ก ๋ฐ๊ฟ๋ ๊น๋นกํ ๊ฒ๊ฐ๋ค์.. ์ค์ํ์ง ์๋๋ก ์ฃผ์ํ๊ฒ ์ต๋๋ค |
@@ -1,20 +1,36 @@
package model;
+import java.util.ArrayList;
import java.util.List;
public class Lotto {
- private List<String> lottoNumbers;
+ private List<LottoNo> lottoNumbers;
- public Lotto(List<String> lottoNumbers) {
+ public Lotto(List<LottoNo> lottoNumbers) {
this.lottoNumbers = lottoNumbers;
}
- public int getCorrectNumberCount(List<String> winningNumber) {
- return (int) winningNumber.stream().filter((x) -> lottoNumbers.contains(x)).count();
+ public Lotto(String[] lottoNumbers) {
+ this.lottoNumbers = new ArrayList<>();
+ for (int i = 0; i < lottoNumbers.length; i++)
+ this.lottoNumbers.add(new LottoNo(Integer.parseInt(lottoNumbers[i])));
}
public String showLotto() {
- return lottoNumbers.toString();
+ List<String> lotto = new ArrayList<>();
+
+ for (LottoNo lottoNo : lottoNumbers)
+ lotto.add(lottoNo.getStringNumber());
+
+ return lotto.toString();
+ }
+
+ public int getCorrectCount(List<String> winningNumbers) {
+ return (int) lottoNumbers.stream().filter((x) -> winningNumbers.contains(x.getStringNumber())).count();
+ }
+
+ public boolean isContain(String stringNumber) {
+ return (int)lottoNumbers.stream().filter(x -> x.getStringNumber().equals(stringNumber)).count() != 0;
}
} | Java | set๊ณผ List์ ๊ฐ์ฅ ํฐ ์ฐจ์ด์ ์ ์ค๋ณต์ ํ์ฉํ๋์ง ์ํ๋์ง๋ก ์๊ณ ์์ต๋๋ค.
์ด๋ถ๋ถ์์ set์ ํ์ฉํ์๋ ๋ก๋ ๋ฒํธ๊ฐ 6๊ฐ๊ฐ ๋ ๋๊น์ง ๋๋ค ์ซ์๋ฅผ ๋ฐ๋ ๋ฐฉ๋ฒ์ด ์๊ฒ ๋ค์ ์๋ํด๋ณด๊ฒ ์ต๋๋ค. |
@@ -1,28 +1,33 @@
package com.emotionalcart.product.application;
-import com.emotionalcart.core.feature.product.*;
-import com.emotionalcart.core.feature.provider.Provider;
-import com.emotionalcart.core.feature.review.Review;
import com.emotionalcart.core.exception.ErrorCode;
import com.emotionalcart.core.exception.ProductException;
import com.emotionalcart.core.feature.category.Category;
-import com.emotionalcart.product.domain.ProductDataProvider;
-import com.emotionalcart.product.domain.dto.ProductDetail;
-import com.emotionalcart.product.domain.support.*;
-import com.emotionalcart.product.domain.CategoryDataProvider;
-import com.emotionalcart.product.domain.ProviderDataProvider;
import com.emotionalcart.core.feature.product.Product;
import com.emotionalcart.core.feature.product.ProductOption;
import com.emotionalcart.core.feature.product.ProductOptionDetail;
-
+import com.emotionalcart.core.feature.provider.Provider;
+import com.emotionalcart.core.feature.review.Review;
+import com.emotionalcart.core.feature.review.ReviewImage;
+import com.emotionalcart.product.domain.CategoryDataProvider;
+import com.emotionalcart.product.domain.ProductDataProvider;
+import com.emotionalcart.product.domain.ProviderDataProvider;
+import com.emotionalcart.product.domain.dto.ProductDetail;
+import com.emotionalcart.product.domain.support.*;
import com.emotionalcart.product.presentation.dto.*;
+import com.emotionalcart.s3.S3Utils;
+import com.emotionalcart.s3.config.S3Constants;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
+import org.springframework.web.multipart.MultipartFile;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
import java.util.stream.Collectors;
@Service
@@ -32,9 +37,10 @@ public class ProductService {
private final ProductDataProvider productDataProvider;
private final CategoryDataProvider categoryDataProvider;
private final ProviderDataProvider providerDataProvider;
+ private final S3Utils s3Utils;
public Page<ReadProductReviews.Response> readProductReviews(@NotNull Long productId,
- ReadProductReviews.Request request) {
+ ReadProductReviews.Request request) {
productDataProvider.findProduct(productId);
Page<Review> reviews = productDataProvider.findAllReviews(productId, request.getPageable());
@@ -48,6 +54,46 @@ private ReviewImages findAllReviewImages(List<Review> reviews) {
return ReviewImages.from(productDataProvider.findAllReviewImages(from.ids()));
}
+ @Transactional
+ public CreateProductReview.Response createProductReview(@NotNull Long productId, CreateProductReview.Request request) {
+ Product product = productDataProvider.findProduct(productId);
+ productDataProvider.findProductReview(productId, "userId123"); // TODO ์ค์ userId ๋ฐ์
+ // TODO ์ ์ ๊ตฌ๋งค๋ด์ญ ํ์ธ
+ Review review = request.toReviewEntity(productId);
+ productDataProvider.saveProductReview(review);
+
+ List<ReviewImage> reviewImages = uploadAndCreateReviewImages(review.getId(), request.getReviewImages());
+ productDataProvider.saveProductReviewImages(reviewImages);
+
+ product.getReviewStatistic().updateStatistics(request.getRating());
+ return new CreateProductReview.Response(review.getId());
+ }
+
+ /**
+ * ๋ฆฌ๋ทฐ ์ด๋ฏธ์ง entity ์์ฑ ๋ฐ s3 ์ ์ฅ
+ */
+ private List<ReviewImage> uploadAndCreateReviewImages(Long reviewId, List<MultipartFile> files) {
+ if (files == null || files.isEmpty()) {
+ return List.of();
+ }
+
+ return files.stream().map(file -> {
+ try {
+ String fileUrl = s3Utils.uploadFile(S3Constants.REVIEW_DIRECTORY, reviewId.toString(), file);
+ return ReviewImage.of(
+ reviewId,
+ file.getOriginalFilename(),
+ fileUrl,
+ file.getContentType(),
+ file.getSize(),
+ files.indexOf(file) + 1
+ );
+ } catch (Exception e) {
+ throw new ProductException(ErrorCode.S3_UPLOAD_FAILED);
+ }
+ }).toList();
+ }
+
public Page<ReadProducts.Response> readProducts(ReadProducts.Request request) {
Page<Product> productPage = productDataProvider.findAllProducts(request.toProductSearch());
| Java | files.indexOf(file) + 1์ ํ์ผ์ด ๋ค์ด์จ ์์๋๋ก ํ๊ธฐ ์์๋ฅผ ๋งค๊ฒจ์ฃผ๋ ๊ฒ์ธ๊ฐ์?? |
@@ -1,28 +1,33 @@
package com.emotionalcart.product.application;
-import com.emotionalcart.core.feature.product.*;
-import com.emotionalcart.core.feature.provider.Provider;
-import com.emotionalcart.core.feature.review.Review;
import com.emotionalcart.core.exception.ErrorCode;
import com.emotionalcart.core.exception.ProductException;
import com.emotionalcart.core.feature.category.Category;
-import com.emotionalcart.product.domain.ProductDataProvider;
-import com.emotionalcart.product.domain.dto.ProductDetail;
-import com.emotionalcart.product.domain.support.*;
-import com.emotionalcart.product.domain.CategoryDataProvider;
-import com.emotionalcart.product.domain.ProviderDataProvider;
import com.emotionalcart.core.feature.product.Product;
import com.emotionalcart.core.feature.product.ProductOption;
import com.emotionalcart.core.feature.product.ProductOptionDetail;
-
+import com.emotionalcart.core.feature.provider.Provider;
+import com.emotionalcart.core.feature.review.Review;
+import com.emotionalcart.core.feature.review.ReviewImage;
+import com.emotionalcart.product.domain.CategoryDataProvider;
+import com.emotionalcart.product.domain.ProductDataProvider;
+import com.emotionalcart.product.domain.ProviderDataProvider;
+import com.emotionalcart.product.domain.dto.ProductDetail;
+import com.emotionalcart.product.domain.support.*;
import com.emotionalcart.product.presentation.dto.*;
+import com.emotionalcart.s3.S3Utils;
+import com.emotionalcart.s3.config.S3Constants;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
+import org.springframework.web.multipart.MultipartFile;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
import java.util.stream.Collectors;
@Service
@@ -32,9 +37,10 @@ public class ProductService {
private final ProductDataProvider productDataProvider;
private final CategoryDataProvider categoryDataProvider;
private final ProviderDataProvider providerDataProvider;
+ private final S3Utils s3Utils;
public Page<ReadProductReviews.Response> readProductReviews(@NotNull Long productId,
- ReadProductReviews.Request request) {
+ ReadProductReviews.Request request) {
productDataProvider.findProduct(productId);
Page<Review> reviews = productDataProvider.findAllReviews(productId, request.getPageable());
@@ -48,6 +54,46 @@ private ReviewImages findAllReviewImages(List<Review> reviews) {
return ReviewImages.from(productDataProvider.findAllReviewImages(from.ids()));
}
+ @Transactional
+ public CreateProductReview.Response createProductReview(@NotNull Long productId, CreateProductReview.Request request) {
+ Product product = productDataProvider.findProduct(productId);
+ productDataProvider.findProductReview(productId, "userId123"); // TODO ์ค์ userId ๋ฐ์
+ // TODO ์ ์ ๊ตฌ๋งค๋ด์ญ ํ์ธ
+ Review review = request.toReviewEntity(productId);
+ productDataProvider.saveProductReview(review);
+
+ List<ReviewImage> reviewImages = uploadAndCreateReviewImages(review.getId(), request.getReviewImages());
+ productDataProvider.saveProductReviewImages(reviewImages);
+
+ product.getReviewStatistic().updateStatistics(request.getRating());
+ return new CreateProductReview.Response(review.getId());
+ }
+
+ /**
+ * ๋ฆฌ๋ทฐ ์ด๋ฏธ์ง entity ์์ฑ ๋ฐ s3 ์ ์ฅ
+ */
+ private List<ReviewImage> uploadAndCreateReviewImages(Long reviewId, List<MultipartFile> files) {
+ if (files == null || files.isEmpty()) {
+ return List.of();
+ }
+
+ return files.stream().map(file -> {
+ try {
+ String fileUrl = s3Utils.uploadFile(S3Constants.REVIEW_DIRECTORY, reviewId.toString(), file);
+ return ReviewImage.of(
+ reviewId,
+ file.getOriginalFilename(),
+ fileUrl,
+ file.getContentType(),
+ file.getSize(),
+ files.indexOf(file) + 1
+ );
+ } catch (Exception e) {
+ throw new ProductException(ErrorCode.S3_UPLOAD_FAILED);
+ }
+ }).toList();
+ }
+
public Page<ReadProducts.Response> readProducts(ReadProducts.Request request) {
Page<Product> productPage = productDataProvider.findAllProducts(request.toProductSearch());
| Java | ๋ง์ต๋๋ค! |
@@ -1,5 +1,12 @@
+import EventController from "./controller/EventController.js";
+
class App {
- async run() {}
+ constructor() {
+ this.eventController = new EventController();
+ }
+ async run() {
+ await this.eventController.eventStart();
+ }
}
export default App; | JavaScript | App ์์ฒด๊ฐ Controller๋ผ๊ณ ์๊ฐํ๊ณ ๊ตฌํ์ ํ๋ ๋ฐฉ๋ฒ๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค |
@@ -0,0 +1,111 @@
+import { MENU, MESSAGE, ARRAY, CALENDAR, BENEFIT_AMOUNT, BADGE, BOUNDARY } from "../commons/constants.js";
+import Order from "./Order.js";
+import { getMenu, getMenuCount } from "../commons/utils.js";
+
+class Benefit {
+ #date;
+ #menu;
+ #order;
+ #benefitResult;
+
+ constructor(date, menu) {
+ this.#date = date;
+ this.#menu = menu;
+ this.#order = new Order(date, menu);
+ }
+
+ // ํํ ๋ด์ญ
+ benefitDetail() {
+ // benefitResult [ DDay | Weekday | Weekend | Special | Giveaway ]
+ this.#benefitResult = [0, 0, 0, 0, 0];
+
+ if (this.#isBenefit()) {
+ if (this.#isDDay()) this.#benefitResult[ARRAY.DDAY] = this.#applyDDay();
+ if (this.#isWeekday()) this.#benefitResult[ARRAY.WEEKDAY] = this.#applyWeekday();
+ if (this.#isWeekend()) this.#benefitResult[ARRAY.WEEKEND] = this.#applyWeekend();
+ if (this.#isSpecial()) this.#benefitResult[ARRAY.SPECIALDAY] = this.#applySpecial();
+ if (this.#isGiveaway()) this.#benefitResult[ARRAY.GIVEAWAY] = this.#applyGiveaway();
+ }
+
+ return this.#benefitResult;
+ }
+
+ // ์ด ํํ ๊ธ์ก
+ totalBenefit() {
+ let totalBenefit = 0;
+ this.#benefitResult.forEach((benefit) => {
+ totalBenefit += benefit;
+ });
+
+ return totalBenefit;
+ }
+
+ // ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก
+ expectedAmount() {
+ const totalDiscount = this.totalBenefit() - this.#benefitResult[ARRAY.GIVEAWAY];
+
+ return this.#order.getAllAmount() - totalDiscount;
+ }
+
+ // 12์ ์ด๋ฒคํธ ๋ฐฐ์ง
+ eventBadge() {
+ const totalBenefit = this.totalBenefit();
+
+ if (!this.#isBenefit()) return MESSAGE.NOTHING;
+ if (totalBenefit <= BOUNDARY.STAR_PRICE) return BADGE.STAR;
+ if (totalBenefit <= BOUNDARY.TREE_PRICE) return BADGE.TREE;
+
+ return BADGE.SANTA;
+ }
+
+ #isBenefit() {
+ return this.#order.getAllAmount() > BOUNDARY.BENEFIT_PRICE;
+ }
+
+ #isDDay() {
+ return this.#date <= BOUNDARY.DDAY_END;
+ }
+
+ #isWeekday() {
+ return CALENDAR.WEEKDAY.includes(this.#date);
+ }
+
+ #isWeekend() {
+ return CALENDAR.WEEKEND.includes(this.#date);
+ }
+
+ #isSpecial() {
+ return CALENDAR.SPECIAL.includes(this.#date);
+ }
+
+ #isGiveaway() {
+ return this.#order.getAllAmount() >= BOUNDARY.GIVEAWAY_PRICE;
+ }
+
+ #applyDDay() {
+ let discount = BENEFIT_AMOUNT.DDAY_START;
+ for (let day = 1; day < this.#date; day++) {
+ discount += BENEFIT_AMOUNT.DDAY_PLUS;
+ }
+ return discount;
+ }
+
+ #applyWeekday() {
+ const menuCount = getMenuCount(getMenu(MENU.DESSERT), this.#menu);
+ return menuCount * BENEFIT_AMOUNT.WEEKDAY;
+ }
+
+ #applyWeekend() {
+ const menuCount = getMenuCount(getMenu(MENU.MAIN), this.#menu);
+ return menuCount * BENEFIT_AMOUNT.WEEKEND;
+ }
+
+ #applySpecial() {
+ return BENEFIT_AMOUNT.SPECIALDAY;
+ }
+
+ #applyGiveaway() {
+ return BENEFIT_AMOUNT.GIVEAWAY;
+ }
+}
+export default Benefit; | JavaScript | benefitResult๋ฅผ Obejct๋ก ๊ตฌํํ๋ฉด ์ข ๋ ๊ฐ๋
์ฑ์ด ์ข์ง ์์๊น ์ถ์ต๋๋ค |
@@ -0,0 +1,88 @@
+import Benefit from "../src/model/Benefit.js";
+import { orderIntoArray } from "../src/commons/utils.js";
+
+describe("Benefit ํด๋์ค ํ
์คํธ(ํํ ์๋ ๊ฒฝ์ฐ)", () => {
+ //given
+ const date = "3";
+ const menu = orderIntoArray("ํฐ๋ณธ์คํ
์ดํฌ-1,๋ฐ๋นํ๋ฆฝ-1,์ด์ฝ์ผ์ดํฌ-2,์ ๋ก์ฝ๋ผ-1");
+ const benefit = new Benefit(date, menu);
+
+ test("Benefit Detail(ํํ ๋ด์ญ) ํ
์คํธ", () => {
+ // when
+ const result = benefit.benefitDetail();
+ // then
+ const expected = [1200, 4046, 0, 1000, 25000];
+
+ expect(result).toEqual(expected);
+ });
+
+ test("Total Beneift(์ด ํํ ๊ธ์ก) ํ
์คํธ", () => {
+ // when
+ const result = benefit.totalBenefit();
+ // then
+ const expected = 31246;
+
+ expect(result).toEqual(expected);
+ });
+
+ test("Expected Amount(์์ ๊ฒฐ์ ๊ธ์ก) ํ
์คํธ", () => {
+ // when
+ const result = benefit.expectedAmount();
+ // then
+ const expected = 135754;
+
+ expect(result).toEqual(expected);
+ });
+
+ test("Event Badge(์ด๋ฒคํธ ๋ฐฐ์ง) ํ
์คํธ", () => {
+ // when
+ const result = benefit.eventBadge();
+ // then
+ const expected = "์ฐํ";
+
+ expect(result).toEqual(expected);
+ });
+});
+
+describe("Benefit ํด๋์ค ํ
์คํธ(ํํ ์๋ ๊ฒฝ์ฐ)", () => {
+ //given
+ const date = "26";
+ const menu = orderIntoArray("ํํ์ค-1,์ ๋ก์ฝ๋ผ-1");
+ const benefit = new Benefit(date, menu);
+
+ test("Benefit Detail(ํํ ๋ด์ญ) ํ
์คํธ", () => {
+ // when
+ const result = benefit.benefitDetail();
+ // then
+ const expected = [0, 0, 0, 0, 0];
+
+ expect(result).toEqual(expected);
+ });
+
+ test("Total Beneift(์ด ํํ ๊ธ์ก) ํ
์คํธ", () => {
+ // when
+ const result = benefit.totalBenefit();
+ // then
+ const expected = 0;
+
+ expect(result).toEqual(expected);
+ });
+
+ test("Expected Amount(์์ ๊ฒฐ์ ๊ธ์ก) ํ
์คํธ", () => {
+ // when
+ const result = benefit.expectedAmount();
+ // then
+ const expected = 8500;
+
+ expect(result).toEqual(expected);
+ });
+
+ test("Event Badge(์ด๋ฒคํธ ๋ฐฐ์ง) ํ
์คํธ", () => {
+ // when
+ const result = benefit.eventBadge();
+ // then
+ const expected = "์์";
+
+ expect(result).toEqual(expected);
+ });
+}); | JavaScript | ํ
์คํธ๊ฐ ๋๋ฌด ํ์ ๋์ด ์๋๊ฒ ๊ฐ์ต๋๋ค test.each๋ฅผ ์ฌ์ฉํ์ฌ ์ข ๋ ๋ฒ์์ฑ ์๊ฒ ํ
์คํธ๋ฅผ ๊ตฌํํ๋ ๋ฐฉ๋ฒ์ด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค |
@@ -0,0 +1,63 @@
+import InputView from "../view/InputView.js";
+import OutputView from "../view/OutputView.js";
+import Order from "../model/Order.js";
+import Benefit from "../model/Benefit.js";
+import { print } from "../commons/utils.js";
+import { MENU } from "../commons/constants.js";
+
+class EventController {
+ #date;
+ #menu;
+
+ async eventStart() {
+ OutputView.printStart();
+
+ // ์ฃผ๋ฌธ ์ ๋ณด ์
๋ ฅ & ์ฃผ๋ฌธ ์ ๋ณด ์ถ๋ ฅ
+ await this.#getOrderInformation();
+ OutputView.printOrderInformation(this.#date, this.#menu);
+
+ // ์ฃผ๋ฌธ ํด๋์ค ์์ฑ & ์ด ์ฃผ๋ฌธ ๊ธ์ก ์ถ๋ ฅ
+ const order = new Order(this.#date, this.#menu);
+ OutputView.printAllAmount(order.getAllAmount());
+
+ // ํํ ํด๋์ค ์์ฑ & ํํ๊ณผ ๊ด๋ จ๋ ๋ฉ์ธ์ง ์ถ๋ ฅ
+ const benefit = new Benefit(this.#date, this.#menu);
+ this.#printBenefit(benefit);
+ }
+
+ async #getOrderInformation() {
+ await this.#getDate();
+ await this.#getMenu();
+ }
+
+ async #getDate() {
+ while (true) {
+ try {
+ this.#date = await InputView.inputDate();
+ break;
+ } catch (error) {
+ print(error);
+ }
+ }
+ }
+
+ async #getMenu() {
+ while (true) {
+ try {
+ this.#menu = await InputView.inputMenu();
+ break;
+ } catch (error) {
+ print(error);
+ }
+ }
+ }
+
+ #printBenefit(benefit) {
+ OutputView.printGiveaway(benefit.benefitDetail()); // <์ฆ์ ๋ฉ๋ด>
+ OutputView.printBenefitDetail(benefit.benefitDetail()); // <ํํ ๋ด์ญ>
+ OutputView.printTotalBenefit(benefit.totalBenefit()); // <์ด ํํ
๊ธ์ก>
+ OutputView.printExpectedAmount(benefit.expectedAmount()); // <ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก>
+ OutputView.printEventBadge(benefit.eventBadge()); // <12์ ์ด๋ฒคํธ ๋ฐฐ์ง>
+ }
+}
+export default EventController; | JavaScript | ๊ฐ๊ฐ์ ๋๋ ํ ๋ฆฌ์ index.js ๋ฅผ ์ถ๊ฐํ๊ณ , ๊ณตํต๋๊ฒ export ์ํค๋ฉด, import ๋ฅผ ๊ฐ๋จํ๊ฒ ํ ์ ์์ต๋๋ค!
*view/index.js*
```javascript
export {default as InputView.js} from './InputView.js'
export {default as OutputView.js} from './OutputView.js'
```
*EventController.js*
```javascript
import { InputView, OutputView } '../view/index.js'
``` |
@@ -0,0 +1,111 @@
+import { MENU, MESSAGE, ARRAY, CALENDAR, BENEFIT_AMOUNT, BADGE, BOUNDARY } from "../commons/constants.js";
+import Order from "./Order.js";
+import { getMenu, getMenuCount } from "../commons/utils.js";
+
+class Benefit {
+ #date;
+ #menu;
+ #order;
+ #benefitResult;
+
+ constructor(date, menu) {
+ this.#date = date;
+ this.#menu = menu;
+ this.#order = new Order(date, menu);
+ }
+
+ // ํํ ๋ด์ญ
+ benefitDetail() {
+ // benefitResult [ DDay | Weekday | Weekend | Special | Giveaway ]
+ this.#benefitResult = [0, 0, 0, 0, 0];
+
+ if (this.#isBenefit()) {
+ if (this.#isDDay()) this.#benefitResult[ARRAY.DDAY] = this.#applyDDay();
+ if (this.#isWeekday()) this.#benefitResult[ARRAY.WEEKDAY] = this.#applyWeekday();
+ if (this.#isWeekend()) this.#benefitResult[ARRAY.WEEKEND] = this.#applyWeekend();
+ if (this.#isSpecial()) this.#benefitResult[ARRAY.SPECIALDAY] = this.#applySpecial();
+ if (this.#isGiveaway()) this.#benefitResult[ARRAY.GIVEAWAY] = this.#applyGiveaway();
+ }
+
+ return this.#benefitResult;
+ }
+
+ // ์ด ํํ ๊ธ์ก
+ totalBenefit() {
+ let totalBenefit = 0;
+ this.#benefitResult.forEach((benefit) => {
+ totalBenefit += benefit;
+ });
+
+ return totalBenefit;
+ }
+
+ // ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก
+ expectedAmount() {
+ const totalDiscount = this.totalBenefit() - this.#benefitResult[ARRAY.GIVEAWAY];
+
+ return this.#order.getAllAmount() - totalDiscount;
+ }
+
+ // 12์ ์ด๋ฒคํธ ๋ฐฐ์ง
+ eventBadge() {
+ const totalBenefit = this.totalBenefit();
+
+ if (!this.#isBenefit()) return MESSAGE.NOTHING;
+ if (totalBenefit <= BOUNDARY.STAR_PRICE) return BADGE.STAR;
+ if (totalBenefit <= BOUNDARY.TREE_PRICE) return BADGE.TREE;
+
+ return BADGE.SANTA;
+ }
+
+ #isBenefit() {
+ return this.#order.getAllAmount() > BOUNDARY.BENEFIT_PRICE;
+ }
+
+ #isDDay() {
+ return this.#date <= BOUNDARY.DDAY_END;
+ }
+
+ #isWeekday() {
+ return CALENDAR.WEEKDAY.includes(this.#date);
+ }
+
+ #isWeekend() {
+ return CALENDAR.WEEKEND.includes(this.#date);
+ }
+
+ #isSpecial() {
+ return CALENDAR.SPECIAL.includes(this.#date);
+ }
+
+ #isGiveaway() {
+ return this.#order.getAllAmount() >= BOUNDARY.GIVEAWAY_PRICE;
+ }
+
+ #applyDDay() {
+ let discount = BENEFIT_AMOUNT.DDAY_START;
+ for (let day = 1; day < this.#date; day++) {
+ discount += BENEFIT_AMOUNT.DDAY_PLUS;
+ }
+ return discount;
+ }
+
+ #applyWeekday() {
+ const menuCount = getMenuCount(getMenu(MENU.DESSERT), this.#menu);
+ return menuCount * BENEFIT_AMOUNT.WEEKDAY;
+ }
+
+ #applyWeekend() {
+ const menuCount = getMenuCount(getMenu(MENU.MAIN), this.#menu);
+ return menuCount * BENEFIT_AMOUNT.WEEKEND;
+ }
+
+ #applySpecial() {
+ return BENEFIT_AMOUNT.SPECIALDAY;
+ }
+
+ #applyGiveaway() {
+ return BENEFIT_AMOUNT.GIVEAWAY;
+ }
+}
+export default Benefit; | JavaScript | ```javascript
this.#benefitResult = Array.from({length:5(ํํ์ ๊ธธ์ด๋ฅผ ๋ํ๋ด๋ ์์๋ก ์์ )}, () => 0)
```
์ ๊ฐ์ด ๋ฐ๊พธ๋ ๊ฒ์ ์ด๋จ๊น์? |
@@ -0,0 +1,111 @@
+import { MENU, MESSAGE, ARRAY, CALENDAR, BENEFIT_AMOUNT, BADGE, BOUNDARY } from "../commons/constants.js";
+import Order from "./Order.js";
+import { getMenu, getMenuCount } from "../commons/utils.js";
+
+class Benefit {
+ #date;
+ #menu;
+ #order;
+ #benefitResult;
+
+ constructor(date, menu) {
+ this.#date = date;
+ this.#menu = menu;
+ this.#order = new Order(date, menu);
+ }
+
+ // ํํ ๋ด์ญ
+ benefitDetail() {
+ // benefitResult [ DDay | Weekday | Weekend | Special | Giveaway ]
+ this.#benefitResult = [0, 0, 0, 0, 0];
+
+ if (this.#isBenefit()) {
+ if (this.#isDDay()) this.#benefitResult[ARRAY.DDAY] = this.#applyDDay();
+ if (this.#isWeekday()) this.#benefitResult[ARRAY.WEEKDAY] = this.#applyWeekday();
+ if (this.#isWeekend()) this.#benefitResult[ARRAY.WEEKEND] = this.#applyWeekend();
+ if (this.#isSpecial()) this.#benefitResult[ARRAY.SPECIALDAY] = this.#applySpecial();
+ if (this.#isGiveaway()) this.#benefitResult[ARRAY.GIVEAWAY] = this.#applyGiveaway();
+ }
+
+ return this.#benefitResult;
+ }
+
+ // ์ด ํํ ๊ธ์ก
+ totalBenefit() {
+ let totalBenefit = 0;
+ this.#benefitResult.forEach((benefit) => {
+ totalBenefit += benefit;
+ });
+
+ return totalBenefit;
+ }
+
+ // ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก
+ expectedAmount() {
+ const totalDiscount = this.totalBenefit() - this.#benefitResult[ARRAY.GIVEAWAY];
+
+ return this.#order.getAllAmount() - totalDiscount;
+ }
+
+ // 12์ ์ด๋ฒคํธ ๋ฐฐ์ง
+ eventBadge() {
+ const totalBenefit = this.totalBenefit();
+
+ if (!this.#isBenefit()) return MESSAGE.NOTHING;
+ if (totalBenefit <= BOUNDARY.STAR_PRICE) return BADGE.STAR;
+ if (totalBenefit <= BOUNDARY.TREE_PRICE) return BADGE.TREE;
+
+ return BADGE.SANTA;
+ }
+
+ #isBenefit() {
+ return this.#order.getAllAmount() > BOUNDARY.BENEFIT_PRICE;
+ }
+
+ #isDDay() {
+ return this.#date <= BOUNDARY.DDAY_END;
+ }
+
+ #isWeekday() {
+ return CALENDAR.WEEKDAY.includes(this.#date);
+ }
+
+ #isWeekend() {
+ return CALENDAR.WEEKEND.includes(this.#date);
+ }
+
+ #isSpecial() {
+ return CALENDAR.SPECIAL.includes(this.#date);
+ }
+
+ #isGiveaway() {
+ return this.#order.getAllAmount() >= BOUNDARY.GIVEAWAY_PRICE;
+ }
+
+ #applyDDay() {
+ let discount = BENEFIT_AMOUNT.DDAY_START;
+ for (let day = 1; day < this.#date; day++) {
+ discount += BENEFIT_AMOUNT.DDAY_PLUS;
+ }
+ return discount;
+ }
+
+ #applyWeekday() {
+ const menuCount = getMenuCount(getMenu(MENU.DESSERT), this.#menu);
+ return menuCount * BENEFIT_AMOUNT.WEEKDAY;
+ }
+
+ #applyWeekend() {
+ const menuCount = getMenuCount(getMenu(MENU.MAIN), this.#menu);
+ return menuCount * BENEFIT_AMOUNT.WEEKEND;
+ }
+
+ #applySpecial() {
+ return BENEFIT_AMOUNT.SPECIALDAY;
+ }
+
+ #applyGiveaway() {
+ return BENEFIT_AMOUNT.GIVEAWAY;
+ }
+}
+export default Benefit; | JavaScript | ํด๋์ค ๋ถ๋ฆฌ์ ๋๋ฌด ์ง์คํ๋๋ผ
ํํ์ ํ์ธํ๋ ํด๋์ค์ ํํ์ ์ ์ฉํ๋ ํด๋์ค๋ก ๋ถ๋ฆฌํด์ ์์ฑํ์๋๋ฐ,
ํ๋์ ํด๋์ค์ ๋ฌถ์ด์ ์์ฑํ๋ ๊ฒ๋ ๊ด์ฐฎ์ ๋ณด์ด๋ค์๐ |
@@ -0,0 +1,63 @@
+import InputView from "../view/InputView.js";
+import OutputView from "../view/OutputView.js";
+import Order from "../model/Order.js";
+import Benefit from "../model/Benefit.js";
+import { print } from "../commons/utils.js";
+import { MENU } from "../commons/constants.js";
+
+class EventController {
+ #date;
+ #menu;
+
+ async eventStart() {
+ OutputView.printStart();
+
+ // ์ฃผ๋ฌธ ์ ๋ณด ์
๋ ฅ & ์ฃผ๋ฌธ ์ ๋ณด ์ถ๋ ฅ
+ await this.#getOrderInformation();
+ OutputView.printOrderInformation(this.#date, this.#menu);
+
+ // ์ฃผ๋ฌธ ํด๋์ค ์์ฑ & ์ด ์ฃผ๋ฌธ ๊ธ์ก ์ถ๋ ฅ
+ const order = new Order(this.#date, this.#menu);
+ OutputView.printAllAmount(order.getAllAmount());
+
+ // ํํ ํด๋์ค ์์ฑ & ํํ๊ณผ ๊ด๋ จ๋ ๋ฉ์ธ์ง ์ถ๋ ฅ
+ const benefit = new Benefit(this.#date, this.#menu);
+ this.#printBenefit(benefit);
+ }
+
+ async #getOrderInformation() {
+ await this.#getDate();
+ await this.#getMenu();
+ }
+
+ async #getDate() {
+ while (true) {
+ try {
+ this.#date = await InputView.inputDate();
+ break;
+ } catch (error) {
+ print(error);
+ }
+ }
+ }
+
+ async #getMenu() {
+ while (true) {
+ try {
+ this.#menu = await InputView.inputMenu();
+ break;
+ } catch (error) {
+ print(error);
+ }
+ }
+ }
+
+ #printBenefit(benefit) {
+ OutputView.printGiveaway(benefit.benefitDetail()); // <์ฆ์ ๋ฉ๋ด>
+ OutputView.printBenefitDetail(benefit.benefitDetail()); // <ํํ ๋ด์ญ>
+ OutputView.printTotalBenefit(benefit.totalBenefit()); // <์ด ํํ
๊ธ์ก>
+ OutputView.printExpectedAmount(benefit.expectedAmount()); // <ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก>
+ OutputView.printEventBadge(benefit.eventBadge()); // <12์ ์ด๋ฒคํธ ๋ฐฐ์ง>
+ }
+}
+export default EventController; | JavaScript | Controller์ ํ๋๋ model์ ํ๋๋ฅผ ํตํด ๋ถ๋ฌ์ฌ ์ ์๋ค๊ณ ์๊ฐํฉ๋๋ค!
ํ๋๋ฅผ ์ค์ฌ๋ณด๋๊ฑด ์ด๋จ๊น์? |
@@ -0,0 +1,63 @@
+import InputView from "../view/InputView.js";
+import OutputView from "../view/OutputView.js";
+import Order from "../model/Order.js";
+import Benefit from "../model/Benefit.js";
+import { print } from "../commons/utils.js";
+import { MENU } from "../commons/constants.js";
+
+class EventController {
+ #date;
+ #menu;
+
+ async eventStart() {
+ OutputView.printStart();
+
+ // ์ฃผ๋ฌธ ์ ๋ณด ์
๋ ฅ & ์ฃผ๋ฌธ ์ ๋ณด ์ถ๋ ฅ
+ await this.#getOrderInformation();
+ OutputView.printOrderInformation(this.#date, this.#menu);
+
+ // ์ฃผ๋ฌธ ํด๋์ค ์์ฑ & ์ด ์ฃผ๋ฌธ ๊ธ์ก ์ถ๋ ฅ
+ const order = new Order(this.#date, this.#menu);
+ OutputView.printAllAmount(order.getAllAmount());
+
+ // ํํ ํด๋์ค ์์ฑ & ํํ๊ณผ ๊ด๋ จ๋ ๋ฉ์ธ์ง ์ถ๋ ฅ
+ const benefit = new Benefit(this.#date, this.#menu);
+ this.#printBenefit(benefit);
+ }
+
+ async #getOrderInformation() {
+ await this.#getDate();
+ await this.#getMenu();
+ }
+
+ async #getDate() {
+ while (true) {
+ try {
+ this.#date = await InputView.inputDate();
+ break;
+ } catch (error) {
+ print(error);
+ }
+ }
+ }
+
+ async #getMenu() {
+ while (true) {
+ try {
+ this.#menu = await InputView.inputMenu();
+ break;
+ } catch (error) {
+ print(error);
+ }
+ }
+ }
+
+ #printBenefit(benefit) {
+ OutputView.printGiveaway(benefit.benefitDetail()); // <์ฆ์ ๋ฉ๋ด>
+ OutputView.printBenefitDetail(benefit.benefitDetail()); // <ํํ ๋ด์ญ>
+ OutputView.printTotalBenefit(benefit.totalBenefit()); // <์ด ํํ
๊ธ์ก>
+ OutputView.printExpectedAmount(benefit.expectedAmount()); // <ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก>
+ OutputView.printEventBadge(benefit.eventBadge()); // <12์ ์ด๋ฒคํธ ๋ฐฐ์ง>
+ }
+}
+export default EventController; | JavaScript | ERROR์ ์ถ๋ ฅ๋ util ์ด ์๋ OutputView ์์ ํด์ฃผ๋๊ฑด ์ด๋จ๊น์? |
@@ -0,0 +1,56 @@
+import { print, priceToString } from "../commons/utils.js";
+import { MESSAGE, ARRAY, BENEFIT_AMOUNT } from "../commons/constants.js";
+
+const OutputView = {
+ printStart() {
+ print(MESSAGE.START);
+ },
+
+ printOrderInformation(date, menu) {
+ print(MESSAGE.MONTH + date + MESSAGE.SHOW_BENEFIT);
+ print(MESSAGE.MENU);
+ menu[ARRAY.MENU].forEach((menuName, index) => {
+ print(menuName + MESSAGE.BLANK + menu[ARRAY.COUNT][index] + MESSAGE.EA);
+ });
+ },
+
+ printAllAmount(amount) {
+ print(MESSAGE.TOTAL_AMOUNT);
+ print(priceToString(amount) + MESSAGE.WON);
+ },
+
+ printGiveaway(benefitResult) {
+ print(MESSAGE.GIVEAWAY);
+ if (benefitResult[ARRAY.GIVEAWAY] !== 0) print(MESSAGE.GIVEAWAY_ITEM);
+ else print(MESSAGE.NOTHING);
+ },
+
+ printBenefitDetail(benefitResult) {
+ print(MESSAGE.BENEFIT_DETAILS);
+ if (JSON.stringify(benefitResult) === "[0,0,0,0,0]") {
+ print(MESSAGE.NOTHING);
+ } else {
+ benefitResult.forEach((benefit, index) => {
+ if (benefit !== 0) print(MESSAGE.BENEFIT_DETAILS_TITLE[index] + priceToString(benefit) + MESSAGE.WON);
+ });
+ }
+ },
+
+ printTotalBenefit(totalBenefit) {
+ print(MESSAGE.TOTAL_BENEFIT);
+ if (totalBenefit > 0) print(MESSAGE.HYPEN + priceToString(totalBenefit) + MESSAGE.WON);
+ else print(priceToString(totalBenefit) + MESSAGE.WON);
+ },
+
+ printExpectedAmount(expectedAmount) {
+ print(MESSAGE.EXPECTED_AMOUNT);
+ print(priceToString(expectedAmount) + MESSAGE.WON);
+ },
+
+ printEventBadge(eventBadge) {
+ print(MESSAGE.EVENT_BADGE);
+ print(eventBadge);
+ },
+};
+
+export default OutputView; | JavaScript | else ๋ฅผ ์ง์ํ๋ผ๋ ์๊ตฌ์ฌํญ์ด ์์ด์,
์์ if๋ฌธ์ return ํด์ฃผ๋ ๋ฐฉ์์ ์ถ์ฒํฉ๋๋ค! |
@@ -12,19 +12,22 @@
import nextstep.security.authorization.access.MvcRequestMatcher;
import nextstep.security.authorization.access.RequestMatcherEntry;
import nextstep.security.authorization.manager.AuthenticatedAuthorizationManager;
+import nextstep.security.authorization.manager.AuthorizationManager;
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.authorization.role.RoleHierarchy;
+import nextstep.security.authorization.role.RoleHierarchyImpl;
import nextstep.security.config.DefaultSecurityFilterChain;
import nextstep.security.config.DelegatingFilterProxy;
import nextstep.security.config.FilterChainProxy;
import nextstep.security.config.SecurityFilterChain;
import nextstep.security.context.SecurityContextHolderFilter;
import nextstep.security.userdetails.UserDetails;
import nextstep.security.userdetails.UserDetailsService;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@@ -34,8 +37,8 @@
import java.util.List;
import java.util.Set;
-@EnableAspectJAutoProxy
@Configuration
+@EnableAspectJAutoProxy
public class SecurityConfig {
private final MemberRepository memberRepository;
@@ -45,8 +48,8 @@ public SecurityConfig(MemberRepository memberRepository) {
}
@Bean
- public DelegatingFilterProxy delegatingFilterProxy() {
- return new DelegatingFilterProxy(filterChainProxy(List.of(securityFilterChain())));
+ public DelegatingFilterProxy delegatingFilterProxy(RequestMatcherDelegatingAuthorizationManager requestAuthorizationManager) {
+ return new DelegatingFilterProxy(filterChainProxy(List.of(securityFilterChain(requestAuthorizationManager))));
}
@Bean
@@ -55,13 +58,13 @@ public FilterChainProxy filterChainProxy(List<SecurityFilterChain> securityFilte
}
@Bean
- public SecurityFilterChain securityFilterChain() {
+ public SecurityFilterChain securityFilterChain(RequestMatcherDelegatingAuthorizationManager requestAuthorizationManager) {
return new DefaultSecurityFilterChain(
List.of(
new SecurityContextHolderFilter(),
new UsernamePasswordAuthenticationFilter(userDetailsService()),
new BasicAuthenticationFilter(userDetailsService()),
- new AuthorizationFilter(requestAuthorizationManager())
+ new AuthorizationFilter(requestAuthorizationManager)
)
);
}
@@ -92,13 +95,7 @@ public Set<String> getAuthorities() {
}
@Bean
- public SecuredMethodInterceptor securedMethodInterceptor() {
- return new SecuredMethodInterceptor(
- new SecuredAuthorizationManager()
- );
- }
-
- @Bean
+ @ConditionalOnMissingBean(RequestMatcherDelegatingAuthorizationManager.class)
public RequestMatcherDelegatingAuthorizationManager requestAuthorizationManager() {
List<RequestMatcherEntry<AuthorizationManager<HttpServletRequest>>> mappings = new ArrayList<>();
@@ -108,17 +105,34 @@ public RequestMatcherDelegatingAuthorizationManager requestAuthorizationManager(
);
mappings.add(new RequestMatcherEntry<>(
new MvcRequestMatcher(HttpMethod.GET, "/members"),
- new HasAuthorityAuthorizationManager<>("ADMIN"))
+ new HasAuthorityAuthorizationManager<>(roleHierarchy(), "ADMIN"))
);
mappings.add(new RequestMatcherEntry<>(
new MvcRequestMatcher(HttpMethod.GET, "/search"),
new PermitAllAuthorizationManager<>())
);
+
mappings.add(new RequestMatcherEntry<>(
new AnyRequestMatcher(),
new DenyAllAuthorizationManager<>())
);
return new RequestMatcherDelegatingAuthorizationManager(mappings);
}
+
+ @Bean
+ @ConditionalOnMissingBean(RoleHierarchy.class)
+ public RoleHierarchy roleHierarchy() {
+ return RoleHierarchyImpl.with()
+ .role("ADMIN").implies("USER")
+ .build();
+ }
+
+ @Bean
+ public SecuredMethodInterceptor securedMethodInterceptor(RoleHierarchy roleHierarchy) {
+ return new SecuredMethodInterceptor(
+ new SecuredAuthorizationManager(roleHierarchy)
+ );
+ }
+
} | Java | ํ
์คํธ๋ฅผ ์ํ ์ฝ๋๊ฐ ํ๋ก๋์
์ฝ๋์ ์ถ๊ฐ๋์ด ์๋ค์! ํ
์คํธ ํ๊ฒฝ์์๋ง ์ํฅ์ ๋ฐ๋๋ก ๊ตฌ์กฐ๋ฅผ ๊ฐ์ ํด๋ณด๋ฉด ์ด๋จ๊น์? |
@@ -2,11 +2,24 @@
import nextstep.security.authentication.Authentication;
import nextstep.security.authorization.AuthorizationDecision;
+import nextstep.security.authorization.GrantedAuthority;
+import nextstep.security.authorization.role.NullRoleHierarchy;
+import nextstep.security.authorization.role.RoleHierarchy;
import java.util.Collection;
public class AuthoritiesAuthorizationManager implements AuthorizationManager<Collection<String>> {
+ private final RoleHierarchy roleHierarchy;
+
+ public AuthoritiesAuthorizationManager() {
+ this(new NullRoleHierarchy());
+ }
+
+ public AuthoritiesAuthorizationManager(RoleHierarchy roleHierarchy) {
+ this.roleHierarchy = roleHierarchy;
+ }
+
@Override
public AuthorizationDecision check(Authentication authentication, Collection<String> authorities) {
@@ -19,12 +32,17 @@ private boolean isGranted(Authentication authentication, Collection<String> auth
}
private boolean hasAuthority(Authentication authentication, Collection<String> authorities) {
- for (String authority : authentication.getAuthorities()) {
- if (authorities.contains(authority)) {
+ Collection<GrantedAuthority> reachableAuthorities = getReachableAuthorities(authentication);
+ for (GrantedAuthority authority : reachableAuthorities) {
+ if (authorities.contains(authority.getAuthority())) {
return true;
}
}
return false;
}
+
+ private Collection<GrantedAuthority> getReachableAuthorities(Authentication authentication) {
+ return roleHierarchy.getReachableGrantedAuthorities(authentication.getAuthorities());
+ }
} | Java | ```suggestion
this(new NullRoleHierarchy());
```
์์ํ์ง๋ง.. ์ฃผ ์์ฑ์๋ฅผ ์ ํด ํ๋์ ์์ฑ์์์๋ง ์ด๊ธฐํ๋ฅผ ๋ด๋นํ๋ฉด ์ ์ง๋ณด์์ฑ์ ๋์ผ ์ ์์ต๋๋ค! |
@@ -0,0 +1,87 @@
+package nextstep.security.authorization.role;
+
+import nextstep.security.SimpleGrantedAuthority;
+import nextstep.security.authorization.GrantedAuthority;
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+import java.util.Set;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+public class RoleHierarchyTest {
+
+ @Test
+ void getReachableGrantedAuthorities() {
+ RoleHierarchy roleHierarchy = RoleHierarchyImpl.fromHierarchy(
+ """
+ ROLE_ADMIN > ROLE_USER
+ ROLE_USER > ROLE_GUEST
+ """
+ );
+
+ List<String> reachableAuthorities =
+ roleHierarchy.getReachableGrantedAuthorities(Set.of(new SimpleGrantedAuthority("ROLE_ADMIN")))
+ .stream().map(GrantedAuthority::getAuthority).toList();
+
+ assertThat(reachableAuthorities).containsExactlyInAnyOrder(
+ "ROLE_ADMIN",
+ "ROLE_USER",
+ "ROLE_GUEST"
+ );
+
+ }
+
+ @Test
+ void getComplexReachableGrantedAuthorities() {
+ RoleHierarchy roleHierarchy = RoleHierarchyImpl.fromHierarchy(
+ """
+ ROLE_ADMIN > ROLE_USER
+ ROLE_USER > ROLE_GUEST
+ ROLE_ADMIN > ROLE_ANY
+ """
+ );
+
+ List<String> reachableAuthorities =
+ roleHierarchy.getReachableGrantedAuthorities(Set.of(new SimpleGrantedAuthority("ROLE_ADMIN")))
+ .stream().map(GrantedAuthority::getAuthority).toList();
+
+ assertThat(reachableAuthorities).containsExactlyInAnyOrder(
+ "ROLE_ADMIN",
+ "ROLE_USER",
+ "ROLE_GUEST",
+ "ROLE_ANY"
+ );
+
+ }
+
+ @Test
+ void buildWithDsl() {
+ RoleHierarchy roleHierarchy = RoleHierarchyImpl.with()
+ .role("ROLE_ADMIN").implies("ROLE_USER")
+ .role("ROLE_USER").implies("ROLE_GUEST")
+ .build();
+
+ List<String> reachableAuthorities =
+ roleHierarchy.getReachableGrantedAuthorities(Set.of(new SimpleGrantedAuthority("ROLE_ADMIN")))
+ .stream().map(GrantedAuthority::getAuthority).toList();
+
+ assertThat(reachableAuthorities).containsExactlyInAnyOrder(
+ "ROLE_ADMIN",
+ "ROLE_USER",
+ "ROLE_GUEST"
+ );
+ }
+
+ @Test
+ void hierarchyCycleDetect() {
+ assertThatThrownBy(() -> RoleHierarchyImpl.with()
+ .role("ROLE_ADMIN").implies("ROLE_USER")
+ .role("ROLE_USER").implies("ROLE_GUEST")
+ .role("ROLE_GUEST").implies("ROLE_ADMIN") // Cycle
+ .build())
+ .isInstanceOf(CycleInRoleHierarchyException.class);
+ }
+} | Java | ํ
์คํธ ๋๋ฌด ์ข๋ค์ ๐
์ถ๊ฐ๋ก ์ํ ์ฐธ์กฐ๊ฐ ๋ฐ์ํ์ ๋์ ๊ฐ์ ์์ธ ์ํฉ์ ๋ํ ํ
์คํธ๋ ์ถ๊ฐํด๋ณด๋ฉด ์ด๋จ๊น์? |
@@ -0,0 +1,148 @@
+package nextstep.security.authorization.role;
+
+import nextstep.security.SimpleGrantedAuthority;
+import nextstep.security.authorization.GrantedAuthority;
+
+import java.util.ArrayDeque;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Queue;
+import java.util.Set;
+
+public class RoleHierarchyImpl implements RoleHierarchy {
+
+ private final Map<String, Set<GrantedAuthority>> reachableAuthoritiesMap;
+
+ private RoleHierarchyImpl(Map<String, Set<GrantedAuthority>> reachableAuthoritiesMap) {
+ this.reachableAuthoritiesMap = reachableAuthoritiesMap;
+ RoleHierarchyCycleChecker cycleChecker = new RoleHierarchyCycleChecker(reachableAuthoritiesMap);
+ cycleChecker.checkCycle();
+ }
+
+ public static RoleHierarchyImpl fromHierarchy(String hierarchy) {
+ Map<String, Set<GrantedAuthority>> reachableAuthoritiesMap = convertHierarchicalRoles(hierarchy);
+ return new RoleHierarchyImpl(reachableAuthoritiesMap);
+ }
+
+ public static Builder with() {
+ return new Builder();
+ }
+
+ private static Map<String, Set<GrantedAuthority>> convertHierarchicalRoles(String hierarchy) {
+
+ Map<String, Set<GrantedAuthority>> hierarchicalMap = new HashMap<>();
+ for (String line : hierarchy.split("\n")) {
+ String[] roles = line.trim().split("\\s*>\\s*");
+
+ String parent = roles[0].trim();
+ String child = roles[1].trim();
+
+ hierarchicalMap.computeIfAbsent(parent, k -> new HashSet<>())
+ .add(new SimpleGrantedAuthority(child));
+ }
+
+ return hierarchicalMap;
+ }
+
+ @Override
+ public Collection<GrantedAuthority> getReachableGrantedAuthorities(
+ Collection<GrantedAuthority> authorities) {
+
+ Set<GrantedAuthority> result = new HashSet<>();
+ Set<GrantedAuthority> processed = new HashSet<>();
+ Queue<GrantedAuthority> queue = new ArrayDeque<>(authorities);
+
+ while (!queue.isEmpty()) {
+ GrantedAuthority current = queue.poll();
+
+ if (processed.contains(current)) {
+ continue;
+ }
+
+ processed.add(current);
+ result.add(current);
+
+ Set<GrantedAuthority> next = reachableAuthoritiesMap.getOrDefault(current.getAuthority(), Collections.emptySet());
+ for (GrantedAuthority authority : next) {
+ if (!processed.contains(authority)) {
+ queue.offer(authority);
+ }
+ }
+ }
+
+ return result;
+ }
+
+ public static final class Builder {
+ private final Map<String, Set<GrantedAuthority>> hierarchy = new HashMap<>();
+
+ public ImpliedRoles role(String parent) {
+ return new ImpliedRoles(parent);
+ }
+
+ public RoleHierarchyImpl build() {
+ return new RoleHierarchyImpl(hierarchy);
+ }
+
+ private Builder addHierarchy(String role, String... children) {
+ Set<GrantedAuthority> authorities = hierarchy.computeIfAbsent(role, k -> new HashSet<>());
+ for (String child : children) {
+ authorities.add(new SimpleGrantedAuthority(child));
+ }
+
+ return this;
+ }
+
+ public final class ImpliedRoles {
+ private final String parent;
+
+ public ImpliedRoles(String parent) {
+ this.parent = parent;
+ }
+
+ public Builder implies(String... children) {
+ return Builder.this.addHierarchy(parent, children);
+ }
+ }
+ }
+
+ private static final class RoleHierarchyCycleChecker {
+ private final Map<String, Set<GrantedAuthority>> reachableAuthoritiesMap;
+ private final Set<String> visited;
+ private final Set<String> visiting;
+
+ private RoleHierarchyCycleChecker(Map<String, Set<GrantedAuthority>> reachableAuthoritiesMap) {
+ this.reachableAuthoritiesMap = reachableAuthoritiesMap;
+ this.visited = new HashSet<>();
+ this.visiting = new HashSet<>();
+ }
+
+ private void checkCycle() {
+ for (String role : reachableAuthoritiesMap.keySet()) {
+ if (!visited.contains(role)) {
+ visit(role);
+ }
+ }
+ }
+
+ private void visit(String role) {
+ if (visiting.contains(role)) {
+ throw new CycleInRoleHierarchyException();
+ }
+
+ visiting.add(role);
+ Set<GrantedAuthority> children = reachableAuthoritiesMap.get(role);
+ if (children != null) {
+ for (GrantedAuthority child : children) {
+ visit(child.getAuthority());
+ }
+ }
+
+ visiting.remove(role);
+ visited.add(role);
+ }
+ }
+} | Java | ์ง๊ธ์ stream ๊ธฐ๋ฅ์ ์ ํ์ฉํด์ ๊ตฌํํด ์ฃผ์
จ๋๋ฐ์! ์คํ๋ง๊ณผ ๊ฐ์ ํ๋ ์์ํฌ์ ๊ฒฝ์ฐ ๊ฐ๋
์ฑ๋ณด๋ค ์ฑ๋ฅ์ ์ฐ์ ํ๊ธฐ ๋๋ฌธ์ stream ๋ณด๋จ for๋ฌธ์ ์ ํธํ๊ณ ์์ต๋๋ค.
๊ธฐ์กด ์ ํ๋ฆฌ์ผ์ด์
์ ๋ฐฉํฅ์ฑ์ธ ๊ฐ๋
์ฑ๋ณด๋ค ์ฑ๋ฅ์ ์ฐ์ ์ผ๋ก ๊ตฌํํด๋ณด๋ ๊ฒ๋ ํ๋์ ์ฌ๋ฏธ๊ฐ ๋ ์ ์์ ๊ฒ ๊ฐ์ต๋๋ค :) |
@@ -0,0 +1,148 @@
+package nextstep.security.authorization.role;
+
+import nextstep.security.SimpleGrantedAuthority;
+import nextstep.security.authorization.GrantedAuthority;
+
+import java.util.ArrayDeque;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Queue;
+import java.util.Set;
+
+public class RoleHierarchyImpl implements RoleHierarchy {
+
+ private final Map<String, Set<GrantedAuthority>> reachableAuthoritiesMap;
+
+ private RoleHierarchyImpl(Map<String, Set<GrantedAuthority>> reachableAuthoritiesMap) {
+ this.reachableAuthoritiesMap = reachableAuthoritiesMap;
+ RoleHierarchyCycleChecker cycleChecker = new RoleHierarchyCycleChecker(reachableAuthoritiesMap);
+ cycleChecker.checkCycle();
+ }
+
+ public static RoleHierarchyImpl fromHierarchy(String hierarchy) {
+ Map<String, Set<GrantedAuthority>> reachableAuthoritiesMap = convertHierarchicalRoles(hierarchy);
+ return new RoleHierarchyImpl(reachableAuthoritiesMap);
+ }
+
+ public static Builder with() {
+ return new Builder();
+ }
+
+ private static Map<String, Set<GrantedAuthority>> convertHierarchicalRoles(String hierarchy) {
+
+ Map<String, Set<GrantedAuthority>> hierarchicalMap = new HashMap<>();
+ for (String line : hierarchy.split("\n")) {
+ String[] roles = line.trim().split("\\s*>\\s*");
+
+ String parent = roles[0].trim();
+ String child = roles[1].trim();
+
+ hierarchicalMap.computeIfAbsent(parent, k -> new HashSet<>())
+ .add(new SimpleGrantedAuthority(child));
+ }
+
+ return hierarchicalMap;
+ }
+
+ @Override
+ public Collection<GrantedAuthority> getReachableGrantedAuthorities(
+ Collection<GrantedAuthority> authorities) {
+
+ Set<GrantedAuthority> result = new HashSet<>();
+ Set<GrantedAuthority> processed = new HashSet<>();
+ Queue<GrantedAuthority> queue = new ArrayDeque<>(authorities);
+
+ while (!queue.isEmpty()) {
+ GrantedAuthority current = queue.poll();
+
+ if (processed.contains(current)) {
+ continue;
+ }
+
+ processed.add(current);
+ result.add(current);
+
+ Set<GrantedAuthority> next = reachableAuthoritiesMap.getOrDefault(current.getAuthority(), Collections.emptySet());
+ for (GrantedAuthority authority : next) {
+ if (!processed.contains(authority)) {
+ queue.offer(authority);
+ }
+ }
+ }
+
+ return result;
+ }
+
+ public static final class Builder {
+ private final Map<String, Set<GrantedAuthority>> hierarchy = new HashMap<>();
+
+ public ImpliedRoles role(String parent) {
+ return new ImpliedRoles(parent);
+ }
+
+ public RoleHierarchyImpl build() {
+ return new RoleHierarchyImpl(hierarchy);
+ }
+
+ private Builder addHierarchy(String role, String... children) {
+ Set<GrantedAuthority> authorities = hierarchy.computeIfAbsent(role, k -> new HashSet<>());
+ for (String child : children) {
+ authorities.add(new SimpleGrantedAuthority(child));
+ }
+
+ return this;
+ }
+
+ public final class ImpliedRoles {
+ private final String parent;
+
+ public ImpliedRoles(String parent) {
+ this.parent = parent;
+ }
+
+ public Builder implies(String... children) {
+ return Builder.this.addHierarchy(parent, children);
+ }
+ }
+ }
+
+ private static final class RoleHierarchyCycleChecker {
+ private final Map<String, Set<GrantedAuthority>> reachableAuthoritiesMap;
+ private final Set<String> visited;
+ private final Set<String> visiting;
+
+ private RoleHierarchyCycleChecker(Map<String, Set<GrantedAuthority>> reachableAuthoritiesMap) {
+ this.reachableAuthoritiesMap = reachableAuthoritiesMap;
+ this.visited = new HashSet<>();
+ this.visiting = new HashSet<>();
+ }
+
+ private void checkCycle() {
+ for (String role : reachableAuthoritiesMap.keySet()) {
+ if (!visited.contains(role)) {
+ visit(role);
+ }
+ }
+ }
+
+ private void visit(String role) {
+ if (visiting.contains(role)) {
+ throw new CycleInRoleHierarchyException();
+ }
+
+ visiting.add(role);
+ Set<GrantedAuthority> children = reachableAuthoritiesMap.get(role);
+ if (children != null) {
+ for (GrantedAuthority child : children) {
+ visit(child.getAuthority());
+ }
+ }
+
+ visiting.remove(role);
+ visited.add(role);
+ }
+ }
+} | Java | ```suggestion
Queue<GrantedAuthority> queue = new ArrayDeque<>(authorities);
```
BFS ์๊ณ ๋ฆฌ์ฆ์ ํ์ฉํ์ฌ ์ ๊ตฌํํด ์ฃผ์
จ๋ค์ ๐
์๊ณ ๋ฆฌ์ฆ์ ๋ง๋ ์๋ฃ๊ตฌ์กฐ๋ก ๋ฐ๊พผ๋ค๋ฉด ์ฑ๋ฅ์ด ๋ ์ฌ๋ผ๊ฐ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,148 @@
+package nextstep.security.authorization.role;
+
+import nextstep.security.SimpleGrantedAuthority;
+import nextstep.security.authorization.GrantedAuthority;
+
+import java.util.ArrayDeque;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Queue;
+import java.util.Set;
+
+public class RoleHierarchyImpl implements RoleHierarchy {
+
+ private final Map<String, Set<GrantedAuthority>> reachableAuthoritiesMap;
+
+ private RoleHierarchyImpl(Map<String, Set<GrantedAuthority>> reachableAuthoritiesMap) {
+ this.reachableAuthoritiesMap = reachableAuthoritiesMap;
+ RoleHierarchyCycleChecker cycleChecker = new RoleHierarchyCycleChecker(reachableAuthoritiesMap);
+ cycleChecker.checkCycle();
+ }
+
+ public static RoleHierarchyImpl fromHierarchy(String hierarchy) {
+ Map<String, Set<GrantedAuthority>> reachableAuthoritiesMap = convertHierarchicalRoles(hierarchy);
+ return new RoleHierarchyImpl(reachableAuthoritiesMap);
+ }
+
+ public static Builder with() {
+ return new Builder();
+ }
+
+ private static Map<String, Set<GrantedAuthority>> convertHierarchicalRoles(String hierarchy) {
+
+ Map<String, Set<GrantedAuthority>> hierarchicalMap = new HashMap<>();
+ for (String line : hierarchy.split("\n")) {
+ String[] roles = line.trim().split("\\s*>\\s*");
+
+ String parent = roles[0].trim();
+ String child = roles[1].trim();
+
+ hierarchicalMap.computeIfAbsent(parent, k -> new HashSet<>())
+ .add(new SimpleGrantedAuthority(child));
+ }
+
+ return hierarchicalMap;
+ }
+
+ @Override
+ public Collection<GrantedAuthority> getReachableGrantedAuthorities(
+ Collection<GrantedAuthority> authorities) {
+
+ Set<GrantedAuthority> result = new HashSet<>();
+ Set<GrantedAuthority> processed = new HashSet<>();
+ Queue<GrantedAuthority> queue = new ArrayDeque<>(authorities);
+
+ while (!queue.isEmpty()) {
+ GrantedAuthority current = queue.poll();
+
+ if (processed.contains(current)) {
+ continue;
+ }
+
+ processed.add(current);
+ result.add(current);
+
+ Set<GrantedAuthority> next = reachableAuthoritiesMap.getOrDefault(current.getAuthority(), Collections.emptySet());
+ for (GrantedAuthority authority : next) {
+ if (!processed.contains(authority)) {
+ queue.offer(authority);
+ }
+ }
+ }
+
+ return result;
+ }
+
+ public static final class Builder {
+ private final Map<String, Set<GrantedAuthority>> hierarchy = new HashMap<>();
+
+ public ImpliedRoles role(String parent) {
+ return new ImpliedRoles(parent);
+ }
+
+ public RoleHierarchyImpl build() {
+ return new RoleHierarchyImpl(hierarchy);
+ }
+
+ private Builder addHierarchy(String role, String... children) {
+ Set<GrantedAuthority> authorities = hierarchy.computeIfAbsent(role, k -> new HashSet<>());
+ for (String child : children) {
+ authorities.add(new SimpleGrantedAuthority(child));
+ }
+
+ return this;
+ }
+
+ public final class ImpliedRoles {
+ private final String parent;
+
+ public ImpliedRoles(String parent) {
+ this.parent = parent;
+ }
+
+ public Builder implies(String... children) {
+ return Builder.this.addHierarchy(parent, children);
+ }
+ }
+ }
+
+ private static final class RoleHierarchyCycleChecker {
+ private final Map<String, Set<GrantedAuthority>> reachableAuthoritiesMap;
+ private final Set<String> visited;
+ private final Set<String> visiting;
+
+ private RoleHierarchyCycleChecker(Map<String, Set<GrantedAuthority>> reachableAuthoritiesMap) {
+ this.reachableAuthoritiesMap = reachableAuthoritiesMap;
+ this.visited = new HashSet<>();
+ this.visiting = new HashSet<>();
+ }
+
+ private void checkCycle() {
+ for (String role : reachableAuthoritiesMap.keySet()) {
+ if (!visited.contains(role)) {
+ visit(role);
+ }
+ }
+ }
+
+ private void visit(String role) {
+ if (visiting.contains(role)) {
+ throw new CycleInRoleHierarchyException();
+ }
+
+ visiting.add(role);
+ Set<GrantedAuthority> children = reachableAuthoritiesMap.get(role);
+ if (children != null) {
+ for (GrantedAuthority child : children) {
+ visit(child.getAuthority());
+ }
+ }
+
+ visiting.remove(role);
+ visited.add(role);
+ }
+ }
+} | Java | ์ค... ๊ทธ๋ ๊ตฐ์ !! ์๊ฐํด๋ณด๋ ์คํ๋ง์ด๋ ์ํ๋ฆฌํฐ ์ฝ๋๋ฅผ ๋ณด๋ฉด์ stream์ ์ฌ์ฉํ ๋ถ๋ถ์ด ๊ฑฐ์ ์๋ณด์ธ๋ค ์ถ๊ธด ํ๋๋ฐ ์ฑ๋ฅ์ ์ธ ๋ถ๋ถ์ ์ฑ๊ฒจ๊ฐ๋ ๊ฒ์ด์๊ตฐ์. ์ด๋ถ๋ถ์ for loop์ผ๋ก ๋ณ๊ฒฝํด์ ์ ์ฉํด๋ณด๊ฒ ์ต๋๋ค. !! |
@@ -0,0 +1,87 @@
+package nextstep.security.authorization.role;
+
+import nextstep.security.SimpleGrantedAuthority;
+import nextstep.security.authorization.GrantedAuthority;
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+import java.util.Set;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+public class RoleHierarchyTest {
+
+ @Test
+ void getReachableGrantedAuthorities() {
+ RoleHierarchy roleHierarchy = RoleHierarchyImpl.fromHierarchy(
+ """
+ ROLE_ADMIN > ROLE_USER
+ ROLE_USER > ROLE_GUEST
+ """
+ );
+
+ List<String> reachableAuthorities =
+ roleHierarchy.getReachableGrantedAuthorities(Set.of(new SimpleGrantedAuthority("ROLE_ADMIN")))
+ .stream().map(GrantedAuthority::getAuthority).toList();
+
+ assertThat(reachableAuthorities).containsExactlyInAnyOrder(
+ "ROLE_ADMIN",
+ "ROLE_USER",
+ "ROLE_GUEST"
+ );
+
+ }
+
+ @Test
+ void getComplexReachableGrantedAuthorities() {
+ RoleHierarchy roleHierarchy = RoleHierarchyImpl.fromHierarchy(
+ """
+ ROLE_ADMIN > ROLE_USER
+ ROLE_USER > ROLE_GUEST
+ ROLE_ADMIN > ROLE_ANY
+ """
+ );
+
+ List<String> reachableAuthorities =
+ roleHierarchy.getReachableGrantedAuthorities(Set.of(new SimpleGrantedAuthority("ROLE_ADMIN")))
+ .stream().map(GrantedAuthority::getAuthority).toList();
+
+ assertThat(reachableAuthorities).containsExactlyInAnyOrder(
+ "ROLE_ADMIN",
+ "ROLE_USER",
+ "ROLE_GUEST",
+ "ROLE_ANY"
+ );
+
+ }
+
+ @Test
+ void buildWithDsl() {
+ RoleHierarchy roleHierarchy = RoleHierarchyImpl.with()
+ .role("ROLE_ADMIN").implies("ROLE_USER")
+ .role("ROLE_USER").implies("ROLE_GUEST")
+ .build();
+
+ List<String> reachableAuthorities =
+ roleHierarchy.getReachableGrantedAuthorities(Set.of(new SimpleGrantedAuthority("ROLE_ADMIN")))
+ .stream().map(GrantedAuthority::getAuthority).toList();
+
+ assertThat(reachableAuthorities).containsExactlyInAnyOrder(
+ "ROLE_ADMIN",
+ "ROLE_USER",
+ "ROLE_GUEST"
+ );
+ }
+
+ @Test
+ void hierarchyCycleDetect() {
+ assertThatThrownBy(() -> RoleHierarchyImpl.with()
+ .role("ROLE_ADMIN").implies("ROLE_USER")
+ .role("ROLE_USER").implies("ROLE_GUEST")
+ .role("ROLE_GUEST").implies("ROLE_ADMIN") // Cycle
+ .build())
+ .isInstanceOf(CycleInRoleHierarchyException.class);
+ }
+} | Java | ์์ฑ์์ ํ์งํ๋ ๊ฒ์ด ์ข์ ๊ฒ ๊ฐ์ ์์ฑ์์ชฝ์ ์ถ๊ฐํด๋ณด์์ต๋๋ค! |
@@ -12,19 +12,22 @@
import nextstep.security.authorization.access.MvcRequestMatcher;
import nextstep.security.authorization.access.RequestMatcherEntry;
import nextstep.security.authorization.manager.AuthenticatedAuthorizationManager;
+import nextstep.security.authorization.manager.AuthorizationManager;
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.authorization.role.RoleHierarchy;
+import nextstep.security.authorization.role.RoleHierarchyImpl;
import nextstep.security.config.DefaultSecurityFilterChain;
import nextstep.security.config.DelegatingFilterProxy;
import nextstep.security.config.FilterChainProxy;
import nextstep.security.config.SecurityFilterChain;
import nextstep.security.context.SecurityContextHolderFilter;
import nextstep.security.userdetails.UserDetails;
import nextstep.security.userdetails.UserDetailsService;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@@ -34,8 +37,8 @@
import java.util.List;
import java.util.Set;
-@EnableAspectJAutoProxy
@Configuration
+@EnableAspectJAutoProxy
public class SecurityConfig {
private final MemberRepository memberRepository;
@@ -45,8 +48,8 @@ public SecurityConfig(MemberRepository memberRepository) {
}
@Bean
- public DelegatingFilterProxy delegatingFilterProxy() {
- return new DelegatingFilterProxy(filterChainProxy(List.of(securityFilterChain())));
+ public DelegatingFilterProxy delegatingFilterProxy(RequestMatcherDelegatingAuthorizationManager requestAuthorizationManager) {
+ return new DelegatingFilterProxy(filterChainProxy(List.of(securityFilterChain(requestAuthorizationManager))));
}
@Bean
@@ -55,13 +58,13 @@ public FilterChainProxy filterChainProxy(List<SecurityFilterChain> securityFilte
}
@Bean
- public SecurityFilterChain securityFilterChain() {
+ public SecurityFilterChain securityFilterChain(RequestMatcherDelegatingAuthorizationManager requestAuthorizationManager) {
return new DefaultSecurityFilterChain(
List.of(
new SecurityContextHolderFilter(),
new UsernamePasswordAuthenticationFilter(userDetailsService()),
new BasicAuthenticationFilter(userDetailsService()),
- new AuthorizationFilter(requestAuthorizationManager())
+ new AuthorizationFilter(requestAuthorizationManager)
)
);
}
@@ -92,13 +95,7 @@ public Set<String> getAuthorities() {
}
@Bean
- public SecuredMethodInterceptor securedMethodInterceptor() {
- return new SecuredMethodInterceptor(
- new SecuredAuthorizationManager()
- );
- }
-
- @Bean
+ @ConditionalOnMissingBean(RequestMatcherDelegatingAuthorizationManager.class)
public RequestMatcherDelegatingAuthorizationManager requestAuthorizationManager() {
List<RequestMatcherEntry<AuthorizationManager<HttpServletRequest>>> mappings = new ArrayList<>();
@@ -108,17 +105,34 @@ public RequestMatcherDelegatingAuthorizationManager requestAuthorizationManager(
);
mappings.add(new RequestMatcherEntry<>(
new MvcRequestMatcher(HttpMethod.GET, "/members"),
- new HasAuthorityAuthorizationManager<>("ADMIN"))
+ new HasAuthorityAuthorizationManager<>(roleHierarchy(), "ADMIN"))
);
mappings.add(new RequestMatcherEntry<>(
new MvcRequestMatcher(HttpMethod.GET, "/search"),
new PermitAllAuthorizationManager<>())
);
+
mappings.add(new RequestMatcherEntry<>(
new AnyRequestMatcher(),
new DenyAllAuthorizationManager<>())
);
return new RequestMatcherDelegatingAuthorizationManager(mappings);
}
+
+ @Bean
+ @ConditionalOnMissingBean(RoleHierarchy.class)
+ public RoleHierarchy roleHierarchy() {
+ return RoleHierarchyImpl.with()
+ .role("ADMIN").implies("USER")
+ .build();
+ }
+
+ @Bean
+ public SecuredMethodInterceptor securedMethodInterceptor(RoleHierarchy roleHierarchy) {
+ return new SecuredMethodInterceptor(
+ new SecuredAuthorizationManager(roleHierarchy)
+ );
+ }
+
} | Java | ํ
์คํธ์ ๋ถ๋ฆฌ๋๋ ์ฝ๋๊ฐ ๋ช
ํํ๋ค์ ๐ |
@@ -0,0 +1,148 @@
+package nextstep.security.authorization.role;
+
+import nextstep.security.SimpleGrantedAuthority;
+import nextstep.security.authorization.GrantedAuthority;
+
+import java.util.ArrayDeque;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Queue;
+import java.util.Set;
+
+public class RoleHierarchyImpl implements RoleHierarchy {
+
+ private final Map<String, Set<GrantedAuthority>> reachableAuthoritiesMap;
+
+ private RoleHierarchyImpl(Map<String, Set<GrantedAuthority>> reachableAuthoritiesMap) {
+ this.reachableAuthoritiesMap = reachableAuthoritiesMap;
+ RoleHierarchyCycleChecker cycleChecker = new RoleHierarchyCycleChecker(reachableAuthoritiesMap);
+ cycleChecker.checkCycle();
+ }
+
+ public static RoleHierarchyImpl fromHierarchy(String hierarchy) {
+ Map<String, Set<GrantedAuthority>> reachableAuthoritiesMap = convertHierarchicalRoles(hierarchy);
+ return new RoleHierarchyImpl(reachableAuthoritiesMap);
+ }
+
+ public static Builder with() {
+ return new Builder();
+ }
+
+ private static Map<String, Set<GrantedAuthority>> convertHierarchicalRoles(String hierarchy) {
+
+ Map<String, Set<GrantedAuthority>> hierarchicalMap = new HashMap<>();
+ for (String line : hierarchy.split("\n")) {
+ String[] roles = line.trim().split("\\s*>\\s*");
+
+ String parent = roles[0].trim();
+ String child = roles[1].trim();
+
+ hierarchicalMap.computeIfAbsent(parent, k -> new HashSet<>())
+ .add(new SimpleGrantedAuthority(child));
+ }
+
+ return hierarchicalMap;
+ }
+
+ @Override
+ public Collection<GrantedAuthority> getReachableGrantedAuthorities(
+ Collection<GrantedAuthority> authorities) {
+
+ Set<GrantedAuthority> result = new HashSet<>();
+ Set<GrantedAuthority> processed = new HashSet<>();
+ Queue<GrantedAuthority> queue = new ArrayDeque<>(authorities);
+
+ while (!queue.isEmpty()) {
+ GrantedAuthority current = queue.poll();
+
+ if (processed.contains(current)) {
+ continue;
+ }
+
+ processed.add(current);
+ result.add(current);
+
+ Set<GrantedAuthority> next = reachableAuthoritiesMap.getOrDefault(current.getAuthority(), Collections.emptySet());
+ for (GrantedAuthority authority : next) {
+ if (!processed.contains(authority)) {
+ queue.offer(authority);
+ }
+ }
+ }
+
+ return result;
+ }
+
+ public static final class Builder {
+ private final Map<String, Set<GrantedAuthority>> hierarchy = new HashMap<>();
+
+ public ImpliedRoles role(String parent) {
+ return new ImpliedRoles(parent);
+ }
+
+ public RoleHierarchyImpl build() {
+ return new RoleHierarchyImpl(hierarchy);
+ }
+
+ private Builder addHierarchy(String role, String... children) {
+ Set<GrantedAuthority> authorities = hierarchy.computeIfAbsent(role, k -> new HashSet<>());
+ for (String child : children) {
+ authorities.add(new SimpleGrantedAuthority(child));
+ }
+
+ return this;
+ }
+
+ public final class ImpliedRoles {
+ private final String parent;
+
+ public ImpliedRoles(String parent) {
+ this.parent = parent;
+ }
+
+ public Builder implies(String... children) {
+ return Builder.this.addHierarchy(parent, children);
+ }
+ }
+ }
+
+ private static final class RoleHierarchyCycleChecker {
+ private final Map<String, Set<GrantedAuthority>> reachableAuthoritiesMap;
+ private final Set<String> visited;
+ private final Set<String> visiting;
+
+ private RoleHierarchyCycleChecker(Map<String, Set<GrantedAuthority>> reachableAuthoritiesMap) {
+ this.reachableAuthoritiesMap = reachableAuthoritiesMap;
+ this.visited = new HashSet<>();
+ this.visiting = new HashSet<>();
+ }
+
+ private void checkCycle() {
+ for (String role : reachableAuthoritiesMap.keySet()) {
+ if (!visited.contains(role)) {
+ visit(role);
+ }
+ }
+ }
+
+ private void visit(String role) {
+ if (visiting.contains(role)) {
+ throw new CycleInRoleHierarchyException();
+ }
+
+ visiting.add(role);
+ Set<GrantedAuthority> children = reachableAuthoritiesMap.get(role);
+ if (children != null) {
+ for (GrantedAuthority child : children) {
+ visit(child.getAuthority());
+ }
+ }
+
+ visiting.remove(role);
+ visited.add(role);
+ }
+ }
+} | Java | ๋๋ฌด ์ข๋ค์ฉ ๐ฏ |
@@ -0,0 +1,90 @@
+package nextstep.app;
+
+import jakarta.servlet.http.HttpServletRequest;
+import nextstep.security.authorization.Secured;
+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.AuthorizationManager;
+import nextstep.security.authorization.manager.DenyAllAuthorizationManager;
+import nextstep.security.authorization.manager.HasAuthorityAuthorizationManager;
+import nextstep.security.authorization.manager.PermitAllAuthorizationManager;
+import nextstep.security.authorization.manager.RequestMatcherDelegatingAuthorizationManager;
+import nextstep.security.authorization.role.RoleHierarchy;
+import nextstep.security.authorization.role.RoleHierarchyImpl;
+import org.springframework.boot.test.context.TestConfiguration;
+import org.springframework.context.annotation.Bean;
+import org.springframework.http.HttpMethod;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@TestConfiguration
+public class TestSecurityConfig {
+
+ @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<>(roleHierarchy(), "ADMIN"))
+ );
+ mappings.add(new RequestMatcherEntry<>(
+ new MvcRequestMatcher(HttpMethod.GET, "/search"),
+ new PermitAllAuthorizationManager<>())
+ );
+
+ mappings.add(new RequestMatcherEntry<>(
+ new MvcRequestMatcher(HttpMethod.GET, "/user-granted"),
+ new HasAuthorityAuthorizationManager<>(roleHierarchy(), "USER"))
+ );
+
+ mappings.add(new RequestMatcherEntry<>(
+ new MvcRequestMatcher(HttpMethod.GET, "/admin-granted"),
+ new HasAuthorityAuthorizationManager<>(roleHierarchy(), "ADMIN"))
+ );
+
+ mappings.add(new RequestMatcherEntry<>(
+ new AnyRequestMatcher(),
+ new DenyAllAuthorizationManager<>())
+ );
+
+ return new RequestMatcherDelegatingAuthorizationManager(mappings);
+ }
+
+ @Bean
+ public RoleHierarchy roleHierarchy() {
+ return RoleHierarchyImpl.with()
+ .role("ADMIN").implies("USER")
+ .build();
+ }
+
+ @RestController
+ static class TestController {
+ @GetMapping("/invalid")
+ public String forbidden() {
+ return "forbidden";
+ }
+
+ @Secured("USER")
+ @GetMapping("/user-granted")
+ public String userGranted() {
+ return "userGranted";
+ }
+
+ @Secured("ADMIN")
+ @GetMapping("/admin-granted")
+ public String adminGranted() {
+ return "adminGranted";
+ }
+ }
+
+} | Java | ํ์ฌ ํ๋ก๋์
์ฝ๋์ ํ
์คํธ ์ฝ๋์์ ๋์ผํ ์ค์ ์ด ์ค๋ณต๋๊ณ ์๋๋ฐ, Spring์์ ํ์ฉํ๋ Configurer ํจํด(์ค์ ์ ํจํด)์ ํ์ฉํ๋ฉด ํ์ฅ์ฑ์ด ๋์ด๋ ์ค๋ณต์ ์์ ๋ณผ ์ ์๊ฒ ๋ค์~
์๊ฐ์ด ๋จ๊ณ ์ฌ์ฌํ์ค๊น๋ด ํ์ตํ๋ฉด ์ข์ ๋ด์ฉ ํ๋ ๋์ง๊ณ ๊ฐ๋๋ค ใ
ใ
|
@@ -0,0 +1,148 @@
+package nextstep.security.authorization.role;
+
+import nextstep.security.SimpleGrantedAuthority;
+import nextstep.security.authorization.GrantedAuthority;
+
+import java.util.ArrayDeque;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Queue;
+import java.util.Set;
+
+public class RoleHierarchyImpl implements RoleHierarchy {
+
+ private final Map<String, Set<GrantedAuthority>> reachableAuthoritiesMap;
+
+ private RoleHierarchyImpl(Map<String, Set<GrantedAuthority>> reachableAuthoritiesMap) {
+ this.reachableAuthoritiesMap = reachableAuthoritiesMap;
+ RoleHierarchyCycleChecker cycleChecker = new RoleHierarchyCycleChecker(reachableAuthoritiesMap);
+ cycleChecker.checkCycle();
+ }
+
+ public static RoleHierarchyImpl fromHierarchy(String hierarchy) {
+ Map<String, Set<GrantedAuthority>> reachableAuthoritiesMap = convertHierarchicalRoles(hierarchy);
+ return new RoleHierarchyImpl(reachableAuthoritiesMap);
+ }
+
+ public static Builder with() {
+ return new Builder();
+ }
+
+ private static Map<String, Set<GrantedAuthority>> convertHierarchicalRoles(String hierarchy) {
+
+ Map<String, Set<GrantedAuthority>> hierarchicalMap = new HashMap<>();
+ for (String line : hierarchy.split("\n")) {
+ String[] roles = line.trim().split("\\s*>\\s*");
+
+ String parent = roles[0].trim();
+ String child = roles[1].trim();
+
+ hierarchicalMap.computeIfAbsent(parent, k -> new HashSet<>())
+ .add(new SimpleGrantedAuthority(child));
+ }
+
+ return hierarchicalMap;
+ }
+
+ @Override
+ public Collection<GrantedAuthority> getReachableGrantedAuthorities(
+ Collection<GrantedAuthority> authorities) {
+
+ Set<GrantedAuthority> result = new HashSet<>();
+ Set<GrantedAuthority> processed = new HashSet<>();
+ Queue<GrantedAuthority> queue = new ArrayDeque<>(authorities);
+
+ while (!queue.isEmpty()) {
+ GrantedAuthority current = queue.poll();
+
+ if (processed.contains(current)) {
+ continue;
+ }
+
+ processed.add(current);
+ result.add(current);
+
+ Set<GrantedAuthority> next = reachableAuthoritiesMap.getOrDefault(current.getAuthority(), Collections.emptySet());
+ for (GrantedAuthority authority : next) {
+ if (!processed.contains(authority)) {
+ queue.offer(authority);
+ }
+ }
+ }
+
+ return result;
+ }
+
+ public static final class Builder {
+ private final Map<String, Set<GrantedAuthority>> hierarchy = new HashMap<>();
+
+ public ImpliedRoles role(String parent) {
+ return new ImpliedRoles(parent);
+ }
+
+ public RoleHierarchyImpl build() {
+ return new RoleHierarchyImpl(hierarchy);
+ }
+
+ private Builder addHierarchy(String role, String... children) {
+ Set<GrantedAuthority> authorities = hierarchy.computeIfAbsent(role, k -> new HashSet<>());
+ for (String child : children) {
+ authorities.add(new SimpleGrantedAuthority(child));
+ }
+
+ return this;
+ }
+
+ public final class ImpliedRoles {
+ private final String parent;
+
+ public ImpliedRoles(String parent) {
+ this.parent = parent;
+ }
+
+ public Builder implies(String... children) {
+ return Builder.this.addHierarchy(parent, children);
+ }
+ }
+ }
+
+ private static final class RoleHierarchyCycleChecker {
+ private final Map<String, Set<GrantedAuthority>> reachableAuthoritiesMap;
+ private final Set<String> visited;
+ private final Set<String> visiting;
+
+ private RoleHierarchyCycleChecker(Map<String, Set<GrantedAuthority>> reachableAuthoritiesMap) {
+ this.reachableAuthoritiesMap = reachableAuthoritiesMap;
+ this.visited = new HashSet<>();
+ this.visiting = new HashSet<>();
+ }
+
+ private void checkCycle() {
+ for (String role : reachableAuthoritiesMap.keySet()) {
+ if (!visited.contains(role)) {
+ visit(role);
+ }
+ }
+ }
+
+ private void visit(String role) {
+ if (visiting.contains(role)) {
+ throw new CycleInRoleHierarchyException();
+ }
+
+ visiting.add(role);
+ Set<GrantedAuthority> children = reachableAuthoritiesMap.get(role);
+ if (children != null) {
+ for (GrantedAuthority child : children) {
+ visit(child.getAuthority());
+ }
+ }
+
+ visiting.remove(role);
+ visited.add(role);
+ }
+ }
+} | Java | ๋ฐ๋ณต๋ฌธ์ผ๋ก ๊น๋ํ๊ฒ ๋ณ๊ฒฝํด ์ฃผ์
จ๋ค์ ๐
๋ฏธ์
์ ๋ค๋ฅธ ๋ถ๋ถ์๋ ์์ง ์คํธ๋ฆผ ์ฝ๋๊ฐ ๋จ์ ์๋๋ฐ, ์ด๋ฒ ๋ณ๊ฒฝ์ด ํด๋น ๋ถ๋ถ๋ง ์์ ํ๋ ๊ฒ์ด ๋ง์๊น์?
๋ค๋ฅธ ์ฝ๋์ ์ฝ๋ฉํธ๋ฅผ ๋๋ฆฌ๋ ค ํ๋๋ฐ, ํน์ ์๋ํ์ ๊ฒ์ธ์ง ํ์ธ์ ์ํด ๋ฆฌ๋ทฐ ๋จ๊น๋๋ค. |
@@ -0,0 +1,148 @@
+package nextstep.security.authorization.role;
+
+import nextstep.security.SimpleGrantedAuthority;
+import nextstep.security.authorization.GrantedAuthority;
+
+import java.util.ArrayDeque;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Queue;
+import java.util.Set;
+
+public class RoleHierarchyImpl implements RoleHierarchy {
+
+ private final Map<String, Set<GrantedAuthority>> reachableAuthoritiesMap;
+
+ private RoleHierarchyImpl(Map<String, Set<GrantedAuthority>> reachableAuthoritiesMap) {
+ this.reachableAuthoritiesMap = reachableAuthoritiesMap;
+ RoleHierarchyCycleChecker cycleChecker = new RoleHierarchyCycleChecker(reachableAuthoritiesMap);
+ cycleChecker.checkCycle();
+ }
+
+ public static RoleHierarchyImpl fromHierarchy(String hierarchy) {
+ Map<String, Set<GrantedAuthority>> reachableAuthoritiesMap = convertHierarchicalRoles(hierarchy);
+ return new RoleHierarchyImpl(reachableAuthoritiesMap);
+ }
+
+ public static Builder with() {
+ return new Builder();
+ }
+
+ private static Map<String, Set<GrantedAuthority>> convertHierarchicalRoles(String hierarchy) {
+
+ Map<String, Set<GrantedAuthority>> hierarchicalMap = new HashMap<>();
+ for (String line : hierarchy.split("\n")) {
+ String[] roles = line.trim().split("\\s*>\\s*");
+
+ String parent = roles[0].trim();
+ String child = roles[1].trim();
+
+ hierarchicalMap.computeIfAbsent(parent, k -> new HashSet<>())
+ .add(new SimpleGrantedAuthority(child));
+ }
+
+ return hierarchicalMap;
+ }
+
+ @Override
+ public Collection<GrantedAuthority> getReachableGrantedAuthorities(
+ Collection<GrantedAuthority> authorities) {
+
+ Set<GrantedAuthority> result = new HashSet<>();
+ Set<GrantedAuthority> processed = new HashSet<>();
+ Queue<GrantedAuthority> queue = new ArrayDeque<>(authorities);
+
+ while (!queue.isEmpty()) {
+ GrantedAuthority current = queue.poll();
+
+ if (processed.contains(current)) {
+ continue;
+ }
+
+ processed.add(current);
+ result.add(current);
+
+ Set<GrantedAuthority> next = reachableAuthoritiesMap.getOrDefault(current.getAuthority(), Collections.emptySet());
+ for (GrantedAuthority authority : next) {
+ if (!processed.contains(authority)) {
+ queue.offer(authority);
+ }
+ }
+ }
+
+ return result;
+ }
+
+ public static final class Builder {
+ private final Map<String, Set<GrantedAuthority>> hierarchy = new HashMap<>();
+
+ public ImpliedRoles role(String parent) {
+ return new ImpliedRoles(parent);
+ }
+
+ public RoleHierarchyImpl build() {
+ return new RoleHierarchyImpl(hierarchy);
+ }
+
+ private Builder addHierarchy(String role, String... children) {
+ Set<GrantedAuthority> authorities = hierarchy.computeIfAbsent(role, k -> new HashSet<>());
+ for (String child : children) {
+ authorities.add(new SimpleGrantedAuthority(child));
+ }
+
+ return this;
+ }
+
+ public final class ImpliedRoles {
+ private final String parent;
+
+ public ImpliedRoles(String parent) {
+ this.parent = parent;
+ }
+
+ public Builder implies(String... children) {
+ return Builder.this.addHierarchy(parent, children);
+ }
+ }
+ }
+
+ private static final class RoleHierarchyCycleChecker {
+ private final Map<String, Set<GrantedAuthority>> reachableAuthoritiesMap;
+ private final Set<String> visited;
+ private final Set<String> visiting;
+
+ private RoleHierarchyCycleChecker(Map<String, Set<GrantedAuthority>> reachableAuthoritiesMap) {
+ this.reachableAuthoritiesMap = reachableAuthoritiesMap;
+ this.visited = new HashSet<>();
+ this.visiting = new HashSet<>();
+ }
+
+ private void checkCycle() {
+ for (String role : reachableAuthoritiesMap.keySet()) {
+ if (!visited.contains(role)) {
+ visit(role);
+ }
+ }
+ }
+
+ private void visit(String role) {
+ if (visiting.contains(role)) {
+ throw new CycleInRoleHierarchyException();
+ }
+
+ visiting.add(role);
+ Set<GrantedAuthority> children = reachableAuthoritiesMap.get(role);
+ if (children != null) {
+ for (GrantedAuthority child : children) {
+ visit(child.getAuthority());
+ }
+ }
+
+ visiting.remove(role);
+ visited.add(role);
+ }
+ }
+} | Java | ์ ์ ๊ฐ ๋ค๋ฅธ๊ณณ์์๋ ์ฌ์ฉ์ค์ด์๋ค์ ๐ฅฒ
์ด๋ถ๋ถ์ ํ์ธ์ ๋ชปํ์ต๋๋ค ใ
ใ
ใ
๋ฐ์ํ์ต๋๋ค. ๊ผผ๊ผผํ ๋ฆฌ๋ทฐ ๊ฐ์ฌํฉ๋๋ค ! |
@@ -0,0 +1,135 @@
+package christmas.validator;
+
+import christmas.constant.Constants;
+import christmas.constant.ErrorMessage;
+import christmas.constant.Menu;
+import christmas.util.Utils;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+public class OrderValidator implements Validator {
+ @Override
+ public void check(String input) {
+ chechDefaultTemplate(input);
+ checkValidatedForm(input);
+ checkIfStringMenu(input);
+ checkQuantityRange(input);
+ checkIfMenuExists(input);
+ checkForDuplicateMenu(input);
+ checkTotalMenuCount(input);
+ checkBeverageOnly(input);
+ }
+
+ private void chechDefaultTemplate(final String input) {
+ List<String> orderItems = Arrays.asList(input.split(","));
+
+ orderItems.stream()
+ .map(item -> item.split("-"))
+ .forEach(parts -> {
+ try {
+ if (parts.length != 2 || !parts[1].matches("\\d+")) {
+ throw new IllegalArgumentException(ErrorMessage.NOT_VALIDATED_ORDER.getMessage());
+ }
+ } catch (IllegalArgumentException e) {
+ throw new IllegalArgumentException(ErrorMessage.NOT_VALIDATED_ORDER.getMessage());
+ }
+ });
+ }
+
+ private void checkValidatedForm(final String input) { // ์ ํจํ์ง์์ ์
๋ ฅ (๊ธฐ๋ณธ ํ
ํ๋ฆฟ ์
๋ ฅ์ด ์๋ ๊ฒฝ์ฐ) [์์ฒญ ์ฌํญ ์กด์ฌ]
+ try {
+ Map<String, Integer> resultMap = Stream.of(input.split(","))
+ .map(s -> s.split("-")).collect(Collectors.toMap(
+ arr -> arr[0],
+ arr -> Integer.parseInt(arr[1]),
+ (existing, replacement) -> existing,
+ HashMap::new
+ ));
+ // {"ํด์ฐ๋ฌผํ์คํ": 2, "๋ ๋์์ธ": 1, ...}
+ } catch (IllegalArgumentException e) {
+ throw new IllegalArgumentException(ErrorMessage.NOT_VALIDATED_ORDER.getMessage());
+ }
+ }
+
+ private void checkIfStringMenu(final String input) { // ๋ฉ๋ด(key) ๋ถ๋ถ์ด String, ์ฆ ๋ฌธ์์ด(ํ๊ธ,์์ด)์ด ์๋๋ฉด ์์ธ์ฒ๋ฆฌ [์์ฒญ ํ
ํ๋ฆฟ]
+ Map<String, Integer> menu = Utils.makeStringToHashMap(input);
+ menu.keySet().stream()
+ .filter(key -> !key.matches("[a-zA-Z๊ฐ-ํฃ]+"))
+ .findAny()
+ .ifPresent(invalidKey -> {
+ throw new IllegalArgumentException(ErrorMessage.NOT_VALIDATED_ORDER.getMessage());
+ });
+ }
+
+ private void checkQuantityRange(final String input) { // ์๋์ด ๊ฐ๊ฐ 1์ด์ 20์ดํ ๊ฐ ์๋๋ฉด ์์ธ์ฒ๋ฆฌ [์์ฒญ ์ฌํญ ์กด์ฌ]
+ try {
+ Map<String, Integer> menu = Utils.makeStringToHashMap(input);
+ menu.entrySet().stream()
+ .filter(entry -> entry.getValue() < 1 || entry.getValue() > 20)
+ .findAny()
+ .ifPresent(entry -> {
+ throw new IllegalArgumentException(ErrorMessage.NOT_VALIDATED_ORDER.getMessage());
+ });
+ } catch (IllegalArgumentException e) {
+ throw new IllegalArgumentException(ErrorMessage.NOT_VALIDATED_ORDER.getMessage());
+ }
+ }
+
+ private void checkIfMenuExists(final String input) { // ์๋ ๋ฉ๋ด์ผ์ง ์์ธ์ฒ๋ฆฌ ( ex) T๋ณธ์คํ
์ดํฌ ) [์์ฒญ ์ฌํญ ์กด์ฌ]
+ Map<String, Integer> menu = Utils.makeStringToHashMap(input);
+
+ Set<String> availableMenuItems = Arrays.stream(Menu.values())
+ .map(menuEnum -> menuEnum.getName())
+ .collect(Collectors.toSet());
+
+ menu.keySet().stream()
+ .filter(inputMenu -> !availableMenuItems.contains(inputMenu))
+ .findAny()
+ .ifPresent(invalidKey -> {
+ throw new IllegalArgumentException(ErrorMessage.NOT_VALIDATED_ORDER.getMessage());
+ });
+ }
+
+ private void checkForDuplicateMenu(final String input) {
+ Map<String, Integer> resultMap = Stream.of(input.split(","))
+ .map(s -> s.split("-"))
+ .collect(Collectors.toMap(
+ arr -> arr[0],
+ arr -> Integer.parseInt(arr[1]),
+ (existing, replacement) -> {
+ throw new IllegalArgumentException(ErrorMessage.NOT_VALIDATED_ORDER.getMessage());
+ },
+ HashMap::new
+ ));
+ }
+
+ private void checkTotalMenuCount(final String input) {
+ // ๋ฉ๋ด ๊ฐ์์ ํฉ์ด 20๊ฐ๊ฐ ์ด๊ณผํ ์ ์์ธ์ฒ๋ฆฌ
+ Map<String, Integer> menu = Utils.makeStringToHashMap(input);
+ int total = menu.values().stream().mapToInt(Integer::intValue).sum();
+
+ if (total > Constants.MENU_LIMIT.getConstants()) {
+ throw new IllegalArgumentException(ErrorMessage.TOTAL_MENU_COUNT_IS_OVER.getMessage());
+ }
+ }
+
+ private void checkBeverageOnly(final String input) {
+ // ๊ฐ ๋ฉ๋ด์ ์๋ฃ ํด๋์ค๋ง ์์ผ๋ฉด ์์ธ์ฒ๋ฆฌ
+
+ Map<String, Integer> menu = Utils.makeStringToHashMap(input);
+ List<String> onlyBeverage = Menu.BEVERAGE_MENU;
+
+ List<String> matchCount = menu.keySet().stream()
+ .filter(onlyBeverage::contains)
+ .toList();
+
+ if (menu.size() == matchCount.size()) {
+ throw new IllegalArgumentException(ErrorMessage.ORDER_ONLY_BEVERAGE.getMessage());
+ }
+ }
+} | Java | https://www.inflearn.com/questions/819415/verify-validate-check-is
verify, validate, check, is ์ ๋ค์ด๋ฐ ์ฐจ์ด์ ๋ํด์ ์ค๋ช
ํ๋ ๊ธ์ธ๋ฐ ์ฐธ๊ณ ํ์๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค! |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.