code stringlengths 41 34.3k | lang stringclasses 8
values | review stringlengths 1 4.74k |
|---|---|---|
@@ -0,0 +1,59 @@
+import React from 'react';
+import Comment from './Comment';
+
+class CommentBox extends React.Component {
+ constructor(props) {
+ super(props);
+ this.state = { feedComment: '', commentList: [] };
+ }
+
+ handleInput = e => {
+ this.setState({ [e.target.name]: e.target.value });
+ };
+
+ addCommentByEnter = e => {
+ if (e.key === 'Enter') {
+ this.addComment();
+ }
+ };
+
+ addComment = () => {
+ const { feedComment, commentList } = this.state;
+ this.setState({
+ commentList: [...commentList, feedComment],
+ feedComment: '',
+ });
+ };
+
+ render() {
+ return (
+ <>
+ <div className="feed__comment-box">
+ <input
+ name="feedComment"
+ className="comment__input"
+ placeholder="๋๊ธ ๋ฌ๊ธฐ..."
+ onChange={this.handleInput}
+ onKeyDown={this.addCommentByEnter}
+ value={this.state.feedComment}
+ />
+ <button
+ className="btn btn--hover comment__btn"
+ onClick={this.addComment}
+ >
+ ๊ฒ์
+ </button>
+ </div>
+ <div className="feed__comment">
+ <ul className="feed__comment-list">
+ {this.state.commentList.map((comment, index) => {
+ return <Comment key={index} innerText={comment} />;
+ })}
+ </ul>
+ </div>
+ </>
+ );
+ }
+}
+
+export default CommentBox; | JavaScript | ๋ฆฌ์กํธ๋ก ํ์ผ ์ฎ๊ฒจ์ค๊ธฐ์ jsํ์ผ๋ก๋ง ์์
ํ ๋ ๋์ผ๋ก ์ ๊ทผํ๋ ์ฉ๋๋ก ์ฐ๊ณ ์ง์ฐ๋๊ฑธ ๊น๋นกํ๋ค์ โฆ;;;ใ
ใ
์ง์ ์ต๋๋ค! |
@@ -1,9 +1,23 @@
import React from 'react';
+import './Login.scss';
+import LoginForm from './LoginForm';
-class Login extends React.Component {
+class LoginYoonHee extends React.Component {
render() {
- return null;
+ return (
+ <article className="login-art">
+ <div className="log-in__main">
+ <h1 className="main-name">westagram</h1>
+ <div className="log-in">
+ <LoginForm />
+ </div>
+ <a className="find-ps" href="#!">
+ ๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?
+ </a>
+ </div>
+ </article>
+ );
}
}
-export default Login;
+export default LoginYoonHee; | JavaScript | ์์ ํ์ต๋๋น! ๋๋ถ์ ๋ผ์ฐํฐ์ ๋ํด์ ์ข ๋ ์๊ฒ๋๋ค์ฉ ใ
ใ
|
@@ -0,0 +1,10 @@
+import React from 'react';
+
+class Comment extends React.Component {
+ render() {
+ const { innerText } = this.props;
+ return <li>{innerText}</li>;
+ }
+}
+
+export default Comment; | JavaScript | ์์ ํ์ต๋๋ค-! key๊ฐ ๋ฃ๋๊ณณ์ ์ ํํ ๋ชจ๋ฅด๊ณ ์์๋๋ฐ ์ด์ ์ ํํ๊ฒ ์๊ฑฐ๊ฐ์์! |
@@ -0,0 +1,32 @@
+import React from 'react';
+import Feed from './Feed';
+
+class Feeds extends React.Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ feeds: [],
+ };
+ }
+
+ componentDidMount() {
+ fetch('/data/feed.json')
+ .then(res => res.json())
+ .then(data => {
+ this.setState({ feeds: data });
+ });
+ }
+
+ render() {
+ const { feeds } = this.state;
+ return (
+ <div className="feeds">
+ {feeds.map(feed => (
+ <Feed key={feed.id} img={feed.img} text={feed.text} />
+ ))}
+ </div>
+ );
+ }
+}
+
+export default Feeds; | JavaScript | ์์ ํ์ต๋๋ค-! ํฌํธ๋ฒํธ๋ ์๋ต์ผ๋ฃจ! ํ ๊ฐ์ฌํฉ๋๋น! |
@@ -0,0 +1,32 @@
+import React from 'react';
+import Feed from './Feed';
+
+class Feeds extends React.Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ feeds: [],
+ };
+ }
+
+ componentDidMount() {
+ fetch('/data/feed.json')
+ .then(res => res.json())
+ .then(data => {
+ this.setState({ feeds: data });
+ });
+ }
+
+ render() {
+ const { feeds } = this.state;
+ return (
+ <div className="feeds">
+ {feeds.map(feed => (
+ <Feed key={feed.id} img={feed.img} text={feed.text} />
+ ))}
+ </div>
+ );
+ }
+}
+
+export default Feeds; | JavaScript | feed๋ก ์์ ์๋ฃ ํ์ต๋๋น ๐ |
@@ -1,9 +1,22 @@
+// eslint-disable-next-line
import React from 'react';
+import Nav from './Nav';
+import Feeds from './Feeds';
+import MainR from './MainR';
+import './Main.scss';
-class Main extends React.Component {
+class MainYoonHee extends React.Component {
render() {
- return null;
+ return (
+ <div className="main-body">
+ <Nav />
+ <main>
+ <Feeds />
+ <MainR />
+ </main>
+ </div>
+ );
}
}
-export default Main;
+export default MainYoonHee; | JavaScript | scssํ์ผ ์๋๋ก ์์น์์ ํ์ต๋๋น ! |
@@ -1,9 +1,22 @@
+// eslint-disable-next-line
import React from 'react';
+import Nav from './Nav';
+import Feeds from './Feeds';
+import MainR from './MainR';
+import './Main.scss';
-class Main extends React.Component {
+class MainYoonHee extends React.Component {
render() {
- return null;
+ return (
+ <div className="main-body">
+ <Nav />
+ <main>
+ <Feeds />
+ <MainR />
+ </main>
+ </div>
+ );
}
}
-export default Main;
+export default MainYoonHee; | JavaScript | ๊ทธ ๋ ๋ง์ํด์ฃผ์
จ๋ ๋ถ๋ถ์ด๋ค์ฉ ใ
ใ
.. <div>๋ก ๋ณ๊ฒฝํ์ต๋๋น.. ์ฝ์์ฐฝ์ ๋จ๋ ์์์๋ ๋นจ๊ฐ์ ๊ธ์จ ์ค๋ฅ๊ฐ ์ด๊ฒ๋๋ฌธ์ด์๊ตฐ์ฉ ใ
ใ
index.html์์๋ body๋ถ๋ถ๊ณผ ์ถฉ๋ํด์์; ๊ธฐ๋ณธ์ ์ธ ๊ตฌ์กฐ๋ฅผ ์๊ฐํ๋ฉด ๋น์ฐํ๊ฑด๋ฐ ์ ๊ฐ ๋๋ฌด ์์ผํ๋ค์.. |
@@ -0,0 +1,25 @@
+import React from 'react';
+
+class Recommend extends React.Component {
+ render() {
+ const { nickname, img } = this.props;
+ return (
+ <li className="user main-right__user2">
+ <div className="user-and-botton">
+ <img
+ className="user__img user__img--brder-red"
+ alt={nickname}
+ src={img}
+ />
+ <div className="user-id2">
+ <div className="user__id">{nickname}</div>
+ <div className="text--gray">ํ๊ตญ์ดํ๊ตญ์ดํ๊ตญ์ด</div>
+ </div>
+ </div>
+ <button className="btn btn--hover nnn">ํ๋ก์ฐ</button>
+ </li>
+ );
+ }
+}
+
+export default Recommend; | JavaScript | ์์ ํ์จ๋ฏธ๋น~!๐ |
@@ -0,0 +1,22 @@
+import React from 'react';
+
+class Story extends React.Component {
+ render() {
+ const { nickname, img } = this.props;
+ return (
+ <li className="user main-right__user">
+ <img
+ className="user__img user__img--brder-red"
+ alt={nickname}
+ src={img}
+ />
+ <div className="user-id2">
+ <div className="user__id">{nickname}</div>
+ <div className="text--gray">2์๊ฐ ์ </div>
+ </div>
+ </li>
+ );
+ }
+}
+
+export default Story; | JavaScript | ์ฌ๊ธฐ๋์ฉ~ |
@@ -0,0 +1,281 @@
+/*------๊ณตํต-----*/
+/*------๊ณตํต-----*/
+
+.main-body {
+ background-color: var(--color-boxgray);
+}
+
+main {
+ display: flex;
+ margin-left: 100px;
+}
+
+ul > li {
+ margin: 10px 0;
+}
+
+a {
+ text-decoration: none;
+ color: inherit;
+}
+
+.box {
+ background-color: white;
+ border: 1px solid var(--color-boxborder);
+}
+.box-padding {
+ padding: 10px;
+}
+
+.text {
+ font-size: 12px;
+}
+
+.text--gray {
+ margin-top: 3px;
+ font-size: 13px;
+ color: var(--color-textgray);
+}
+
+.icon {
+ border: no;
+}
+
+.btn {
+ padding: 5px 0px;
+ border: none;
+ border-radius: 5px;
+ background-color: transparent;
+ color: var(--color--btn-text);
+ font-weight: bold;
+}
+.btn--hover:hover {
+ color: white;
+ background-color: var(--color--btn-text);
+}
+
+.westagram {
+ font-family: 'Lobster', cursive;
+ font-size: 25px;
+}
+.user {
+ display: flex;
+ align-items: center;
+ justify-content: flex-start;
+}
+
+.user__img {
+ width: 30px;
+ height: 30px;
+ margin-right: 7px;
+ border-radius: 50%;
+ border: 1px solid var(--color-textgray);
+}
+
+.user__img--brder-red {
+ border: 1px solid red;
+ border-spacing: 3px;
+}
+
+.user__img--small {
+ width: 20px;
+ height: 18px;
+ margin-right: 5px;
+}
+
+.user__img--big {
+ width: 40px;
+ height: 40px;
+}
+
+.user__id {
+ font-size: 14px;
+ font-weight: bolder;
+}
+
+.user-text2 {
+ display: flex;
+ flex-direction: column;
+}
+
+.footer {
+ margin-top: 15px;
+}
+
+/*--------nav--------*/
+/*--------nav--------*/
+/*--------nav--------*/
+
+.nav {
+ display: flex;
+ justify-content: space-around;
+ align-items: center;
+ padding: 20px 0;
+ border-bottom: 1px solid var(--color-boxborder);
+ background-color: white;
+
+ .nav__border {
+ height: 30px;
+ border-left: 2px solid black;
+ }
+
+ .nav-left {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ width: 18%;
+ }
+
+ .nav-center {
+ width: 20%;
+ }
+
+ .nav-center > .search-bar {
+ height: 25px;
+ width: 100%;
+ border: 1px solid var(--color-boxborder);
+ background-color: var(--color-boxgray);
+ text-align: center;
+ }
+ .search-bar[value] {
+ color: var(--color-textgray);
+ }
+
+ .nav-right {
+ display: flex;
+ justify-content: space-between;
+ width: 12%;
+ }
+}
+
+/*----------feed----------*/
+/*----------feed----------*/
+/*----------feed----------*/
+
+.feeds {
+ display: flex;
+ flex-direction: column;
+ width: 50%;
+ padding-top: 65px;
+
+ .feed {
+ display: flex;
+ align-items: center;
+ flex-direction: column;
+ width: 100%;
+ margin-bottom: 50px;
+ border: 1px solid var(--color-boxborder);
+ background-color: white;
+ }
+
+ .feed__head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ width: 95%;
+ margin: 15px 20px;
+ }
+
+ .feed__head > .user {
+ width: 22%;
+ }
+
+ .feed__img {
+ width: 100%;
+ }
+
+ .feed__icons {
+ display: flex;
+ justify-content: space-between;
+ width: 95%;
+ margin: 12px 0px;
+ }
+
+ .feed__icons__left {
+ display: flex;
+ justify-content: space-between;
+ width: 18%;
+ }
+
+ .feed__likes {
+ display: flex;
+ align-items: center;
+ width: 95%;
+ }
+
+ .feed__text {
+ width: 95%;
+ margin-top: 15px;
+ }
+
+ .feed__comment-box {
+ width: 100%;
+ height: 35px;
+ margin-top: 5px;
+ border-top: 1px solid var(--color-boxborder);
+ border-bottom: 1px solid var(--color-boxborder);
+ }
+
+ .comment__input {
+ width: 90%;
+ height: 100%;
+ padding-left: 14px;
+ border: none;
+ }
+
+ .comment__input[placehilder] {
+ color: var(--color-textgray);
+ }
+
+ .comment__btn {
+ width: 8%;
+ height: 80;
+ }
+
+ .feed__comment {
+ width: 100%;
+ }
+ .feed__comment-list {
+ width: 95%;
+ margin: 10px 0;
+ padding: 5px 14px;
+ }
+
+ .feed__comment-list > li {
+ font-size: 13px;
+ }
+}
+
+/*-------------main-right------------*/
+/*-------------main-right------------*/
+/*-------------main-right------------*/
+
+.main-right {
+ position: fixed;
+ right: 40px;
+ width: 25%;
+ margin-top: 65px;
+
+ .main-right__header {
+ display: flex;
+ align-items: flex-end;
+ justify-content: space-between;
+ margin-bottom: 15px;
+ padding: 0 5px;
+ }
+
+ .user-and-botton {
+ width: 70%;
+ display: flex;
+ }
+
+ .main-right__story > .box {
+ margin-top: 15px;
+ }
+
+ .main-right__user2 {
+ display: flex;
+ justify-content: space-between;
+ margin: 2px;
+ }
+} | Unknown | common.scss ํ์ผ์ ์ด๋ฏธ ์์ด์ ํด๋น ๋ถ๋ถ ์ญ์ ํ์ด์ฉ ใ
...๐ฑ |
@@ -0,0 +1,51 @@
+import React from 'react';
+import { withRouter } from 'react-router-dom';
+
+class LoginForm extends React.Component {
+ constructor() {
+ super();
+ this.state = { id: '', ps: '' };
+ }
+
+ goToMain = e => {
+ this.props.history.push('/main-yoonhee');
+ };
+
+ handleInput = e => {
+ this.setState({ [e.target.name]: e.target.value });
+ };
+
+ render() {
+ const { id, ps } = this.state;
+ const isAble = id.includes('@') && ps.length >= 5;
+ return (
+ <form>
+ <input
+ name="id"
+ className="log-in__id"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={this.handleInput}
+ />
+
+ <input
+ name="ps"
+ className="log-in__ps"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={this.handleInput}
+ />
+ <button
+ type="button"
+ className={`log-in__btn ${isAble ? '' : 'disabled'}`}
+ onClick={this.goToMain}
+ disabled={!isAble}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ </form>
+ );
+ }
+}
+
+export default withRouter(LoginForm); | JavaScript | ๋์๋ ๊ฐ์ ๋๋ถ์
๋๋น ใ
.ใ
|
@@ -0,0 +1,59 @@
+import React from 'react';
+import Comment from './Comment';
+
+class CommentBox extends React.Component {
+ constructor(props) {
+ super(props);
+ this.state = { feedComment: '', commentList: [] };
+ }
+
+ handleInput = e => {
+ this.setState({ [e.target.name]: e.target.value });
+ };
+
+ addCommentByEnter = e => {
+ if (e.key === 'Enter') {
+ this.addComment();
+ }
+ };
+
+ addComment = () => {
+ const { feedComment, commentList } = this.state;
+ this.setState({
+ commentList: [...commentList, feedComment],
+ feedComment: '',
+ });
+ };
+
+ render() {
+ return (
+ <>
+ <div className="feed__comment-box">
+ <input
+ name="feedComment"
+ className="comment__input"
+ placeholder="๋๊ธ ๋ฌ๊ธฐ..."
+ onChange={this.handleInput}
+ onKeyDown={this.addCommentByEnter}
+ value={this.state.feedComment}
+ />
+ <button
+ className="btn btn--hover comment__btn"
+ onClick={this.addComment}
+ >
+ ๊ฒ์
+ </button>
+ </div>
+ <div className="feed__comment">
+ <ul className="feed__comment-list">
+ {this.state.commentList.map((comment, index) => {
+ return <Comment key={index} innerText={comment} />;
+ })}
+ </ul>
+ </div>
+ </>
+ );
+ }
+}
+
+export default CommentBox; | JavaScript | ๋ฐ์ดํฐ ๋ด์ฉ์ ๋ป์ ์ ์ ์๊ฒ comment๋ก ๋ณ๊ฒฝํ์ต๋๋ค! |
@@ -0,0 +1,14 @@
+const flowTypeDao = require('../models/flowTypeDao');
+const error = require('../utils/error');
+
+const getFlowTypes = async () => {
+ const flowTypes = await flowTypeDao.getFlowTypes();
+ if (flowTypes.length === 0) {
+ error.throwErr(404, 'NOT_FOUND_TYPE');
+ }
+ return flowTypes;
+}
+
+module.exports = {
+ getFlowTypes
+}
\ No newline at end of file | JavaScript | ```suggestion
return flowTypes;
}
```
else ์์ด๋ ๋ ๊ฒ ๊ฐ์ต๋๋ค :) |
@@ -0,0 +1,83 @@
+@import '../../../../../Styles/common.scss';
+
+.navYeseul {
+ position: fixed;
+ top: 0;
+ left: 50%;
+ right: 0;
+ transform: translateX(-50%);
+ padding: 8px 0;
+ border-bottom: 1px solid $main-border;
+ background-color: #fff;
+ z-index: 9999;
+
+ .inner-nav {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin: 0 auto;
+ padding: 0 20px;
+ width: 100%;
+ max-width: 975px;
+ box-sizing: border-box;
+
+ h1 {
+ display: flex;
+ align-items: center;
+ margin: 0;
+ font-size: 28px;
+ color: $main-font;
+
+ button {
+ margin-right: 15px;
+ padding: 0 14px 0 0;
+ width: 22px;
+ height: 22px;
+ box-sizing: content-box;
+ border-right: 2px solid $main-font;
+
+ img {
+ margin: 0;
+ }
+ }
+ }
+
+ .nav__search {
+ display: flex;
+ align-items: center;
+ padding: 3px 10px 3px 26px;
+ width: 215px;
+ min-width: 125px;
+ height: 28px;
+ box-sizing: border-box;
+ border: 1px solid $main-border;
+ border-radius: 3px;
+ background-color: $bg-light-grey;
+
+ input {
+ height: 100%;
+ background-color: transparent;
+
+ &::placeholder {
+ text-align: center;
+ }
+ }
+ }
+
+ .nav__menu {
+ display: flex;
+
+ li {
+ margin-left: 22px;
+ width: 22px;
+ height: 22px;
+
+ .like-button {
+ padding: 0;
+ width: 22px;
+ height: 22px;
+ }
+ }
+ }
+ }
+} | Unknown | css ์์ฑ ์์์ ๋ฐ๋ฅด๋ฉด z-index๊ฐ ๊ฐ์ฅ ์๋์ ์์ผ ํ ๊ฒ ๊ฐ์์ ๐ |
@@ -0,0 +1,83 @@
+@import '../../../../../Styles/common.scss';
+
+.navYeseul {
+ position: fixed;
+ top: 0;
+ left: 50%;
+ right: 0;
+ transform: translateX(-50%);
+ padding: 8px 0;
+ border-bottom: 1px solid $main-border;
+ background-color: #fff;
+ z-index: 9999;
+
+ .inner-nav {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin: 0 auto;
+ padding: 0 20px;
+ width: 100%;
+ max-width: 975px;
+ box-sizing: border-box;
+
+ h1 {
+ display: flex;
+ align-items: center;
+ margin: 0;
+ font-size: 28px;
+ color: $main-font;
+
+ button {
+ margin-right: 15px;
+ padding: 0 14px 0 0;
+ width: 22px;
+ height: 22px;
+ box-sizing: content-box;
+ border-right: 2px solid $main-font;
+
+ img {
+ margin: 0;
+ }
+ }
+ }
+
+ .nav__search {
+ display: flex;
+ align-items: center;
+ padding: 3px 10px 3px 26px;
+ width: 215px;
+ min-width: 125px;
+ height: 28px;
+ box-sizing: border-box;
+ border: 1px solid $main-border;
+ border-radius: 3px;
+ background-color: $bg-light-grey;
+
+ input {
+ height: 100%;
+ background-color: transparent;
+
+ &::placeholder {
+ text-align: center;
+ }
+ }
+ }
+
+ .nav__menu {
+ display: flex;
+
+ li {
+ margin-left: 22px;
+ width: 22px;
+ height: 22px;
+
+ .like-button {
+ padding: 0;
+ width: 22px;
+ height: 22px;
+ }
+ }
+ }
+ }
+} | Unknown | common css์ ์์ด์ ๋นผ์
๋ ๋ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,125 @@
+import React, { Component } from 'react';
+import { withRouter } from 'react-router-dom';
+import { API } from '../../../config';
+import './Login.scss';
+
+class LoginYeseul extends Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ inputId: '',
+ inputPw: '',
+ loginMode: true,
+ };
+ }
+
+ handleInput = e => {
+ const { name, value } = e.target;
+ this.setState({ [name]: value });
+ };
+
+ convertMode = () => {
+ this.setState({
+ loginMode: !this.state.loginMode,
+ });
+ };
+
+ signIn = e => {
+ const { inputId, inputPw } = this.state;
+ e.preventDefault();
+ fetch(API.SIGN_IN, {
+ method: 'POST',
+ body: JSON.stringify({
+ email: inputId,
+ password: inputPw,
+ }),
+ })
+ .then(users => users.json())
+ .then(users => {
+ if (users.MESSAGE === 'SUCCESS') {
+ this.setState({
+ inputId: '',
+ inputPw: '',
+ });
+ localStorage.setItem('token', users.ACCESS_TOKEN);
+ this.props.history.push('/main-yeseul');
+ } else if (users.MESSAGE === 'INVALID_USER') {
+ const wantToSignUp = window.confirm(
+ '์๋ชป๋ ์ ๋ณด์
๋๋ค. ํ์๊ฐ์
ํ์๊ฒ ์ต๋๊น?'
+ );
+ wantToSignUp && this.convertMode();
+ }
+ });
+ };
+
+ signUp = e => {
+ const { inputId, inputPw } = this.state;
+ e.preventDefault();
+ fetch(API.SIGN_UP, {
+ method: 'POST',
+ body: JSON.stringify({
+ email: inputId,
+ password: inputPw,
+ }),
+ })
+ .then(users => users.json())
+ .then(users => {
+ if (users.MESSAGE === 'SUCCESS') {
+ this.setState({
+ inputId: '',
+ inputPw: '',
+ });
+ alert(`ํ์๊ฐ์
๋์์ต๋๋ค!๐ ๋ก๊ทธ์ธํด์ฃผ์ธ์`);
+ this.convertMode();
+ } else {
+ alert(users.MESSAGE);
+ }
+ });
+ };
+
+ render() {
+ const { inputId, inputPw, loginMode } = this.state;
+ const checkId = /^\w[\w\-.]*@\w+\.\w{2,}/;
+
+ return (
+ <main className="loginYeseul give-border">
+ <h1 className="logo">westagram</h1>
+ <form
+ className="login-form"
+ onSubmit={loginMode ? this.signIn : this.signUp}
+ >
+ <div className="login-form__input-box">
+ <input
+ type="text"
+ name="inputId"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ value={inputId}
+ onChange={this.handleInput}
+ />
+ <input
+ type="password"
+ name="inputPw"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ value={inputPw}
+ onChange={this.handleInput}
+ />
+ </div>
+ <button
+ type="submit"
+ disabled={!(checkId.test(inputId) && inputPw.length > 8)}
+ >
+ {loginMode ? '๋ก๊ทธ์ธ' : 'ํ์๊ฐ์
'}
+ </button>
+ </form>
+ <a
+ href="https://www.instagram.com/accounts/password/reset/"
+ className="find-pw"
+ >
+ ๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?
+ </a>
+ </main>
+ );
+ }
+}
+
+export default withRouter(LoginYeseul); | JavaScript | ๋ํ
์ผ....๐๐ |
@@ -0,0 +1,140 @@
+import React, { Component } from 'react';
+import { Link } from 'react-router-dom';
+import User from '../User/User';
+import Comment from '../Comment/Comment';
+import IconButton from '../Button/IconButton';
+import { API } from '../../../../../config';
+import './Feed.scss';
+
+class Feed extends Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ inputComment: '',
+ commentId: 0,
+ comments: [],
+ };
+ }
+
+ componentDidMount() {
+ const { feedId } = this.props;
+ fetch(API.COMMENT)
+ .then(comments => comments.json())
+ .then(comments => {
+ this.setState({
+ commentId: comments.length + 1,
+ comments: comments.filter(comment => comment.feedId === feedId),
+ });
+ });
+ }
+
+ handleInput = e => {
+ this.setState({ inputComment: e.target.value });
+ };
+
+ addComment = e => {
+ const { inputComment, commentId, comments } = this.state;
+
+ e.preventDefault();
+ this.setState({
+ inputComment: '',
+ commentId: commentId + 1,
+ comments: [
+ ...comments,
+ {
+ id: commentId.toString(),
+ writer: this.props.userName,
+ content: inputComment,
+ tagId: '',
+ },
+ ],
+ });
+ };
+
+ deleteComment = clickedId => {
+ const { comments } = this.state;
+ this.setState({
+ comments: comments.filter(comment => comment.id !== clickedId),
+ });
+ };
+
+ render() {
+ const { inputComment, comments } = this.state;
+ const { writer, contents } = this.props;
+
+ return (
+ <article className="feed give-border">
+ <header className="feed__header">
+ <User size="small" user={writer}>
+ <IconButton
+ className="feed__header__more-icon align-right"
+ info={{ name: '๋๋ณด๊ธฐ', fileName: 'more.svg' }}
+ />
+ </User>
+ </header>
+ <div className="feed__image">
+ <img
+ alt={`by ${writer.name} on ${contents.date}`}
+ src={contents.postedImage}
+ />
+ </div>
+ <div className="feed__btns">
+ <button type="button">
+ <img
+ alt="์ข์์"
+ src="https://s3.ap-northeast-2.amazonaws.com/cdn.wecode.co.kr/bearu/heart.png"
+ />
+ </button>
+ <IconButton info={{ name: '๋๊ธ', fileName: 'comment.svg' }} />
+ <IconButton info={{ name: '๊ณต์ ํ๊ธฐ', fileName: 'send.svg' }} />
+ <IconButton
+ className="align-right"
+ info={{ name: '๋ถ๋งํฌ', fileName: 'bookmark.svg' }}
+ />
+ </div>
+ <p className="feed__likes-number">
+ <Link to="/main-yeseul">{`์ข์์ ${contents.likesNum}๊ฐ`}</Link>
+ </p>
+ <div className="feed__description">
+ <p>
+ <span className="user-name">{writer.name}</span>
+ <span>{contents.description}</span>
+ </p>
+ </div>
+ <div className="feed__comments">
+ {comments.map(comment => (
+ <Comment
+ key={comment.id}
+ info={comment}
+ handleClick={this.deleteComment}
+ />
+ ))}
+ </div>
+ <form
+ className="feed__form align-item-center space-between"
+ name="commentForm"
+ >
+ <IconButton info={{ name: '์ด๋ชจํฐ์ฝ', fileName: 'emoticon.svg' }} />
+ <input
+ type="text"
+ placeholder="๋๊ธ ๋ฌ๊ธฐ..."
+ value={inputComment}
+ className="feed__input-comment"
+ name="inputComment"
+ onChange={this.handleInput}
+ />
+ <input
+ type="submit"
+ className="feed__submit-comment"
+ name="submitComment"
+ value="๊ฒ์"
+ disabled={!(inputComment.length > 0)}
+ onClick={this.addComment}
+ />
+ </form>
+ </article>
+ );
+ }
+}
+
+export default Feed; | JavaScript | ์คํ ์์ฌ๋์ filter๋ก ๊ตฌํํ์
จ๋ค์ฌ! :) |
@@ -0,0 +1,140 @@
+import React, { Component } from 'react';
+import { Link } from 'react-router-dom';
+import User from '../User/User';
+import Comment from '../Comment/Comment';
+import IconButton from '../Button/IconButton';
+import { API } from '../../../../../config';
+import './Feed.scss';
+
+class Feed extends Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ inputComment: '',
+ commentId: 0,
+ comments: [],
+ };
+ }
+
+ componentDidMount() {
+ const { feedId } = this.props;
+ fetch(API.COMMENT)
+ .then(comments => comments.json())
+ .then(comments => {
+ this.setState({
+ commentId: comments.length + 1,
+ comments: comments.filter(comment => comment.feedId === feedId),
+ });
+ });
+ }
+
+ handleInput = e => {
+ this.setState({ inputComment: e.target.value });
+ };
+
+ addComment = e => {
+ const { inputComment, commentId, comments } = this.state;
+
+ e.preventDefault();
+ this.setState({
+ inputComment: '',
+ commentId: commentId + 1,
+ comments: [
+ ...comments,
+ {
+ id: commentId.toString(),
+ writer: this.props.userName,
+ content: inputComment,
+ tagId: '',
+ },
+ ],
+ });
+ };
+
+ deleteComment = clickedId => {
+ const { comments } = this.state;
+ this.setState({
+ comments: comments.filter(comment => comment.id !== clickedId),
+ });
+ };
+
+ render() {
+ const { inputComment, comments } = this.state;
+ const { writer, contents } = this.props;
+
+ return (
+ <article className="feed give-border">
+ <header className="feed__header">
+ <User size="small" user={writer}>
+ <IconButton
+ className="feed__header__more-icon align-right"
+ info={{ name: '๋๋ณด๊ธฐ', fileName: 'more.svg' }}
+ />
+ </User>
+ </header>
+ <div className="feed__image">
+ <img
+ alt={`by ${writer.name} on ${contents.date}`}
+ src={contents.postedImage}
+ />
+ </div>
+ <div className="feed__btns">
+ <button type="button">
+ <img
+ alt="์ข์์"
+ src="https://s3.ap-northeast-2.amazonaws.com/cdn.wecode.co.kr/bearu/heart.png"
+ />
+ </button>
+ <IconButton info={{ name: '๋๊ธ', fileName: 'comment.svg' }} />
+ <IconButton info={{ name: '๊ณต์ ํ๊ธฐ', fileName: 'send.svg' }} />
+ <IconButton
+ className="align-right"
+ info={{ name: '๋ถ๋งํฌ', fileName: 'bookmark.svg' }}
+ />
+ </div>
+ <p className="feed__likes-number">
+ <Link to="/main-yeseul">{`์ข์์ ${contents.likesNum}๊ฐ`}</Link>
+ </p>
+ <div className="feed__description">
+ <p>
+ <span className="user-name">{writer.name}</span>
+ <span>{contents.description}</span>
+ </p>
+ </div>
+ <div className="feed__comments">
+ {comments.map(comment => (
+ <Comment
+ key={comment.id}
+ info={comment}
+ handleClick={this.deleteComment}
+ />
+ ))}
+ </div>
+ <form
+ className="feed__form align-item-center space-between"
+ name="commentForm"
+ >
+ <IconButton info={{ name: '์ด๋ชจํฐ์ฝ', fileName: 'emoticon.svg' }} />
+ <input
+ type="text"
+ placeholder="๋๊ธ ๋ฌ๊ธฐ..."
+ value={inputComment}
+ className="feed__input-comment"
+ name="inputComment"
+ onChange={this.handleInput}
+ />
+ <input
+ type="submit"
+ className="feed__submit-comment"
+ name="submitComment"
+ value="๊ฒ์"
+ disabled={!(inputComment.length > 0)}
+ onClick={this.addComment}
+ />
+ </form>
+ </article>
+ );
+ }
+}
+
+export default Feed; | JavaScript | id๊ฐ์ผ๋ก key props ํ ๋น ๐ ๐ฏ ๐ฅ |
@@ -0,0 +1,125 @@
+import React, { Component } from 'react';
+import { withRouter } from 'react-router-dom';
+import { API } from '../../../config';
+import './Login.scss';
+
+class LoginYeseul extends Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ inputId: '',
+ inputPw: '',
+ loginMode: true,
+ };
+ }
+
+ handleInput = e => {
+ const { name, value } = e.target;
+ this.setState({ [name]: value });
+ };
+
+ convertMode = () => {
+ this.setState({
+ loginMode: !this.state.loginMode,
+ });
+ };
+
+ signIn = e => {
+ const { inputId, inputPw } = this.state;
+ e.preventDefault();
+ fetch(API.SIGN_IN, {
+ method: 'POST',
+ body: JSON.stringify({
+ email: inputId,
+ password: inputPw,
+ }),
+ })
+ .then(users => users.json())
+ .then(users => {
+ if (users.MESSAGE === 'SUCCESS') {
+ this.setState({
+ inputId: '',
+ inputPw: '',
+ });
+ localStorage.setItem('token', users.ACCESS_TOKEN);
+ this.props.history.push('/main-yeseul');
+ } else if (users.MESSAGE === 'INVALID_USER') {
+ const wantToSignUp = window.confirm(
+ '์๋ชป๋ ์ ๋ณด์
๋๋ค. ํ์๊ฐ์
ํ์๊ฒ ์ต๋๊น?'
+ );
+ wantToSignUp && this.convertMode();
+ }
+ });
+ };
+
+ signUp = e => {
+ const { inputId, inputPw } = this.state;
+ e.preventDefault();
+ fetch(API.SIGN_UP, {
+ method: 'POST',
+ body: JSON.stringify({
+ email: inputId,
+ password: inputPw,
+ }),
+ })
+ .then(users => users.json())
+ .then(users => {
+ if (users.MESSAGE === 'SUCCESS') {
+ this.setState({
+ inputId: '',
+ inputPw: '',
+ });
+ alert(`ํ์๊ฐ์
๋์์ต๋๋ค!๐ ๋ก๊ทธ์ธํด์ฃผ์ธ์`);
+ this.convertMode();
+ } else {
+ alert(users.MESSAGE);
+ }
+ });
+ };
+
+ render() {
+ const { inputId, inputPw, loginMode } = this.state;
+ const checkId = /^\w[\w\-.]*@\w+\.\w{2,}/;
+
+ return (
+ <main className="loginYeseul give-border">
+ <h1 className="logo">westagram</h1>
+ <form
+ className="login-form"
+ onSubmit={loginMode ? this.signIn : this.signUp}
+ >
+ <div className="login-form__input-box">
+ <input
+ type="text"
+ name="inputId"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ value={inputId}
+ onChange={this.handleInput}
+ />
+ <input
+ type="password"
+ name="inputPw"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ value={inputPw}
+ onChange={this.handleInput}
+ />
+ </div>
+ <button
+ type="submit"
+ disabled={!(checkId.test(inputId) && inputPw.length > 8)}
+ >
+ {loginMode ? '๋ก๊ทธ์ธ' : 'ํ์๊ฐ์
'}
+ </button>
+ </form>
+ <a
+ href="https://www.instagram.com/accounts/password/reset/"
+ className="find-pw"
+ >
+ ๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?
+ </a>
+ </main>
+ );
+ }
+}
+
+export default withRouter(LoginYeseul); | JavaScript | checkId์ ๋ค์ด๊ฐ๋๋ฐ์ดํฐ๋ ์ด๋ค๊ฑธ ์๋ฏธํ๋๊ฑด๊ฐ์ฌ???? |
@@ -0,0 +1,125 @@
+import React, { Component } from 'react';
+import { withRouter } from 'react-router-dom';
+import { API } from '../../../config';
+import './Login.scss';
+
+class LoginYeseul extends Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ inputId: '',
+ inputPw: '',
+ loginMode: true,
+ };
+ }
+
+ handleInput = e => {
+ const { name, value } = e.target;
+ this.setState({ [name]: value });
+ };
+
+ convertMode = () => {
+ this.setState({
+ loginMode: !this.state.loginMode,
+ });
+ };
+
+ signIn = e => {
+ const { inputId, inputPw } = this.state;
+ e.preventDefault();
+ fetch(API.SIGN_IN, {
+ method: 'POST',
+ body: JSON.stringify({
+ email: inputId,
+ password: inputPw,
+ }),
+ })
+ .then(users => users.json())
+ .then(users => {
+ if (users.MESSAGE === 'SUCCESS') {
+ this.setState({
+ inputId: '',
+ inputPw: '',
+ });
+ localStorage.setItem('token', users.ACCESS_TOKEN);
+ this.props.history.push('/main-yeseul');
+ } else if (users.MESSAGE === 'INVALID_USER') {
+ const wantToSignUp = window.confirm(
+ '์๋ชป๋ ์ ๋ณด์
๋๋ค. ํ์๊ฐ์
ํ์๊ฒ ์ต๋๊น?'
+ );
+ wantToSignUp && this.convertMode();
+ }
+ });
+ };
+
+ signUp = e => {
+ const { inputId, inputPw } = this.state;
+ e.preventDefault();
+ fetch(API.SIGN_UP, {
+ method: 'POST',
+ body: JSON.stringify({
+ email: inputId,
+ password: inputPw,
+ }),
+ })
+ .then(users => users.json())
+ .then(users => {
+ if (users.MESSAGE === 'SUCCESS') {
+ this.setState({
+ inputId: '',
+ inputPw: '',
+ });
+ alert(`ํ์๊ฐ์
๋์์ต๋๋ค!๐ ๋ก๊ทธ์ธํด์ฃผ์ธ์`);
+ this.convertMode();
+ } else {
+ alert(users.MESSAGE);
+ }
+ });
+ };
+
+ render() {
+ const { inputId, inputPw, loginMode } = this.state;
+ const checkId = /^\w[\w\-.]*@\w+\.\w{2,}/;
+
+ return (
+ <main className="loginYeseul give-border">
+ <h1 className="logo">westagram</h1>
+ <form
+ className="login-form"
+ onSubmit={loginMode ? this.signIn : this.signUp}
+ >
+ <div className="login-form__input-box">
+ <input
+ type="text"
+ name="inputId"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ value={inputId}
+ onChange={this.handleInput}
+ />
+ <input
+ type="password"
+ name="inputPw"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ value={inputPw}
+ onChange={this.handleInput}
+ />
+ </div>
+ <button
+ type="submit"
+ disabled={!(checkId.test(inputId) && inputPw.length > 8)}
+ >
+ {loginMode ? '๋ก๊ทธ์ธ' : 'ํ์๊ฐ์
'}
+ </button>
+ </form>
+ <a
+ href="https://www.instagram.com/accounts/password/reset/"
+ className="find-pw"
+ >
+ ๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?
+ </a>
+ </main>
+ );
+ }
+}
+
+export default withRouter(LoginYeseul); | JavaScript | > checkId์ ๋ค์ด๊ฐ๋๋ฐ์ดํฐ๋ ์ด๋ค๊ฑธ ์๋ฏธํ๋๊ฑด๊ฐ์ฌ????
์
๋ ฅํ ์์ด๋๊ฐ ์ด๋ฉ์ผ ํ์์ ๋ง๋์ง ์ฒดํฌํ๋ ์ ๊ทํํ์์ด์์! ๋ค์ด๋ฐ์ด ์ง๊ด์ ์ด์ง ์์๊ฐ์?? |
@@ -0,0 +1,83 @@
+@import '../../../../../Styles/common.scss';
+
+.navYeseul {
+ position: fixed;
+ top: 0;
+ left: 50%;
+ right: 0;
+ transform: translateX(-50%);
+ padding: 8px 0;
+ border-bottom: 1px solid $main-border;
+ background-color: #fff;
+ z-index: 9999;
+
+ .inner-nav {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin: 0 auto;
+ padding: 0 20px;
+ width: 100%;
+ max-width: 975px;
+ box-sizing: border-box;
+
+ h1 {
+ display: flex;
+ align-items: center;
+ margin: 0;
+ font-size: 28px;
+ color: $main-font;
+
+ button {
+ margin-right: 15px;
+ padding: 0 14px 0 0;
+ width: 22px;
+ height: 22px;
+ box-sizing: content-box;
+ border-right: 2px solid $main-font;
+
+ img {
+ margin: 0;
+ }
+ }
+ }
+
+ .nav__search {
+ display: flex;
+ align-items: center;
+ padding: 3px 10px 3px 26px;
+ width: 215px;
+ min-width: 125px;
+ height: 28px;
+ box-sizing: border-box;
+ border: 1px solid $main-border;
+ border-radius: 3px;
+ background-color: $bg-light-grey;
+
+ input {
+ height: 100%;
+ background-color: transparent;
+
+ &::placeholder {
+ text-align: center;
+ }
+ }
+ }
+
+ .nav__menu {
+ display: flex;
+
+ li {
+ margin-left: 22px;
+ width: 22px;
+ height: 22px;
+
+ .like-button {
+ padding: 0;
+ width: 22px;
+ height: 22px;
+ }
+ }
+ }
+ }
+} | Unknown | ์ค ๊ผผ๊ผผํ ๋ด์ฃผ์
จ๋ค์ ๊ฐ์ฌํฉ๋๋น :) ๊ณ ์น๋ฌ๊ฐ์ |
@@ -0,0 +1,125 @@
+import React, { Component } from 'react';
+import { withRouter } from 'react-router-dom';
+import { API } from '../../../config';
+import './Login.scss';
+
+class LoginYeseul extends Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ inputId: '',
+ inputPw: '',
+ loginMode: true,
+ };
+ }
+
+ handleInput = e => {
+ const { name, value } = e.target;
+ this.setState({ [name]: value });
+ };
+
+ convertMode = () => {
+ this.setState({
+ loginMode: !this.state.loginMode,
+ });
+ };
+
+ signIn = e => {
+ const { inputId, inputPw } = this.state;
+ e.preventDefault();
+ fetch(API.SIGN_IN, {
+ method: 'POST',
+ body: JSON.stringify({
+ email: inputId,
+ password: inputPw,
+ }),
+ })
+ .then(users => users.json())
+ .then(users => {
+ if (users.MESSAGE === 'SUCCESS') {
+ this.setState({
+ inputId: '',
+ inputPw: '',
+ });
+ localStorage.setItem('token', users.ACCESS_TOKEN);
+ this.props.history.push('/main-yeseul');
+ } else if (users.MESSAGE === 'INVALID_USER') {
+ const wantToSignUp = window.confirm(
+ '์๋ชป๋ ์ ๋ณด์
๋๋ค. ํ์๊ฐ์
ํ์๊ฒ ์ต๋๊น?'
+ );
+ wantToSignUp && this.convertMode();
+ }
+ });
+ };
+
+ signUp = e => {
+ const { inputId, inputPw } = this.state;
+ e.preventDefault();
+ fetch(API.SIGN_UP, {
+ method: 'POST',
+ body: JSON.stringify({
+ email: inputId,
+ password: inputPw,
+ }),
+ })
+ .then(users => users.json())
+ .then(users => {
+ if (users.MESSAGE === 'SUCCESS') {
+ this.setState({
+ inputId: '',
+ inputPw: '',
+ });
+ alert(`ํ์๊ฐ์
๋์์ต๋๋ค!๐ ๋ก๊ทธ์ธํด์ฃผ์ธ์`);
+ this.convertMode();
+ } else {
+ alert(users.MESSAGE);
+ }
+ });
+ };
+
+ render() {
+ const { inputId, inputPw, loginMode } = this.state;
+ const checkId = /^\w[\w\-.]*@\w+\.\w{2,}/;
+
+ return (
+ <main className="loginYeseul give-border">
+ <h1 className="logo">westagram</h1>
+ <form
+ className="login-form"
+ onSubmit={loginMode ? this.signIn : this.signUp}
+ >
+ <div className="login-form__input-box">
+ <input
+ type="text"
+ name="inputId"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ value={inputId}
+ onChange={this.handleInput}
+ />
+ <input
+ type="password"
+ name="inputPw"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ value={inputPw}
+ onChange={this.handleInput}
+ />
+ </div>
+ <button
+ type="submit"
+ disabled={!(checkId.test(inputId) && inputPw.length > 8)}
+ >
+ {loginMode ? '๋ก๊ทธ์ธ' : 'ํ์๊ฐ์
'}
+ </button>
+ </form>
+ <a
+ href="https://www.instagram.com/accounts/password/reset/"
+ className="find-pw"
+ >
+ ๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?
+ </a>
+ </main>
+ );
+ }
+}
+
+export default withRouter(LoginYeseul); | JavaScript | (์๋ฃ์ผ๋ฉด ์ค๋ฅ๊ฐ ๋จ๋๋ผ๊ตฌ์..) |
@@ -0,0 +1,83 @@
+@import '../../../../../Styles/common.scss';
+
+.navYeseul {
+ position: fixed;
+ top: 0;
+ left: 50%;
+ right: 0;
+ transform: translateX(-50%);
+ padding: 8px 0;
+ border-bottom: 1px solid $main-border;
+ background-color: #fff;
+ z-index: 9999;
+
+ .inner-nav {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin: 0 auto;
+ padding: 0 20px;
+ width: 100%;
+ max-width: 975px;
+ box-sizing: border-box;
+
+ h1 {
+ display: flex;
+ align-items: center;
+ margin: 0;
+ font-size: 28px;
+ color: $main-font;
+
+ button {
+ margin-right: 15px;
+ padding: 0 14px 0 0;
+ width: 22px;
+ height: 22px;
+ box-sizing: content-box;
+ border-right: 2px solid $main-font;
+
+ img {
+ margin: 0;
+ }
+ }
+ }
+
+ .nav__search {
+ display: flex;
+ align-items: center;
+ padding: 3px 10px 3px 26px;
+ width: 215px;
+ min-width: 125px;
+ height: 28px;
+ box-sizing: border-box;
+ border: 1px solid $main-border;
+ border-radius: 3px;
+ background-color: $bg-light-grey;
+
+ input {
+ height: 100%;
+ background-color: transparent;
+
+ &::placeholder {
+ text-align: center;
+ }
+ }
+ }
+
+ .nav__menu {
+ display: flex;
+
+ li {
+ margin-left: 22px;
+ width: 22px;
+ height: 22px;
+
+ .like-button {
+ padding: 0;
+ width: 22px;
+ height: 22px;
+ }
+ }
+ }
+ }
+} | Unknown | ์ ์ common์ ์์ฃ ?!?! |
@@ -0,0 +1,125 @@
+import React, { Component } from 'react';
+import { withRouter } from 'react-router-dom';
+import { API } from '../../../config';
+import './Login.scss';
+
+class LoginYeseul extends Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ inputId: '',
+ inputPw: '',
+ loginMode: true,
+ };
+ }
+
+ handleInput = e => {
+ const { name, value } = e.target;
+ this.setState({ [name]: value });
+ };
+
+ convertMode = () => {
+ this.setState({
+ loginMode: !this.state.loginMode,
+ });
+ };
+
+ signIn = e => {
+ const { inputId, inputPw } = this.state;
+ e.preventDefault();
+ fetch(API.SIGN_IN, {
+ method: 'POST',
+ body: JSON.stringify({
+ email: inputId,
+ password: inputPw,
+ }),
+ })
+ .then(users => users.json())
+ .then(users => {
+ if (users.MESSAGE === 'SUCCESS') {
+ this.setState({
+ inputId: '',
+ inputPw: '',
+ });
+ localStorage.setItem('token', users.ACCESS_TOKEN);
+ this.props.history.push('/main-yeseul');
+ } else if (users.MESSAGE === 'INVALID_USER') {
+ const wantToSignUp = window.confirm(
+ '์๋ชป๋ ์ ๋ณด์
๋๋ค. ํ์๊ฐ์
ํ์๊ฒ ์ต๋๊น?'
+ );
+ wantToSignUp && this.convertMode();
+ }
+ });
+ };
+
+ signUp = e => {
+ const { inputId, inputPw } = this.state;
+ e.preventDefault();
+ fetch(API.SIGN_UP, {
+ method: 'POST',
+ body: JSON.stringify({
+ email: inputId,
+ password: inputPw,
+ }),
+ })
+ .then(users => users.json())
+ .then(users => {
+ if (users.MESSAGE === 'SUCCESS') {
+ this.setState({
+ inputId: '',
+ inputPw: '',
+ });
+ alert(`ํ์๊ฐ์
๋์์ต๋๋ค!๐ ๋ก๊ทธ์ธํด์ฃผ์ธ์`);
+ this.convertMode();
+ } else {
+ alert(users.MESSAGE);
+ }
+ });
+ };
+
+ render() {
+ const { inputId, inputPw, loginMode } = this.state;
+ const checkId = /^\w[\w\-.]*@\w+\.\w{2,}/;
+
+ return (
+ <main className="loginYeseul give-border">
+ <h1 className="logo">westagram</h1>
+ <form
+ className="login-form"
+ onSubmit={loginMode ? this.signIn : this.signUp}
+ >
+ <div className="login-form__input-box">
+ <input
+ type="text"
+ name="inputId"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ value={inputId}
+ onChange={this.handleInput}
+ />
+ <input
+ type="password"
+ name="inputPw"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ value={inputPw}
+ onChange={this.handleInput}
+ />
+ </div>
+ <button
+ type="submit"
+ disabled={!(checkId.test(inputId) && inputPw.length > 8)}
+ >
+ {loginMode ? '๋ก๊ทธ์ธ' : 'ํ์๊ฐ์
'}
+ </button>
+ </form>
+ <a
+ href="https://www.instagram.com/accounts/password/reset/"
+ className="find-pw"
+ >
+ ๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?
+ </a>
+ </main>
+ );
+ }
+}
+
+export default withRouter(LoginYeseul); | JavaScript | ์๋์์ฌ ์ ๊ฐ ์๋ชฐ๋์ด์ ใ
ใ
ใ
ใ
์ํ์
จ์ด์!! |
@@ -0,0 +1,125 @@
+import React, { Component } from 'react';
+import { withRouter } from 'react-router-dom';
+import { API } from '../../../config';
+import './Login.scss';
+
+class LoginYeseul extends Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ inputId: '',
+ inputPw: '',
+ loginMode: true,
+ };
+ }
+
+ handleInput = e => {
+ const { name, value } = e.target;
+ this.setState({ [name]: value });
+ };
+
+ convertMode = () => {
+ this.setState({
+ loginMode: !this.state.loginMode,
+ });
+ };
+
+ signIn = e => {
+ const { inputId, inputPw } = this.state;
+ e.preventDefault();
+ fetch(API.SIGN_IN, {
+ method: 'POST',
+ body: JSON.stringify({
+ email: inputId,
+ password: inputPw,
+ }),
+ })
+ .then(users => users.json())
+ .then(users => {
+ if (users.MESSAGE === 'SUCCESS') {
+ this.setState({
+ inputId: '',
+ inputPw: '',
+ });
+ localStorage.setItem('token', users.ACCESS_TOKEN);
+ this.props.history.push('/main-yeseul');
+ } else if (users.MESSAGE === 'INVALID_USER') {
+ const wantToSignUp = window.confirm(
+ '์๋ชป๋ ์ ๋ณด์
๋๋ค. ํ์๊ฐ์
ํ์๊ฒ ์ต๋๊น?'
+ );
+ wantToSignUp && this.convertMode();
+ }
+ });
+ };
+
+ signUp = e => {
+ const { inputId, inputPw } = this.state;
+ e.preventDefault();
+ fetch(API.SIGN_UP, {
+ method: 'POST',
+ body: JSON.stringify({
+ email: inputId,
+ password: inputPw,
+ }),
+ })
+ .then(users => users.json())
+ .then(users => {
+ if (users.MESSAGE === 'SUCCESS') {
+ this.setState({
+ inputId: '',
+ inputPw: '',
+ });
+ alert(`ํ์๊ฐ์
๋์์ต๋๋ค!๐ ๋ก๊ทธ์ธํด์ฃผ์ธ์`);
+ this.convertMode();
+ } else {
+ alert(users.MESSAGE);
+ }
+ });
+ };
+
+ render() {
+ const { inputId, inputPw, loginMode } = this.state;
+ const checkId = /^\w[\w\-.]*@\w+\.\w{2,}/;
+
+ return (
+ <main className="loginYeseul give-border">
+ <h1 className="logo">westagram</h1>
+ <form
+ className="login-form"
+ onSubmit={loginMode ? this.signIn : this.signUp}
+ >
+ <div className="login-form__input-box">
+ <input
+ type="text"
+ name="inputId"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ value={inputId}
+ onChange={this.handleInput}
+ />
+ <input
+ type="password"
+ name="inputPw"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ value={inputPw}
+ onChange={this.handleInput}
+ />
+ </div>
+ <button
+ type="submit"
+ disabled={!(checkId.test(inputId) && inputPw.length > 8)}
+ >
+ {loginMode ? '๋ก๊ทธ์ธ' : 'ํ์๊ฐ์
'}
+ </button>
+ </form>
+ <a
+ href="https://www.instagram.com/accounts/password/reset/"
+ className="find-pw"
+ >
+ ๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?
+ </a>
+ </main>
+ );
+ }
+}
+
+export default withRouter(LoginYeseul); | JavaScript | ์ ๋ ์ด๋ฒคํธ๋ฅผ ์ค input์ name attribute๋ฅผ ๋ถ์ฌํด์ handleInputId์ด๋ handleInputPw ํจ์๋ฅผ ํ๋๋ก ํฉ์ณค๋๋ฐ ์ฐธ๊ณ ํ์
์ ๋ฐ์ํด๋ ์ข์ ๊ฒ ๊ฐ์์ค!
handleInput = e => {
this.setState({
[e.target.name]: e.target.value,
});
}; |
@@ -0,0 +1,125 @@
+import React, { Component } from 'react';
+import { withRouter } from 'react-router-dom';
+import { API } from '../../../config';
+import './Login.scss';
+
+class LoginYeseul extends Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ inputId: '',
+ inputPw: '',
+ loginMode: true,
+ };
+ }
+
+ handleInput = e => {
+ const { name, value } = e.target;
+ this.setState({ [name]: value });
+ };
+
+ convertMode = () => {
+ this.setState({
+ loginMode: !this.state.loginMode,
+ });
+ };
+
+ signIn = e => {
+ const { inputId, inputPw } = this.state;
+ e.preventDefault();
+ fetch(API.SIGN_IN, {
+ method: 'POST',
+ body: JSON.stringify({
+ email: inputId,
+ password: inputPw,
+ }),
+ })
+ .then(users => users.json())
+ .then(users => {
+ if (users.MESSAGE === 'SUCCESS') {
+ this.setState({
+ inputId: '',
+ inputPw: '',
+ });
+ localStorage.setItem('token', users.ACCESS_TOKEN);
+ this.props.history.push('/main-yeseul');
+ } else if (users.MESSAGE === 'INVALID_USER') {
+ const wantToSignUp = window.confirm(
+ '์๋ชป๋ ์ ๋ณด์
๋๋ค. ํ์๊ฐ์
ํ์๊ฒ ์ต๋๊น?'
+ );
+ wantToSignUp && this.convertMode();
+ }
+ });
+ };
+
+ signUp = e => {
+ const { inputId, inputPw } = this.state;
+ e.preventDefault();
+ fetch(API.SIGN_UP, {
+ method: 'POST',
+ body: JSON.stringify({
+ email: inputId,
+ password: inputPw,
+ }),
+ })
+ .then(users => users.json())
+ .then(users => {
+ if (users.MESSAGE === 'SUCCESS') {
+ this.setState({
+ inputId: '',
+ inputPw: '',
+ });
+ alert(`ํ์๊ฐ์
๋์์ต๋๋ค!๐ ๋ก๊ทธ์ธํด์ฃผ์ธ์`);
+ this.convertMode();
+ } else {
+ alert(users.MESSAGE);
+ }
+ });
+ };
+
+ render() {
+ const { inputId, inputPw, loginMode } = this.state;
+ const checkId = /^\w[\w\-.]*@\w+\.\w{2,}/;
+
+ return (
+ <main className="loginYeseul give-border">
+ <h1 className="logo">westagram</h1>
+ <form
+ className="login-form"
+ onSubmit={loginMode ? this.signIn : this.signUp}
+ >
+ <div className="login-form__input-box">
+ <input
+ type="text"
+ name="inputId"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ value={inputId}
+ onChange={this.handleInput}
+ />
+ <input
+ type="password"
+ name="inputPw"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ value={inputPw}
+ onChange={this.handleInput}
+ />
+ </div>
+ <button
+ type="submit"
+ disabled={!(checkId.test(inputId) && inputPw.length > 8)}
+ >
+ {loginMode ? '๋ก๊ทธ์ธ' : 'ํ์๊ฐ์
'}
+ </button>
+ </form>
+ <a
+ href="https://www.instagram.com/accounts/password/reset/"
+ className="find-pw"
+ >
+ ๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?
+ </a>
+ </main>
+ );
+ }
+}
+
+export default withRouter(LoginYeseul); | JavaScript | - API ๋ถ๋ ์ดํ์ src/config.js ํ์ผ์ ๋ง๋ค์ด ํด๋น ํ์ผ์์ ์ผ๊ด์ ์ผ๋ก ๊ด๋ฆฌํฉ๋๋ค.
```js
// config.js
const IP = '10.58.6.252:8000';
export const SIGN_IN_API = `http://${IP}/user/signin`;
// Login.js
import { SIGN_IN_API } from '../../config.js';
...
fetch(SIGN_IN_API).then().then()
...
```
- ์์ ๊ฐ์ด config.js ์์ ์ผ๊ด์ ์ผ๋ก ๊ด๋ฆฌํ ๊ฒฝ์ฐ, ๋ฐฑ์๋ ์๋ฒ์ IP ๊ฐ ๋ณ๊ฒฝ๋๊ฑฐ๋ ํน์ ์๋ํฌ์ธํธ๊ฐ ๋ณ๊ฒฝ๋์์ ๋, config.js ์์๋ง ํ๋ฒ ์์ ํด์ฃผ๋ฉด ๋๊ธฐ ๋๋ฌธ์ ์ ์ง๋ณด์๊ฐ ํธํด์ง๋๋ค. |
@@ -0,0 +1,125 @@
+import React, { Component } from 'react';
+import { withRouter } from 'react-router-dom';
+import { API } from '../../../config';
+import './Login.scss';
+
+class LoginYeseul extends Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ inputId: '',
+ inputPw: '',
+ loginMode: true,
+ };
+ }
+
+ handleInput = e => {
+ const { name, value } = e.target;
+ this.setState({ [name]: value });
+ };
+
+ convertMode = () => {
+ this.setState({
+ loginMode: !this.state.loginMode,
+ });
+ };
+
+ signIn = e => {
+ const { inputId, inputPw } = this.state;
+ e.preventDefault();
+ fetch(API.SIGN_IN, {
+ method: 'POST',
+ body: JSON.stringify({
+ email: inputId,
+ password: inputPw,
+ }),
+ })
+ .then(users => users.json())
+ .then(users => {
+ if (users.MESSAGE === 'SUCCESS') {
+ this.setState({
+ inputId: '',
+ inputPw: '',
+ });
+ localStorage.setItem('token', users.ACCESS_TOKEN);
+ this.props.history.push('/main-yeseul');
+ } else if (users.MESSAGE === 'INVALID_USER') {
+ const wantToSignUp = window.confirm(
+ '์๋ชป๋ ์ ๋ณด์
๋๋ค. ํ์๊ฐ์
ํ์๊ฒ ์ต๋๊น?'
+ );
+ wantToSignUp && this.convertMode();
+ }
+ });
+ };
+
+ signUp = e => {
+ const { inputId, inputPw } = this.state;
+ e.preventDefault();
+ fetch(API.SIGN_UP, {
+ method: 'POST',
+ body: JSON.stringify({
+ email: inputId,
+ password: inputPw,
+ }),
+ })
+ .then(users => users.json())
+ .then(users => {
+ if (users.MESSAGE === 'SUCCESS') {
+ this.setState({
+ inputId: '',
+ inputPw: '',
+ });
+ alert(`ํ์๊ฐ์
๋์์ต๋๋ค!๐ ๋ก๊ทธ์ธํด์ฃผ์ธ์`);
+ this.convertMode();
+ } else {
+ alert(users.MESSAGE);
+ }
+ });
+ };
+
+ render() {
+ const { inputId, inputPw, loginMode } = this.state;
+ const checkId = /^\w[\w\-.]*@\w+\.\w{2,}/;
+
+ return (
+ <main className="loginYeseul give-border">
+ <h1 className="logo">westagram</h1>
+ <form
+ className="login-form"
+ onSubmit={loginMode ? this.signIn : this.signUp}
+ >
+ <div className="login-form__input-box">
+ <input
+ type="text"
+ name="inputId"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ value={inputId}
+ onChange={this.handleInput}
+ />
+ <input
+ type="password"
+ name="inputPw"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ value={inputPw}
+ onChange={this.handleInput}
+ />
+ </div>
+ <button
+ type="submit"
+ disabled={!(checkId.test(inputId) && inputPw.length > 8)}
+ >
+ {loginMode ? '๋ก๊ทธ์ธ' : 'ํ์๊ฐ์
'}
+ </button>
+ </form>
+ <a
+ href="https://www.instagram.com/accounts/password/reset/"
+ className="find-pw"
+ >
+ ๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?
+ </a>
+ </main>
+ );
+ }
+}
+
+export default withRouter(LoginYeseul); | JavaScript | - ์ ๊ท์ ๐ ๐ |
@@ -0,0 +1,125 @@
+import React, { Component } from 'react';
+import { withRouter } from 'react-router-dom';
+import { API } from '../../../config';
+import './Login.scss';
+
+class LoginYeseul extends Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ inputId: '',
+ inputPw: '',
+ loginMode: true,
+ };
+ }
+
+ handleInput = e => {
+ const { name, value } = e.target;
+ this.setState({ [name]: value });
+ };
+
+ convertMode = () => {
+ this.setState({
+ loginMode: !this.state.loginMode,
+ });
+ };
+
+ signIn = e => {
+ const { inputId, inputPw } = this.state;
+ e.preventDefault();
+ fetch(API.SIGN_IN, {
+ method: 'POST',
+ body: JSON.stringify({
+ email: inputId,
+ password: inputPw,
+ }),
+ })
+ .then(users => users.json())
+ .then(users => {
+ if (users.MESSAGE === 'SUCCESS') {
+ this.setState({
+ inputId: '',
+ inputPw: '',
+ });
+ localStorage.setItem('token', users.ACCESS_TOKEN);
+ this.props.history.push('/main-yeseul');
+ } else if (users.MESSAGE === 'INVALID_USER') {
+ const wantToSignUp = window.confirm(
+ '์๋ชป๋ ์ ๋ณด์
๋๋ค. ํ์๊ฐ์
ํ์๊ฒ ์ต๋๊น?'
+ );
+ wantToSignUp && this.convertMode();
+ }
+ });
+ };
+
+ signUp = e => {
+ const { inputId, inputPw } = this.state;
+ e.preventDefault();
+ fetch(API.SIGN_UP, {
+ method: 'POST',
+ body: JSON.stringify({
+ email: inputId,
+ password: inputPw,
+ }),
+ })
+ .then(users => users.json())
+ .then(users => {
+ if (users.MESSAGE === 'SUCCESS') {
+ this.setState({
+ inputId: '',
+ inputPw: '',
+ });
+ alert(`ํ์๊ฐ์
๋์์ต๋๋ค!๐ ๋ก๊ทธ์ธํด์ฃผ์ธ์`);
+ this.convertMode();
+ } else {
+ alert(users.MESSAGE);
+ }
+ });
+ };
+
+ render() {
+ const { inputId, inputPw, loginMode } = this.state;
+ const checkId = /^\w[\w\-.]*@\w+\.\w{2,}/;
+
+ return (
+ <main className="loginYeseul give-border">
+ <h1 className="logo">westagram</h1>
+ <form
+ className="login-form"
+ onSubmit={loginMode ? this.signIn : this.signUp}
+ >
+ <div className="login-form__input-box">
+ <input
+ type="text"
+ name="inputId"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ value={inputId}
+ onChange={this.handleInput}
+ />
+ <input
+ type="password"
+ name="inputPw"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ value={inputPw}
+ onChange={this.handleInput}
+ />
+ </div>
+ <button
+ type="submit"
+ disabled={!(checkId.test(inputId) && inputPw.length > 8)}
+ >
+ {loginMode ? '๋ก๊ทธ์ธ' : 'ํ์๊ฐ์
'}
+ </button>
+ </form>
+ <a
+ href="https://www.instagram.com/accounts/password/reset/"
+ className="find-pw"
+ >
+ ๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?
+ </a>
+ </main>
+ );
+ }
+}
+
+export default withRouter(LoginYeseul); | JavaScript | - ํด๋์ค ๋ค์ ๋ค์ด๋ฐ ๐ |
@@ -0,0 +1,60 @@
+@import '../../../Styles/common.scss';
+
+.loginYeseul {
+ position: fixed;
+ top: 50%;
+ left: 50%;
+ transform: translate(-50%, -60%);
+ padding: 32px 0 25px;
+ width: 350px;
+ text-align: center;
+
+ h1 {
+ font-size: 40px;
+ }
+
+ .login-form {
+ margin: 35px 40px 120px;
+
+ &__input-box {
+ margin-bottom: 15px;
+
+ input {
+ margin: 3px 0;
+ padding: 12px 10px 10px;
+ border: 1px solid $main-border;
+ border-radius: 3px;
+ background-color: $bg-light-grey;
+
+ &::placeholder,
+ &::-webkit-input-placeholder,
+ &::-ms-input-placeholder {
+ color: $font--grey;
+ }
+
+ &:focus {
+ border: 1px solid $border--gray;
+ }
+ }
+ }
+
+ button {
+ padding: 8px;
+ width: 100%;
+ border-radius: 4px;
+ background-color: $btn--blue;
+ color: #fff;
+ font-weight: 600;
+ }
+ }
+
+ .find-pw {
+ font-size: 13px;
+ }
+
+ button:disabled,
+ input:disabled {
+ opacity: 0.3;
+ pointer-events: none;
+ }
+} | Unknown | - & ์ฐ์ฐ์ ํ์ฉ ๊ตฟ์
๋๋ค! |
@@ -0,0 +1,55 @@
+import React, { Component } from 'react';
+import { Link } from 'react-router-dom';
+import './Comment.scss';
+
+class Comment extends Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ isLiked: false,
+ };
+ }
+
+ likeComment = () => {
+ this.setState({ isLiked: !this.state.isLiked });
+ };
+
+ render() {
+ const { isLiked } = this.state;
+ const { info, handleClick } = this.props;
+
+ return (
+ <p className="feed__comment align-item-center">
+ <span className="user-name">{info.writer}</span>
+ <Link to="/main-yeseul">{info.tagId ? `@${info.tagId}` : ''}</Link>
+ {info.content}
+ <button
+ type="button"
+ className="delete-btn"
+ onClick={() => handleClick(info.id)}
+ >
+ x
+ </button>
+ <button
+ className={
+ isLiked ? 'like-btn align-right clicked' : 'like-btn align-right '
+ }
+ onClick={this.likeComment}
+ >
+ <svg
+ version="1.1"
+ id="Capa_1"
+ xmlns="http://www.w3.org/2000/svg"
+ xmlnsXlink="http://www.w3.org/1999/xlink"
+ viewBox="-50 -45 580 580"
+ xmlSpace="preserve"
+ >
+ <path d="M376,30c-27.783,0-53.255,8.804-75.707,26.168c-21.525,16.647-35.856,37.85-44.293,53.268c-8.437-15.419-22.768-36.621-44.293-53.268C189.255,38.804,163.783,30,136,30C58.468,30,0,93.417,0,177.514c0,90.854,72.943,153.015,183.369,247.118c18.752,15.981,40.007,34.095,62.099,53.414C248.38,480.596,252.12,482,256,482s7.62-1.404,10.532-3.953c22.094-19.322,43.348-37.435,62.111-53.425C439.057,330.529,512,268.368,512,177.514C512,93.417,453.532,30,376,30z" />
+ </svg>
+ </button>
+ </p>
+ );
+ }
+}
+
+export default Comment; | JavaScript | - id ๊ฐ์ ํ๋ก์ ํธ ์ ์ฒด ๋ด์์ ์ ์ผํด์ผํ๊ธฐ ๋๋ฌธ์, ๊ผญ ํ์ํ ๊ฒฝ์ฐ์๋ง ์ฌ์ฉํด์ฃผ์ธ์!
- id ๋์ ์ onClick ์ด๋ฒคํธ์ ๋ฐ๋ก ์ธ์๋ฅผ ๋๊ฒจ์ฃผ์ค ์๋ ์์ต๋๋ค. ์ฐธ๊ณ ํด์ฃผ์ธ์!
```js
onClick = {() => this.props.handleClick(info.id)}
``` |
@@ -0,0 +1,140 @@
+import React, { Component } from 'react';
+import { Link } from 'react-router-dom';
+import User from '../User/User';
+import Comment from '../Comment/Comment';
+import IconButton from '../Button/IconButton';
+import { API } from '../../../../../config';
+import './Feed.scss';
+
+class Feed extends Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ inputComment: '',
+ commentId: 0,
+ comments: [],
+ };
+ }
+
+ componentDidMount() {
+ const { feedId } = this.props;
+ fetch(API.COMMENT)
+ .then(comments => comments.json())
+ .then(comments => {
+ this.setState({
+ commentId: comments.length + 1,
+ comments: comments.filter(comment => comment.feedId === feedId),
+ });
+ });
+ }
+
+ handleInput = e => {
+ this.setState({ inputComment: e.target.value });
+ };
+
+ addComment = e => {
+ const { inputComment, commentId, comments } = this.state;
+
+ e.preventDefault();
+ this.setState({
+ inputComment: '',
+ commentId: commentId + 1,
+ comments: [
+ ...comments,
+ {
+ id: commentId.toString(),
+ writer: this.props.userName,
+ content: inputComment,
+ tagId: '',
+ },
+ ],
+ });
+ };
+
+ deleteComment = clickedId => {
+ const { comments } = this.state;
+ this.setState({
+ comments: comments.filter(comment => comment.id !== clickedId),
+ });
+ };
+
+ render() {
+ const { inputComment, comments } = this.state;
+ const { writer, contents } = this.props;
+
+ return (
+ <article className="feed give-border">
+ <header className="feed__header">
+ <User size="small" user={writer}>
+ <IconButton
+ className="feed__header__more-icon align-right"
+ info={{ name: '๋๋ณด๊ธฐ', fileName: 'more.svg' }}
+ />
+ </User>
+ </header>
+ <div className="feed__image">
+ <img
+ alt={`by ${writer.name} on ${contents.date}`}
+ src={contents.postedImage}
+ />
+ </div>
+ <div className="feed__btns">
+ <button type="button">
+ <img
+ alt="์ข์์"
+ src="https://s3.ap-northeast-2.amazonaws.com/cdn.wecode.co.kr/bearu/heart.png"
+ />
+ </button>
+ <IconButton info={{ name: '๋๊ธ', fileName: 'comment.svg' }} />
+ <IconButton info={{ name: '๊ณต์ ํ๊ธฐ', fileName: 'send.svg' }} />
+ <IconButton
+ className="align-right"
+ info={{ name: '๋ถ๋งํฌ', fileName: 'bookmark.svg' }}
+ />
+ </div>
+ <p className="feed__likes-number">
+ <Link to="/main-yeseul">{`์ข์์ ${contents.likesNum}๊ฐ`}</Link>
+ </p>
+ <div className="feed__description">
+ <p>
+ <span className="user-name">{writer.name}</span>
+ <span>{contents.description}</span>
+ </p>
+ </div>
+ <div className="feed__comments">
+ {comments.map(comment => (
+ <Comment
+ key={comment.id}
+ info={comment}
+ handleClick={this.deleteComment}
+ />
+ ))}
+ </div>
+ <form
+ className="feed__form align-item-center space-between"
+ name="commentForm"
+ >
+ <IconButton info={{ name: '์ด๋ชจํฐ์ฝ', fileName: 'emoticon.svg' }} />
+ <input
+ type="text"
+ placeholder="๋๊ธ ๋ฌ๊ธฐ..."
+ value={inputComment}
+ className="feed__input-comment"
+ name="inputComment"
+ onChange={this.handleInput}
+ />
+ <input
+ type="submit"
+ className="feed__submit-comment"
+ name="submitComment"
+ value="๊ฒ์"
+ disabled={!(inputComment.length > 0)}
+ onClick={this.addComment}
+ />
+ </form>
+ </article>
+ );
+ }
+}
+
+export default Feed; | JavaScript | - get ๋ฉ์๋๋ ๊ธฐ๋ณธ ๋ฉ์๋์ด๊ธฐ ๋๋ฌธ์ ์๋ตํด์ฃผ์ค ์ ์์ต๋๋ค.
```suggestion
fetch('/data/Yeseul/commentData.json')
``` |
@@ -0,0 +1,140 @@
+import React, { Component } from 'react';
+import { Link } from 'react-router-dom';
+import User from '../User/User';
+import Comment from '../Comment/Comment';
+import IconButton from '../Button/IconButton';
+import { API } from '../../../../../config';
+import './Feed.scss';
+
+class Feed extends Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ inputComment: '',
+ commentId: 0,
+ comments: [],
+ };
+ }
+
+ componentDidMount() {
+ const { feedId } = this.props;
+ fetch(API.COMMENT)
+ .then(comments => comments.json())
+ .then(comments => {
+ this.setState({
+ commentId: comments.length + 1,
+ comments: comments.filter(comment => comment.feedId === feedId),
+ });
+ });
+ }
+
+ handleInput = e => {
+ this.setState({ inputComment: e.target.value });
+ };
+
+ addComment = e => {
+ const { inputComment, commentId, comments } = this.state;
+
+ e.preventDefault();
+ this.setState({
+ inputComment: '',
+ commentId: commentId + 1,
+ comments: [
+ ...comments,
+ {
+ id: commentId.toString(),
+ writer: this.props.userName,
+ content: inputComment,
+ tagId: '',
+ },
+ ],
+ });
+ };
+
+ deleteComment = clickedId => {
+ const { comments } = this.state;
+ this.setState({
+ comments: comments.filter(comment => comment.id !== clickedId),
+ });
+ };
+
+ render() {
+ const { inputComment, comments } = this.state;
+ const { writer, contents } = this.props;
+
+ return (
+ <article className="feed give-border">
+ <header className="feed__header">
+ <User size="small" user={writer}>
+ <IconButton
+ className="feed__header__more-icon align-right"
+ info={{ name: '๋๋ณด๊ธฐ', fileName: 'more.svg' }}
+ />
+ </User>
+ </header>
+ <div className="feed__image">
+ <img
+ alt={`by ${writer.name} on ${contents.date}`}
+ src={contents.postedImage}
+ />
+ </div>
+ <div className="feed__btns">
+ <button type="button">
+ <img
+ alt="์ข์์"
+ src="https://s3.ap-northeast-2.amazonaws.com/cdn.wecode.co.kr/bearu/heart.png"
+ />
+ </button>
+ <IconButton info={{ name: '๋๊ธ', fileName: 'comment.svg' }} />
+ <IconButton info={{ name: '๊ณต์ ํ๊ธฐ', fileName: 'send.svg' }} />
+ <IconButton
+ className="align-right"
+ info={{ name: '๋ถ๋งํฌ', fileName: 'bookmark.svg' }}
+ />
+ </div>
+ <p className="feed__likes-number">
+ <Link to="/main-yeseul">{`์ข์์ ${contents.likesNum}๊ฐ`}</Link>
+ </p>
+ <div className="feed__description">
+ <p>
+ <span className="user-name">{writer.name}</span>
+ <span>{contents.description}</span>
+ </p>
+ </div>
+ <div className="feed__comments">
+ {comments.map(comment => (
+ <Comment
+ key={comment.id}
+ info={comment}
+ handleClick={this.deleteComment}
+ />
+ ))}
+ </div>
+ <form
+ className="feed__form align-item-center space-between"
+ name="commentForm"
+ >
+ <IconButton info={{ name: '์ด๋ชจํฐ์ฝ', fileName: 'emoticon.svg' }} />
+ <input
+ type="text"
+ placeholder="๋๊ธ ๋ฌ๊ธฐ..."
+ value={inputComment}
+ className="feed__input-comment"
+ name="inputComment"
+ onChange={this.handleInput}
+ />
+ <input
+ type="submit"
+ className="feed__submit-comment"
+ name="submitComment"
+ value="๊ฒ์"
+ disabled={!(inputComment.length > 0)}
+ onClick={this.addComment}
+ />
+ </form>
+ </article>
+ );
+ }
+}
+
+export default Feed; | JavaScript | - ๋ถ๋ณ์ฑ ์ ์ง์ผ์ฃผ์
จ๋ค์! ๐ ๐ |
@@ -0,0 +1,140 @@
+import React, { Component } from 'react';
+import { Link } from 'react-router-dom';
+import User from '../User/User';
+import Comment from '../Comment/Comment';
+import IconButton from '../Button/IconButton';
+import { API } from '../../../../../config';
+import './Feed.scss';
+
+class Feed extends Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ inputComment: '',
+ commentId: 0,
+ comments: [],
+ };
+ }
+
+ componentDidMount() {
+ const { feedId } = this.props;
+ fetch(API.COMMENT)
+ .then(comments => comments.json())
+ .then(comments => {
+ this.setState({
+ commentId: comments.length + 1,
+ comments: comments.filter(comment => comment.feedId === feedId),
+ });
+ });
+ }
+
+ handleInput = e => {
+ this.setState({ inputComment: e.target.value });
+ };
+
+ addComment = e => {
+ const { inputComment, commentId, comments } = this.state;
+
+ e.preventDefault();
+ this.setState({
+ inputComment: '',
+ commentId: commentId + 1,
+ comments: [
+ ...comments,
+ {
+ id: commentId.toString(),
+ writer: this.props.userName,
+ content: inputComment,
+ tagId: '',
+ },
+ ],
+ });
+ };
+
+ deleteComment = clickedId => {
+ const { comments } = this.state;
+ this.setState({
+ comments: comments.filter(comment => comment.id !== clickedId),
+ });
+ };
+
+ render() {
+ const { inputComment, comments } = this.state;
+ const { writer, contents } = this.props;
+
+ return (
+ <article className="feed give-border">
+ <header className="feed__header">
+ <User size="small" user={writer}>
+ <IconButton
+ className="feed__header__more-icon align-right"
+ info={{ name: '๋๋ณด๊ธฐ', fileName: 'more.svg' }}
+ />
+ </User>
+ </header>
+ <div className="feed__image">
+ <img
+ alt={`by ${writer.name} on ${contents.date}`}
+ src={contents.postedImage}
+ />
+ </div>
+ <div className="feed__btns">
+ <button type="button">
+ <img
+ alt="์ข์์"
+ src="https://s3.ap-northeast-2.amazonaws.com/cdn.wecode.co.kr/bearu/heart.png"
+ />
+ </button>
+ <IconButton info={{ name: '๋๊ธ', fileName: 'comment.svg' }} />
+ <IconButton info={{ name: '๊ณต์ ํ๊ธฐ', fileName: 'send.svg' }} />
+ <IconButton
+ className="align-right"
+ info={{ name: '๋ถ๋งํฌ', fileName: 'bookmark.svg' }}
+ />
+ </div>
+ <p className="feed__likes-number">
+ <Link to="/main-yeseul">{`์ข์์ ${contents.likesNum}๊ฐ`}</Link>
+ </p>
+ <div className="feed__description">
+ <p>
+ <span className="user-name">{writer.name}</span>
+ <span>{contents.description}</span>
+ </p>
+ </div>
+ <div className="feed__comments">
+ {comments.map(comment => (
+ <Comment
+ key={comment.id}
+ info={comment}
+ handleClick={this.deleteComment}
+ />
+ ))}
+ </div>
+ <form
+ className="feed__form align-item-center space-between"
+ name="commentForm"
+ >
+ <IconButton info={{ name: '์ด๋ชจํฐ์ฝ', fileName: 'emoticon.svg' }} />
+ <input
+ type="text"
+ placeholder="๋๊ธ ๋ฌ๊ธฐ..."
+ value={inputComment}
+ className="feed__input-comment"
+ name="inputComment"
+ onChange={this.handleInput}
+ />
+ <input
+ type="submit"
+ className="feed__submit-comment"
+ name="submitComment"
+ value="๊ฒ์"
+ disabled={!(inputComment.length > 0)}
+ onClick={this.addComment}
+ />
+ </form>
+ </article>
+ );
+ }
+}
+
+export default Feed; | JavaScript | - setState ๊ฐ ๊ธฐ์กด์ state ๊ฐ์ **๋ณํฉ** ํ๋ ์คํผ๋ ์ด์
์ด๊ธฐ ๋๋ฌธ์, ...this.state ๋ฅผ ํด์ฃผ์ค ํ์๊ฐ ์์ต๋๋ค.
```suggestion
this.setState({
comments: comments.filter(comment => comment.id !== clickedId),
});
``` |
@@ -2,12 +2,11 @@ import styled from '@emotion/styled';
import { useRouter } from 'next/router';
import React, { useCallback, useMemo } from 'react';
import { FieldValues } from 'react-hook-form';
-import { useMutation } from 'react-query';
import { useRecoilValue } from 'recoil';
import { useGetFlavors } from '@/apis/flavors';
-import { ICreateReviewPayload, postReview } from '@/apis/review';
-import { uploadImage } from '@/apis/upload/uploadImage';
+import { ICreateReviewPayload, useCreateReviewMutation } from '@/apis/review';
+import { useUploadImageMutation } from '@/apis/upload/uploadImage';
import BottomFloatingButtonArea from '@/components/BottomFloatingButtonArea';
import { BOTTOM_FLOATING_BUTTON_AREA_HEIGHT } from '@/components/BottomFloatingButtonArea/BottomFloatingButtonArea';
import Button, { ButtonCount } from '@/components/Button';
@@ -39,8 +38,8 @@ const ReviewDetailContainer: React.FC<RecordThirdStepContainerProps> = ({
const router = useRouter();
const reviewForm = useRecoilValue($reviewForm);
const { data: flavors } = useGetFlavors();
- const { mutateAsync: uploadImageMutation } = useMutation(uploadImage);
- const { mutateAsync: createReviewMutation } = useMutation(postReview);
+ const { uploadImage } = useUploadImageMutation();
+ const { createReview } = useCreateReviewMutation();
// const { mutateAsync: updateRecordMutation } = useMutation(updateRecord, {
// onSuccess: () => {
// router.back();
@@ -60,25 +59,25 @@ const ReviewDetailContainer: React.FC<RecordThirdStepContainerProps> = ({
const handleImageUpload = useCallback(
async (image: FormData) => {
- const { imageUrl } = await uploadImageMutation(image);
+ const { imageUrl } = await uploadImage(image);
return imageUrl;
},
- [uploadImageMutation],
+ [uploadImage],
);
const handleCreateSubmit = useCallback(
(data: FieldValues) => {
- createReviewMutation(
+ createReview(
{
...reviewForm,
...data,
- beerId: beer.id,
+ beerId: beer?.id,
} as ICreateReviewPayload,
{ onSuccess: (_data) => router.push(`/record/ticket/${_data.id}?type=${NEW_TYPE}`) },
);
},
- [createReviewMutation, reviewForm, beer.id, router],
+ [createReview, reviewForm, beer?.id, router],
);
// const handleUpdateSubmit = useCallback(
@@ -112,7 +111,7 @@ const ReviewDetailContainer: React.FC<RecordThirdStepContainerProps> = ({
>
<StyledWrapper>
<h2>{'๋น์ ๋ง์ ๋งฅ์ฃผ ์ด์ผ๊ธฐ๋ ๋ค๋ ค์ฃผ์ธ์'}</h2>
- <p className="body-1">{beer.korName}</p>
+ <p className="body-1">{beer?.korName}</p>
<ImageUploadField
name="imageUrl"
beer={beer} | Unknown | @hy57in
mutation๋ ํ ๋ฒ ๋ํํด์ ์ฌ์ฉํ๋๊ฑด ์ด๋ ์ ๊ฐ์?
```typescript
export const useCreateReviewMutation = () => {
const cache = useQueryClient();
const { mutateAsync: createReviewMutation, ...rest } = useMutation(createReview, {
onSuccess: async () => {
await cache.invalidateQueries(queryKeyFactory.GET_REVIEW);
},
});
return {
createReview: createReviewMutation,
...rest,
};
};
``` |
@@ -2,12 +2,11 @@ import styled from '@emotion/styled';
import { useRouter } from 'next/router';
import React, { useCallback, useMemo } from 'react';
import { FieldValues } from 'react-hook-form';
-import { useMutation } from 'react-query';
import { useRecoilValue } from 'recoil';
import { useGetFlavors } from '@/apis/flavors';
-import { ICreateReviewPayload, postReview } from '@/apis/review';
-import { uploadImage } from '@/apis/upload/uploadImage';
+import { ICreateReviewPayload, useCreateReviewMutation } from '@/apis/review';
+import { useUploadImageMutation } from '@/apis/upload/uploadImage';
import BottomFloatingButtonArea from '@/components/BottomFloatingButtonArea';
import { BOTTOM_FLOATING_BUTTON_AREA_HEIGHT } from '@/components/BottomFloatingButtonArea/BottomFloatingButtonArea';
import Button, { ButtonCount } from '@/components/Button';
@@ -39,8 +38,8 @@ const ReviewDetailContainer: React.FC<RecordThirdStepContainerProps> = ({
const router = useRouter();
const reviewForm = useRecoilValue($reviewForm);
const { data: flavors } = useGetFlavors();
- const { mutateAsync: uploadImageMutation } = useMutation(uploadImage);
- const { mutateAsync: createReviewMutation } = useMutation(postReview);
+ const { uploadImage } = useUploadImageMutation();
+ const { createReview } = useCreateReviewMutation();
// const { mutateAsync: updateRecordMutation } = useMutation(updateRecord, {
// onSuccess: () => {
// router.back();
@@ -60,25 +59,25 @@ const ReviewDetailContainer: React.FC<RecordThirdStepContainerProps> = ({
const handleImageUpload = useCallback(
async (image: FormData) => {
- const { imageUrl } = await uploadImageMutation(image);
+ const { imageUrl } = await uploadImage(image);
return imageUrl;
},
- [uploadImageMutation],
+ [uploadImage],
);
const handleCreateSubmit = useCallback(
(data: FieldValues) => {
- createReviewMutation(
+ createReview(
{
...reviewForm,
...data,
- beerId: beer.id,
+ beerId: beer?.id,
} as ICreateReviewPayload,
{ onSuccess: (_data) => router.push(`/record/ticket/${_data.id}?type=${NEW_TYPE}`) },
);
},
- [createReviewMutation, reviewForm, beer.id, router],
+ [createReview, reviewForm, beer?.id, router],
);
// const handleUpdateSubmit = useCallback(
@@ -112,7 +111,7 @@ const ReviewDetailContainer: React.FC<RecordThirdStepContainerProps> = ({
>
<StyledWrapper>
<h2>{'๋น์ ๋ง์ ๋งฅ์ฃผ ์ด์ผ๊ธฐ๋ ๋ค๋ ค์ฃผ์ธ์'}</h2>
- <p className="body-1">{beer.korName}</p>
+ <p className="body-1">{beer?.korName}</p>
<ImageUploadField
name="imageUrl"
beer={beer} | Unknown | @hy57in
`useGetReviewsByBeer` ๋ queryKey๋ฅผ queryKeyFactory์์ ๊ฐ์ ธ์ค๋ ๋ฐฉ์์ผ๋ก ๋ณ๊ฒฝํ๋๊ฑฐ ์ด๋จ๊น์!?
ref
- https://github.com/beerair/beerair-web/blob/8a3fb178139646a813eac410820e31846c3460c3/src/commons/queryKeyFactory.ts |
@@ -2,12 +2,11 @@ import styled from '@emotion/styled';
import { useRouter } from 'next/router';
import React, { useCallback, useMemo } from 'react';
import { FieldValues } from 'react-hook-form';
-import { useMutation } from 'react-query';
import { useRecoilValue } from 'recoil';
import { useGetFlavors } from '@/apis/flavors';
-import { ICreateReviewPayload, postReview } from '@/apis/review';
-import { uploadImage } from '@/apis/upload/uploadImage';
+import { ICreateReviewPayload, useCreateReviewMutation } from '@/apis/review';
+import { useUploadImageMutation } from '@/apis/upload/uploadImage';
import BottomFloatingButtonArea from '@/components/BottomFloatingButtonArea';
import { BOTTOM_FLOATING_BUTTON_AREA_HEIGHT } from '@/components/BottomFloatingButtonArea/BottomFloatingButtonArea';
import Button, { ButtonCount } from '@/components/Button';
@@ -39,8 +38,8 @@ const ReviewDetailContainer: React.FC<RecordThirdStepContainerProps> = ({
const router = useRouter();
const reviewForm = useRecoilValue($reviewForm);
const { data: flavors } = useGetFlavors();
- const { mutateAsync: uploadImageMutation } = useMutation(uploadImage);
- const { mutateAsync: createReviewMutation } = useMutation(postReview);
+ const { uploadImage } = useUploadImageMutation();
+ const { createReview } = useCreateReviewMutation();
// const { mutateAsync: updateRecordMutation } = useMutation(updateRecord, {
// onSuccess: () => {
// router.back();
@@ -60,25 +59,25 @@ const ReviewDetailContainer: React.FC<RecordThirdStepContainerProps> = ({
const handleImageUpload = useCallback(
async (image: FormData) => {
- const { imageUrl } = await uploadImageMutation(image);
+ const { imageUrl } = await uploadImage(image);
return imageUrl;
},
- [uploadImageMutation],
+ [uploadImage],
);
const handleCreateSubmit = useCallback(
(data: FieldValues) => {
- createReviewMutation(
+ createReview(
{
...reviewForm,
...data,
- beerId: beer.id,
+ beerId: beer?.id,
} as ICreateReviewPayload,
{ onSuccess: (_data) => router.push(`/record/ticket/${_data.id}?type=${NEW_TYPE}`) },
);
},
- [createReviewMutation, reviewForm, beer.id, router],
+ [createReview, reviewForm, beer?.id, router],
);
// const handleUpdateSubmit = useCallback(
@@ -112,7 +111,7 @@ const ReviewDetailContainer: React.FC<RecordThirdStepContainerProps> = ({
>
<StyledWrapper>
<h2>{'๋น์ ๋ง์ ๋งฅ์ฃผ ์ด์ผ๊ธฐ๋ ๋ค๋ ค์ฃผ์ธ์'}</h2>
- <p className="body-1">{beer.korName}</p>
+ <p className="body-1">{beer?.korName}</p>
<ImageUploadField
name="imageUrl"
beer={beer} | Unknown | [bf34ee2](https://github.com/beerair/beerair-web/pull/162/commits/bf34ee2ba98545a4e64603f0bdad6d5195f50a47)
๋ง๋ค์ด๋์ queryKeyFactory ๋ฅผ ์๊ณ ์์๋ค์. ํด๋น๋ถ๋ถ ์์ ํ์ต๋๋ค!
mutaion๋ ๋ํํด์ ์์ ํ์ต๋๋ค! |
@@ -0,0 +1,45 @@
+import { useMutation, useQueryClient } from 'react-query';
+
+import request from '@/commons/axios';
+import { queryKeyFactory } from '@/commons/queryKeyFactory';
+import { IBaseResponse, IReview } from '@/types';
+
+/**
+ * ๋ฆฌ๋ทฐ ๋ฑ๋ก
+ */
+
+export interface ICreateReviewResponseData extends IBaseResponse<IReview> {}
+
+export interface ICreateReviewPayload {
+ beerId: number;
+ content: string;
+ feelStatus: number;
+ imageUrl: string;
+ isPublic: boolean;
+ flavorIds: number[];
+}
+
+export const createReview = async (payload: ICreateReviewPayload) => {
+ const res = await request<ICreateReviewResponseData>({
+ method: 'post',
+ url: '/api/v1/reviews',
+ data: { payload },
+ });
+
+ return res.data;
+};
+
+export const useCreateReviewMutation = () => {
+ const cache = useQueryClient();
+
+ const { mutateAsync: createReviewMutation, ...rest } = useMutation(createReview, {
+ onSuccess: async () => {
+ await cache.invalidateQueries(queryKeyFactory.GET_REVIEW());
+ },
+ });
+
+ return {
+ createReview: createReviewMutation,
+ ...rest,
+ };
+}; | TypeScript | @hy57in
๋ฆฌ๋ทฐ ์์ฑ๋๊ณ ํธ์ถ๋๋ success ํจ์ ๋ด๋ถ์์๋ ๋ฆฌ๋ทฐ ๋ฆฌ์คํธ๋ฅผ invalidate ์์ผ์ผํ์ง ์๋์..? |
@@ -0,0 +1,45 @@
+import { useMutation, useQueryClient } from 'react-query';
+
+import request from '@/commons/axios';
+import { queryKeyFactory } from '@/commons/queryKeyFactory';
+import { IBaseResponse, IReview } from '@/types';
+
+/**
+ * ๋ฆฌ๋ทฐ ๋ฑ๋ก
+ */
+
+export interface ICreateReviewResponseData extends IBaseResponse<IReview> {}
+
+export interface ICreateReviewPayload {
+ beerId: number;
+ content: string;
+ feelStatus: number;
+ imageUrl: string;
+ isPublic: boolean;
+ flavorIds: number[];
+}
+
+export const createReview = async (payload: ICreateReviewPayload) => {
+ const res = await request<ICreateReviewResponseData>({
+ method: 'post',
+ url: '/api/v1/reviews',
+ data: { payload },
+ });
+
+ return res.data;
+};
+
+export const useCreateReviewMutation = () => {
+ const cache = useQueryClient();
+
+ const { mutateAsync: createReviewMutation, ...rest } = useMutation(createReview, {
+ onSuccess: async () => {
+ await cache.invalidateQueries(queryKeyFactory.GET_REVIEW());
+ },
+ });
+
+ return {
+ createReview: createReviewMutation,
+ ...rest,
+ };
+}; | TypeScript | ์ํซ..! ๋ฆฌ๋ทฐ ๋ฆฌ์คํธ๋ฅผ invalidate ํ๋ ๊ฒ์ผ๋ก ์์ ํ์ต๋๋ค. ๋ฆฌ๋ทฐ ๊ฐ์ฌํฉ๋๋ค ๐ซข |
@@ -97,12 +97,12 @@ const BeerTicketTitle: React.FC<BeerTicketTitleProps> = ({
{sliceAndUpperCase(beer?.country?.engName || 'non', 3)}
</span>
<div className="ticket-detail">
- {`${beer?.alcohol?.toFixed(1)}%`}
+ {beer?.alcohol ? `${beer.alcohol?.toFixed(1)}%` : '-'}
<span className="ticket-detail-split-dot">{'โข'}</span>
- {beer?.type?.korName}
+ {beer?.type?.korName ?? '-'}
</div>
</div>
- <span className="ticket-beer-name">{beer?.korName}</span>
+ <span className="ticket-beer-name">{beer?.korName ?? '-'}</span>
</StyledBeerTicketTitle>
);
}; | Unknown | '?' ์์ด๋ ๊ด์ฐฎ์ ๊ฒ ๊ฐ์์!
```suggestion
{beer?.alcohol ? `${beer.alcohol.toFixed(1)}%` : '-'}
``` |
@@ -5,16 +5,18 @@ export default class ReviewMapper {
constructor(private readonly review: ReviewAllProperties) {}
toDomain() {
+ if (!this.review) return null;
+
return new Review({
id: this.review.id,
- writerId: this.review.writerId,
- writer: this.review.writer,
- ownerId: this.review.ownerId,
+ writerId: this.review?.writerId,
+ writer: this.review?.writer,
+ ownerId: this.review?.ownerId,
rating: this.review.rating,
content: this.review.content,
- planId: this.review.planId,
+ planId: this.review?.planId,
createdAt: this.review.createdAt,
- updatedAt: this.review.updatedAt
+ updatedAt: this.review?.updatedAt
});
}
} | TypeScript | ์ ๋ ์ด๋ ๊ฒ ํ๋๊ฑฐ ๊ฐ๊ธด ํ๋ฐ if๋ฌธ ์์์ null ๊ฐ๊ณผ undefined๊ฐ์ ์ฒดํฌํด์ ๋ฆฌํด๋ฌธ ์ดํ๋ก ์ต์
๋๋ก ์ค ํ์๋ ์๋๊ฑฐ ๊ฐ์์ |
@@ -1,4 +1,5 @@
import { IsInt, IsNotEmpty, IsPositive, IsString, IsUUID } from 'class-validator';
+import { Type } from 'class-transformer';
export class CreateReviewDTO {
@IsUUID()
@@ -18,3 +19,13 @@ export class CreateReviewDTO {
@IsNotEmpty()
planId: string;
}
+
+export class GetReviewsQueryDTO {
+ @Type(() => Number)
+ @IsInt()
+ page: number = 1;
+
+ @Type(() => Number)
+ @IsInt()
+ pageSize: number = 5;
+} | TypeScript | ๊ธฐ๋ณธ๊ฐ์ ์ฃผ๋ ค๋ฉด isOptional์ด ์์ด์ผ๋์ง ์๋์? ํ
์คํธํด์ ๊ด์ฐฎ๋๊ฐ์? |
@@ -14,13 +14,13 @@ export interface ReviewProperties {
export interface ReviewAllProperties {
id?: string;
- writerId: string;
+ writerId?: string;
writer?: UserReference;
- ownerId: string;
+ ownerId?: string;
owner?: UserReference;
rating: number;
content: string;
- planId: string;
+ planId?: string;
plan?: PlanReference;
createdAt?: Date;
updatedAt?: Date; | TypeScript | ํ๋์ด ์ญ์ ๋๋๋ผ๋ ๋ฆฌ๋ทฐ๋ ๋จ์์๋ ํ๋ก์ธ์ค์ธ๊ฐ์?
๊ทธ๋ ๋ค๋ ์ ์ ํ์ ์ ํฌ๋ ๋
ผ๋ฆฌ์ญ์ ๋ผ์ planId๋ ์ต์
๋์ด ์๋์ฌ๋ ๋ ๊ฑฐ๊ฐ์์.
ํ๋์ ์ต์
๋๋ก ์ ์งํด์ผ๊ฒ ๋ค์.
์ฌ๊ธฐ createdAt๊ณผ updatedAt์ด ์ต์
๋์ด ์๋์ฌ๋ ๊ด์ฐฎ์ง ์๋์? |
@@ -5,16 +5,18 @@ export default class ReviewMapper {
constructor(private readonly review: ReviewAllProperties) {}
toDomain() {
+ if (!this.review) return null;
+
return new Review({
id: this.review.id,
- writerId: this.review.writerId,
- writer: this.review.writer,
- ownerId: this.review.ownerId,
+ writerId: this.review?.writerId,
+ writer: this.review?.writer,
+ ownerId: this.review?.ownerId,
rating: this.review.rating,
content: this.review.content,
- planId: this.review.planId,
+ planId: this.review?.planId,
createdAt: this.review.createdAt,
- updatedAt: this.review.updatedAt
+ updatedAt: this.review?.updatedAt
});
}
} | TypeScript | ๋ฆฌํด๋ฌธ์ ์ต์
๋์ ์ ๋ฃ์ผ๋ฉด, ์๋ฅผ ๋ค๋ฉด ์ง๊ธ PR์ ์ฌ๋ฆฐ ๋ฆฌ๋ทฐ ๋ชฉ๋ก ์กฐํ ๋๋ writer ๋ฐ์ดํฐ๋ include๋ฅผ ํ์ง ์๊ณ ๋งคํํ๋๊น ๊ฐ์ด ์๋๋ฐ ๋ฌธ์ ์๋์??? |
@@ -1,4 +1,5 @@
import { IsInt, IsNotEmpty, IsPositive, IsString, IsUUID } from 'class-validator';
+import { Type } from 'class-transformer';
export class CreateReviewDTO {
@IsUUID()
@@ -18,3 +19,13 @@ export class CreateReviewDTO {
@IsNotEmpty()
planId: string;
}
+
+export class GetReviewsQueryDTO {
+ @Type(() => Number)
+ @IsInt()
+ page: number = 1;
+
+ @Type(() => Number)
+ @IsInt()
+ pageSize: number = 5;
+} | TypeScript | ๋ค ๋ค์ ํ
์คํธํด๋ดค๋๋ฐ ๋ฌธ์ ์์ด์! ์ ์ฐธ๊ณ ๋ก PlanQueryOptionDTO ์ฐธ๊ณ ํด์ ์์ฑํ์ต๋๋ค ใ
ใ
ใ
|
@@ -14,13 +14,13 @@ export interface ReviewProperties {
export interface ReviewAllProperties {
id?: string;
- writerId: string;
+ writerId?: string;
writer?: UserReference;
- ownerId: string;
+ ownerId?: string;
owner?: UserReference;
rating: number;
content: string;
- planId: string;
+ planId?: string;
plan?: PlanReference;
createdAt?: Date;
updatedAt?: Date; | TypeScript | ์ฌ์ค ์ด ์ธํฐํ์ด์ค๋ ์ค์ ํ๋ก์ธ์ค์์ ๋ฆฌ๋ทฐ ๊ฐ์ฒด๋ฅผ ์ด๋ฃจ๋ ๋ฐ์ ํ์ํ ํ๋๋ฅผ ๊ธฐ์ค์ผ๋ก ๋ง๋ค์ด์ rating, content ๋ง๊ณ ๋ ๋ค ์ต์
๋์
๋๋ค.. ์๋ฅผ ๋ค๋ฉด ์ง๊ธ ๋ง๋ API์ ๊ฒฝ์ฐ plan์ ๋ํ ๋ด์ฉ์ด ํ์์๊ธฐ ๋๋ฌธ์ planId๋ฅผ db์์ ๊ฐ์ ธ์ค์ง๋ ์๊ฑฐ๋ ์. ์ด์ ๋ง๋ค๊ฒ ๋ dreamer์ ๋ด๊ฐ ์์ฑํ ๋ฆฌ๋ทฐ ๋ชฉ๋ก์๋ ํ์ํ๊ณ ์. ์ต์
๋์ด ๋๋ฌด ๋ง์์ ํ์
์์ ์ฑ์ด ์ข ์ ๋งคํ๋ค๋ฉด ์ธํฐํ์ด์ค๋ฅผ ์์ ๋๋๊ฑฐ๋ ํด์ผํ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -5,16 +5,18 @@ export default class ReviewMapper {
constructor(private readonly review: ReviewAllProperties) {}
toDomain() {
+ if (!this.review) return null;
+
return new Review({
id: this.review.id,
- writerId: this.review.writerId,
- writer: this.review.writer,
- ownerId: this.review.ownerId,
+ writerId: this.review?.writerId,
+ writer: this.review?.writer,
+ ownerId: this.review?.ownerId,
rating: this.review.rating,
content: this.review.content,
- planId: this.review.planId,
+ planId: this.review?.planId,
createdAt: this.review.createdAt,
- updatedAt: this.review.updatedAt
+ updatedAt: this.review?.updatedAt
});
}
} | TypeScript | ์ ์ต์
๋์ review๊ฐ ์๋์ง ์ฒดํฌํ๋๊ฑฐ์ง ์๋์? |
@@ -1,4 +1,5 @@
import { IsInt, IsNotEmpty, IsPositive, IsString, IsUUID } from 'class-validator';
+import { Type } from 'class-transformer';
export class CreateReviewDTO {
@IsUUID()
@@ -18,3 +19,13 @@ export class CreateReviewDTO {
@IsNotEmpty()
planId: string;
}
+
+export class GetReviewsQueryDTO {
+ @Type(() => Number)
+ @IsInt()
+ page: number = 1;
+
+ @Type(() => Number)
+ @IsInt()
+ pageSize: number = 5;
+} | TypeScript | ๊ทธ๋ ๊ตฐ์,, |
@@ -14,13 +14,13 @@ export interface ReviewProperties {
export interface ReviewAllProperties {
id?: string;
- writerId: string;
+ writerId?: string;
writer?: UserReference;
- ownerId: string;
+ ownerId?: string;
owner?: UserReference;
rating: number;
content: string;
- planId: string;
+ planId?: string;
plan?: PlanReference;
createdAt?: Date;
updatedAt?: Date; | TypeScript | ์ดํดํ์ต๋๋ค |
@@ -14,13 +14,13 @@ export interface ReviewProperties {
export interface ReviewAllProperties {
id?: string;
- writerId: string;
+ writerId?: string;
writer?: UserReference;
- ownerId: string;
+ ownerId?: string;
owner?: UserReference;
rating: number;
content: string;
- planId: string;
+ planId?: string;
plan?: PlanReference;
createdAt?: Date;
updatedAt?: Date; | TypeScript | ๋๋๊ธฐ๋ณด๋จ ๊ทธ๋ฅ ์ต์
๋๋ก ํ์
๊ฐ์๋ฅผ ์ค์ด์ฃ |
@@ -5,16 +5,18 @@ export default class ReviewMapper {
constructor(private readonly review: ReviewAllProperties) {}
toDomain() {
+ if (!this.review) return null;
+
return new Review({
id: this.review.id,
- writerId: this.review.writerId,
- writer: this.review.writer,
- ownerId: this.review.ownerId,
+ writerId: this.review?.writerId,
+ writer: this.review?.writer,
+ ownerId: this.review?.ownerId,
rating: this.review.rating,
content: this.review.content,
- planId: this.review.planId,
+ planId: this.review?.planId,
createdAt: this.review.createdAt,
- updatedAt: this.review.updatedAt
+ updatedAt: this.review?.updatedAt
});
}
} | TypeScript | this.review์ ํด๋น ๊ฐ์ด ์์ผ๋ฉด undefined ๊ฐ์ ํ ๋นํ๋ค๊ณ ํฉ๋๋ค (ํน์๋ ํด์ ๋ค์ ์ฐพ์๋ดค์ต๋๋ค ใ
ใ
ใ
) |
@@ -0,0 +1,18 @@
+const categoryDao = require('../models/categoryDao');
+const error = require('../utils/error');
+
+const getCategory = async (type) => {
+ const categoryTypes = {
+ '์ง์ถ' : [1, 2, 3],
+ '์์
' : [4]
+ }
+
+ const categories = await categoryDao.getCategoriesByIds(categoryTypes[type]);
+ categories.map((category) => { category.type = type })
+
+ return categories;
+}
+
+module.exports = {
+ getCategory
+}
\ No newline at end of file | JavaScript | ```suggestion
const getCategory = async (type) => {
const categoryTypes = {
'์ง์ถ' : [1, 2, 4],
'์์
' : [3]
}
const categories = await categoryDao.getCategoriesByIds(categoryTypes[type]);
categories.map((category) => { category.type = type })
return categories
}
module.exports = { getCategory }
```
1. ์์
/์ง์ถ์ ํ์
๊ณผ categoryId๋ฅผ ๋ชจ๋ ํ๋์ฝ๋ฉ ํด๋๊ธฐ ๋ณด๋ค๋ ํ์
์ผ๋ก ๋ชจ์์ ์ ๋ฆฌํ์๋ ๋ฐฉ๋ฒ์ด ๋ณด๋ค ํ์ฅ์ฑ ์๊ณ , ๊ฐ๋
์ฑ๋ ๋์ ๊ฒ ๊ฐ์ต๋๋ค.
2. category๋ฅผ dao์์ ํ๋์ฉ for loop์ผ๋ก getCategory dao์ query๋ฅผ ๋ ๋ฆฌ์๊ธฐ๋ณด๋ค๋ getCategoriesByIds ์ด๋ผ๋ dao ํจ์๋ฅผ ๋ง๋์
์ ๋ฐฐ์ด์ ํต์งธ๋ก ์ธ์๋ก ๋ณด๋ด๋ ๊ฒ์ด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค.
๊ทธ๋์ dao๋จ SQL ์ฟผ๋ฆฌ๋ฌธ์์๋ ์ธ์๋ฅผ ๋ฐฐ์ด๋ก ๋ฐ์ผ์
์ ์ฌ๋ฌ ์นดํ
๊ณ ๋ฆฌ๋ฅผ ํ ๋ฒ์ SELECT ํ๋ ๋ฐฉ์์ ์ถ์ฒ๋๋ฆฝ๋๋ค.
Query ๋ฌธ์ ๋ณด๋ด๋ ํ์๋ฅผ 3ํ์์ 1ํ๋ก ์ค์ด๊ธฐ ์ํจ์
๋๋ค |
@@ -0,0 +1,20 @@
+const categoryService = require('../services/categoryService');
+const error = require('../utils/error');
+
+const getCategory = async (req, res) => {
+ try {
+ const { type } = req.query;
+ if (!type) {
+ error.throwErr(400, 'KEY_ERROR');
+ }
+ const categories = await categoryService.getCategory(type);
+ return res.status(200).json({message: 'GET_SUCCESS', 'category': categories});
+ } catch (err) {
+ console.error(err);
+ return res.status(err.statusCode || 500).json({message: err.message || 'INTERNAL_SERVER_ERROR'});
+ }
+}
+
+module.exports = {
+ getCategory
+}
\ No newline at end of file | JavaScript | ์๋ฌ ๋ฐ์์์ผ ๋ณด์
จ๋์? ๋ชจ๋ ์๋ฌ๊ฐ 'internal_server_error'๋ก ๋ ํ
๋ฐ, ์๋ํ์ ๋ฐ๊ฐ ๋ง์๊น์? |
@@ -0,0 +1,18 @@
+const categoryDao = require('../models/categoryDao');
+const error = require('../utils/error');
+
+const getCategory = async (type) => {
+ const categoryTypes = {
+ '์ง์ถ' : [1, 2, 3],
+ '์์
' : [4]
+ }
+
+ const categories = await categoryDao.getCategoriesByIds(categoryTypes[type]);
+ categories.map((category) => { category.type = type })
+
+ return categories;
+}
+
+module.exports = {
+ getCategory
+}
\ No newline at end of file | JavaScript | 3. ๊ทผ๋ณธ์ ์ธ ์ง๋ฌธ์ด ํ๋ ์๋๋ฐ, category๊ฐ flow_type_id๋ฅผ FK๋ก ๊ฐ์ง๊ณ ์์ผ๋ฉด, ํ๋์ฝ๋ฉ์ ์ํด๋ ๋ ๊ฒ ๊ฐ์๋ฐ FK ์์ฑํ์๋๊ฒ ์ข์ง ์์๊น์? ์ด๋ถ๋ถ์ ๋ฐฑ์๋ ํ ๊ฐ์ด ๋ผ์ด์ง์์ ์ ํ ๋ฒ ์ฐพ์์ ์ฃผ์ธ์! |
@@ -0,0 +1,20 @@
+const categoryService = require('../services/categoryService');
+const error = require('../utils/error');
+
+const getCategory = async (req, res) => {
+ try {
+ const { type } = req.query;
+ if (!type) {
+ error.throwErr(400, 'KEY_ERROR');
+ }
+ const categories = await categoryService.getCategory(type);
+ return res.status(200).json({message: 'GET_SUCCESS', 'category': categories});
+ } catch (err) {
+ console.error(err);
+ return res.status(err.statusCode || 500).json({message: err.message || 'INTERNAL_SERVER_ERROR'});
+ }
+}
+
+module.exports = {
+ getCategory
+}
\ No newline at end of file | JavaScript | ์ ํด๋น **error message** ๋ถ๋ถ ์์ ํ๊ฒ ์ต๋๋ค.
`=> 'INTERNAL_SERVER_ERROR' || err.message}` |
@@ -0,0 +1,14 @@
+const {DataSource} = require('typeorm');
+const dotenv = require('dotenv');
+dotenv.config();
+
+const appDataSource = new DataSource({
+ type : process.env.TYPEORM_CONNECTION,
+ host: process.env.TYPEORM_HOST,
+ port: process.env.TYPEORM_PORT,
+ username: process.env.TYPEORM_USERNAME,
+ password: process.env.TYPEORM_PASSWORD,
+ database: process.env.TYPEORM_DATABASE
+});
+
+module.exports = { appDataSource }
\ No newline at end of file | JavaScript | ๋ฐ์ํ๊ฒ ์ต๋๋ค! |
@@ -0,0 +1,213 @@
+<?xml version="1.0" encoding="utf-8"?>
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:tools="http://schemas.android.com/tools"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ tools:context=".ArchiveReviewFragment" >
+
+ <TextView
+ android:id="@+id/archive_review_main"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="30dp"
+ android:layout_centerHorizontal="true"
+ android:layout_gravity="center_horizontal"
+ android:text="๋ฆฌ๋ทฐ ์์ฑ"
+ android:textColor="@color/black"
+ android:textAlignment="center"
+ android:textSize="20dp"
+ android:textStyle="bold" />
+
+ <ImageButton
+ android:id="@+id/back_button"
+ android:layout_width="48dp"
+ android:layout_height="48dp"
+ android:layout_alignParentStart="true"
+ android:layout_marginStart="16dp"
+ android:layout_marginTop="21dp"
+ android:adjustViewBounds="true"
+ android:background="@android:color/transparent"
+ android:contentDescription="๋ค๋ก ๊ฐ๊ธฐ"
+ android:scaleType="centerInside"
+ android:src="@drawable/_2025_01_23_023248" />
+
+ <ImageButton
+ android:id="@+id/review_book_image"
+ android:layout_width="200dp"
+ android:layout_height="260dp"
+ android:layout_marginTop="25dp"
+ android:layout_below="@id/archive_review_main"
+ android:layout_centerHorizontal="true"
+ android:layout_gravity="center_horizontal" />
+
+ <TextView
+ android:id="@+id/review_book_text"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="140dp"
+ android:layout_below="@id/archive_review_main"
+ android:layout_centerHorizontal="true"
+ android:layout_gravity="center_horizontal"
+ android:text="์ฑ
ํ์ง"
+ android:textColor="@color/black"
+ android:textAlignment="center"
+ android:textSize="20dp"
+ android:textStyle="bold" />
+
+ <TextView
+ android:id="@+id/review_starRate"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="20dp"
+ android:layout_below="@+id/review_book_image"
+ android:layout_marginStart="30dp"
+ android:text="๋ณ์ "
+ android:textColor="@color/black"
+ android:textSize="15dp"
+ android:textStyle="bold" />
+
+ <RatingBar
+ android:id="@+id/ratingBar"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:scaleX="0.7"
+ android:scaleY="0.7"
+ android:layout_marginStart="-10dp"
+ android:layout_below="@id/review_starRate"
+ android:numStars="5"
+ android:stepSize="1"
+ android:rating="4" />
+
+ <TextView
+ android:id="@+id/write_review"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="8dp"
+ android:layout_below="@+id/ratingBar"
+ android:layout_marginStart="30dp"
+ android:text="์ฑ
๋ฆฌ๋ทฐ"
+ android:textColor="@color/black"
+ android:textSize="15dp"
+ android:textStyle="bold" />
+
+ <FrameLayout
+ android:id="@+id/reviewInput_layout"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:orientation="vertical"
+ android:paddingTop="8dp"
+ android:layout_below="@id/write_review">
+
+ <!-- ์์ฑํ๊ธฐ ๋ฒํผ -->
+ <Button
+ android:id="@+id/submitButton"
+ android:layout_width="115dp"
+ android:layout_height="30dp"
+ android:layout_gravity="end"
+ android:layout_marginEnd="40dp"
+ android:layout_marginBottom="30dp"
+ android:layout_marginTop="60dp"
+ android:elevation="5dp"
+ android:text="์์ฑํ๊ธฐ"
+ android:background="@drawable/button_border_gray"
+ android:textColor="#FFFFFF"
+ android:textSize="14dp"
+ android:padding="4dp" />
+
+ <!-- ๋ฆฌ๋ทฐ ์
๋ ฅ๋ -->
+ <EditText
+ android:id="@+id/reviewInput"
+ android:layout_width="match_parent"
+ android:layout_height="100dp"
+ android:layout_marginStart="30dp"
+ android:layout_marginEnd="30dp"
+ android:elevation="1dp"
+ android:hint="๋ฆฌ๋ทฐ๋ฅผ ์
๋ ฅํ์ธ์"
+ android:background="#EAEAEA"
+ android:padding="8dp"
+ android:textSize="16sp"
+ android:inputType="textMultiLine" />
+ </FrameLayout>
+
+ <TextView
+ android:id="@+id/favoriteLine"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="0dp"
+ android:layout_below="@+id/reviewInput_layout"
+ android:layout_marginStart="30dp"
+ android:text="๋ง์์ ๋๋ ํ ์ค"
+ android:textColor="@color/black"
+ android:textSize="15dp"
+ android:textStyle="bold" />
+
+ <FrameLayout
+ android:id="@+id/favoriteLine_layout"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:orientation="vertical"
+ android:paddingTop="8dp"
+ android:layout_below="@id/favoriteLine">
+
+ <Button
+ android:id="@+id/submitButton_2"
+ android:layout_width="115dp"
+ android:layout_height="30dp"
+ android:layout_gravity="end"
+ android:layout_marginEnd="40dp"
+ android:layout_marginBottom="30dp"
+ android:layout_marginTop="60dp"
+ android:elevation="5dp"
+ android:text="์์ฑํ๊ธฐ"
+ android:background="@drawable/button_border_gray"
+ android:textColor="#FFFFFF"
+ android:textSize="14dp"
+ android:padding="4dp" />
+
+ <EditText
+ android:id="@+id/favoriteLineInput"
+ android:layout_width="match_parent"
+ android:layout_height="100dp"
+ android:layout_marginStart="30dp"
+ android:layout_marginEnd="30dp"
+ android:elevation="1dp"
+ android:hint="๋ง์์ ๋๋ ํ ์ค์ ์
๋ ฅํ์ธ์"
+ android:background="#EAEAEA"
+ android:padding="8dp"
+ android:textSize="16sp"
+ android:inputType="textMultiLine" />
+
+ </FrameLayout>
+
+ <Button
+ android:id="@+id/see_more"
+ android:layout_width="115dp"
+ android:layout_height="30dp"
+ android:layout_below="@id/favoriteLine_layout"
+ android:layout_marginTop="30dp"
+ android:layout_marginStart="85dp"
+ android:background="@drawable/button_border_gray"
+ android:drawablePadding="4dp"
+ android:gravity="center_vertical"
+ android:text="๋๋ณด๊ธฐ"
+ android:textAlignment="center"
+ android:textSize="14dp"
+ android:textColor="#000000" />
+
+ <Button
+ android:id="@+id/store_review"
+ android:layout_width="115dp"
+ android:layout_height="30dp"
+ android:layout_below="@id/favoriteLine_layout"
+ android:layout_marginTop="30dp"
+ android:layout_marginStart="210dp"
+ android:background="@drawable/button_border"
+ android:drawablePadding="4dp"
+ android:gravity="center_vertical"
+ android:text="์ ์ฅํ๊ธฐ"
+ android:textAlignment="center"
+ android:textSize="14dp"
+ android:textColor="#000000" />
+
+
+</RelativeLayout>
\ No newline at end of file | Unknown | ์ฌ๊ธฐ์ ์ปจํ
์คํธ๋ .ArchiveReviewFragment๋ก ์ถ์ ๋ฉ๋๋ค. |
@@ -1,9 +1,14 @@
+import java.util.List;
import java.util.Scanner;
public class InputView {
private static final String INPUT_MONEY_MESSAGE = "๊ตฌ์
๊ธ์ก์ ์
๋ ฅํด ์ฃผ์ธ์.";
private static final String INPUT_WINNING_LOTTO_MESSAGE = "์ง๋ ์ฃผ ๋น์ฒจ ๋ฒํธ๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์.";
+ private static final String MANUAL_LOTTO_COUNT_MESSAGE = "์๋์ผ๋ก ๊ตฌ๋งคํ ๋ก๋ ์๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์.";
+ private static final String MANUAL_LOTTO_NUMBER_MESSAGE = "์๋์ผ๋ก ๊ตฌ๋งคํ ๋ฒํธ๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์.";
+
+ private static final String INPUT_BONUS_NUMBER_MESSAGE = "๋ณด๋์ค ๋ณผ์ ์
๋ ฅํด ์ฃผ์ธ์.";
private static Scanner scanner = new Scanner(System.in);
@@ -12,6 +17,30 @@ public static int inputMoney() {
return Integer.parseInt(scanner.nextLine());
}
+ public static int manualLottoCount() {
+ System.out.println(MANUAL_LOTTO_COUNT_MESSAGE);
+ return Integer.parseInt(scanner.nextLine());
+ }
+
+ public static List<LottoNumber> manualLotto(int i, int manualLottoCount) {
+ if (i == 0) {
+ System.out.println(MANUAL_LOTTO_NUMBER_MESSAGE);
+ }
+
+ String inputs = scanner.nextLine();
+ if (i != manualLottoCount - 1) {
+ scanner.nextLine();
+ }
+
+ return StringParsingUtils.parseToLottoNumber(inputs);
+ }
+
+ public static BonusNumber inputBonusNumber() {
+ System.out.println(INPUT_BONUS_NUMBER_MESSAGE);
+ int bonusNumber = Integer.parseInt(scanner.nextLine());
+ return new BonusNumber(new LottoNumber(bonusNumber));
+ }
+
public static String inputWinningLottoNumber() {
System.out.println(INPUT_WINNING_LOTTO_MESSAGE);
return scanner.nextLine(); | Java | ์ ํ๋ฆฌ์ผ์ด์
์คํ์ ์์ผ๋ณด๋ ์
๋ ฅ์ ์ฐ๋ฌ์ ๋ฐ๊ธฐ ๋๋ฌธ์ ํ ์ค ์
๋ ฅ์ ๋ฐ์ ํ ์
๋ ฅ์ ํ ๋ฒ ๋ ๊ธฐ๋ค๋ฆฌ๊ณ ์์ต๋๋ค! ์ด๋ค ์๋๋ก ์ฌ์ฉํ์ ๊ฑธ๊น์? |
@@ -9,19 +9,24 @@ public LottoGame() {
statistics = new TreeMap<>();
}
- public int inputMoney(int money) {
+ public int calculateLottoCount(int money) {
return lottoCount = money / Lotto.LOTTO_PRICE;
}
- public LottoTicket generateAutoLottoTicket() {
+ public LottoTicket generateLottoTicket(int manualLottoCount) {
List<Lotto> lottos = new ArrayList<>();
- for(int i = 0; i < lottoCount; i++) {
+
+ for (int i = 0; i < manualLottoCount; i++) {
+ lottos.add(ManualLottoGenerator.generate(i, manualLottoCount));
+ }
+
+ for(int i = manualLottoCount; i < lottoCount; i++) {
lottos.add(AutoLottoGenerator.generate());
}
- return generateLottoTicket(lottos);
+ return makeLottoTicket(lottos);
}
- private LottoTicket generateLottoTicket(List<Lotto> lottos) {
+ private LottoTicket makeLottoTicket(List<Lotto> lottos) {
return lottoTicket = new LottoTicket(lottos);
}
| Java | ์๋ ๋ก๋์ ์๋ ๋ก๋๋ฅผ ํจ๊ป ์์ฑํ๊ณ ์๋๋ฐ ์ด๋ฅผ ๋ถ๋ฆฌ์์ผ๋ณด๋ฉด ์ด๋จ๊น์?
```
List<Lotto> lottos = InputView.manualLotto(lottoCount);
OutputView.printLottoTicket(game.generateLottoTicket(lottos));
```
์ฝ๋ ์์ฒด๋ก generateLottoTicket์์ ์๋๋ก๋๊น์ง ์์ฑํด์ฃผ๋ ๊ฒ์ธ์ง ํน์ ์๋ํ๋๋ก ์๋ ๋ก๋์ ์๋ ๋ก๋๋ฅผ ํจ๊ป ์์ฑํ๋ ๊ฒ์ธ์ง ๋ฉ์๋๋ช
๋ง ๋ณด๊ณ ๋ ์๋ฏธ๊ฐ ์กฐ๊ธ ๋ชจํธํ๋ค๊ณ ์๊ฐ๋ฉ๋๋ค. (๊ฐ์ธ์ ์๊ฐ์ผ๋ก)
๊ทธ๋ฆฌ๊ณ ๋์ค์ ์๊ตฌ์ฌํญ์ด ๋ณ๊ฒฝ๋์ด `์๋ ๋ก๋ ์์ฑ๋ง` ํน์ `์๋ ๋ก๋ ์์ฑ๋ง` ๊ทธ๋ฆฌ๊ณ ์ง๊ธ๊ณผ ๊ฐ์ด `์๋ ๋ก๋์ ์๋ ๋ก๋๋ฅผ ์์ด์` ํ ์ ์๋๋ก ํ๋ ํํ๋ผ๋ฉด ๋ฉ์๋ ์์ฒด๋ก ์กฐ๊ธ ๋ ๋ถ๋ช
ํ ์๋ฏธ๋ฅผ ๊ฐ์ง๊ณ ๋ฉ์๋๋ฅผ ์ฌํ์ฉํ ์ ์์ ๊ฒ ๊ฐ์์์ ~ |
@@ -0,0 +1,12 @@
+public class BonusNumber {
+ private LottoNumber bonusNumber;
+
+ public BonusNumber(LottoNumber bonusNumber) {
+ this.bonusNumber = bonusNumber;
+ }
+
+ public LottoNumber getBonusNumber() {
+ return bonusNumber;
+ }
+}
+ | Java | LottoNumber ์์ฒด๋ ์์๊ฐ์ ํฌ์ฅํ ํํ๋ก LottoNumber ํ์
์ผ๋ก bonusNumber๋ฅผ ์ฌ์ฉํ ์ ์๋๋ฐ ์ด๋ฅผ ํ ๋ฒ ๋ ํฌ์ฅํ์ฌ ์ฌ์ฉํ์ ์ด์ ๊ฐ ์์ผ์ค๊น์? BonusNumber์์๋ ์ด๋ ํ ํ์๋ฅผ ํ์ง ์๊ณ ํฌ์ฅ๋ ๊ฐ์ ํ ๋ฒ ๋ Wrapping ํ๋ ํํ๋ก๋ง ์ฌ์ฉ๋๊ณ ์๋๋ฐ ๋ถํ์ํด ๋ณด์ฌ์์~ |
@@ -43,6 +43,10 @@ public int match(WinningLotto winningLotto) {
return matchCount;
}
+ public boolean isBonusMatch(WinningLotto winningLotto) {
+ return lotto.contains(winningLotto.getBonusNumber());
+ }
+
public boolean contains(LottoNumber lottoNumber) {
return lotto.contains(lottoNumber);
} | Java | lotto์ ๋ณด๋์ค ์ซ์๊ฐ ํฌํจ๋์ด์๋์ง ํ๋ณํ๋ ์ญํ ์ ํ๋ ๋ฉ์๋๋ก ๋ณด์ด๋ค์. ๋จ์ํ ํ๋ณ ์ฌ๋ถ๋ผ๋ฉด boolean ํ์
์ผ๋ก ๋ณ๊ฒฝํด์ฃผ๋ฉด ์ด๋จ๊น์? ๋ง์ฝ ๋ณด๋์ค ์ซ์๊ฐ 1๊ฐ ์ด์์ด๋ผ๋ ์๊ตฌ์ฌํญ ๋ณ๊ฒฝ์ ์ผ๋ํ ๊ตฌํ์ด๋ผ๋ฉด 1, 0์ ๋ฆฌํดํ๋ ๊ฒ๋ณด๋ค ๊ตฌ์ฒด์ ์ผ๋ก ๋งค์นญ๋ ๊ฐฏ์๋ฅผ ๋ฆฌํดํด์ฃผ๋ ์์ผ๋ก ๋ณ๊ฒฝํด๋ณด๋ฉด ํ์ฅ์ ์ ๋ฆฌํ ๊ตฌํ์ด ๋ ๊ฒ ๊ฐ์์. ๋ฉ์๋๋ช
๋ ์๋ฏธ์ ๋ฌ์ ์กฐ๊ธ ๋ ๋ช
ํํ๊ฒ ํ๋ฉด ์๋ฒฝํ ๊ฒ ๊ฐ์ต๋๋คb |
@@ -6,6 +6,8 @@ public class OutputView {
private static final String RESULT_STATISTICS_MESSAGE = "๋น์ฒจ ํต๊ณ";
private static final String BOUNDARY_LINE = "---------";
private static final String TOTAL_EARNING_RATIO_MESSAGE = "์ด ์์ต๋ฅ ์ %s ์
๋๋ค.";
+ private static final int SECOND_RANK_COUNT = 5;
+ private static final int MINIMUM_PRIZE_COUNT = 3;
public static void printLottoCount(int lottoCount) {
System.out.printf((LOTTO_PURCHASE_COMPLETE_MESSAGE) + "%n", lottoCount);
@@ -22,12 +24,29 @@ public static void printStatistics(Map<Rank, Integer> statistics) {
System.out.println(BOUNDARY_LINE);
for (Rank rank : statistics.keySet()) {
- System.out.print(String.format("%d ๊ฐ ์ผ์น (%d์)", rank.getMatchCount(), rank.getReward()));
- System.out.println(" - " + statistics.get(rank) + "๊ฐ");
+ printResult(rank, statistics);
}
}
public static void printEarningRate(String earningRate) {
System.out.printf((TOTAL_EARNING_RATIO_MESSAGE) + "%n", earningRate);
}
+
+ private static void printResult(Rank rank, Map<Rank, Integer> statistics) {
+ if (validateMatchCountIs5(rank)) {
+ System.out.print(String.format("%d ๊ฐ ์ผ์น, ๋ณด๋์ค ๋ณผ ์ผ์น (%d์)", rank.getMatchCount(), rank.getReward()));
+ System.out.println(" - " + statistics.get(rank) + "๊ฐ");
+ } else if (validateMatchCountOver3(rank)) {
+ System.out.print(String.format("%d ๊ฐ ์ผ์น (%d์)", rank.getMatchCount(), rank.getReward()));
+ System.out.println(" - " + statistics.get(rank) + "๊ฐ");
+ }
+ }
+
+ private static boolean validateMatchCountIs5(Rank rank) {
+ return rank.getMatchCount() == SECOND_RANK_COUNT && rank.isBonusMatch();
+ }
+
+ private static boolean validateMatchCountOver3(Rank rank) {
+ return rank.getMatchCount() >= MINIMUM_PRIZE_COUNT;
+ }
}
\ No newline at end of file | Java | ์ ์ฝ์ฌํญ ์๊ตฌ์ฌํญ์ ๋ฐ์ํ ๋ `rank.getMatch() == 5 && rank.getBonusMatchCount() == 1` ์ ๊ฐ์ ์ฝ๋๋ฅผ ๋ฉ์๋๋ก ๋ฐ๋ก ๋ถ๋ฆฌํด์ `validateMatchCount(rank)`์ ๊ฐ์ด ์์ฑํ๋ค๋ฉด ์ฝ๋๋ฅผ ์ฝ๋ ๋ค๋ฅธ ๊ฐ๋ฐ์๊ฐ ์ ์ฝ์ฌํญ์ ํ์
ํ๋๋ฐ ๋ ์ฌ์ธ ๊ฒ ๊ฐ์ต๋๋ค. ๋ฉ์๋๋ช
๋ง ๋ณด๊ณ "์ด ์ง์ ์์ validate ์ฒดํฌ๋ฅผ ํ๋ ๊ตฌ๋"๋ผ๊ณ ํ๋์ ํ์
์ด ๋๊ณ , ๊ตฌ์ฒด์ ์ธ ์ ์ฝ์ฌํญ์ด ๊ถ๊ธํ ๋ ํด๋น ๋ฉ์๋ ๋ด๋ถ ๊ตฌํ๋ง ์ฐพ์๋ณด๋ฉด ๋๊ฒ ๋ ๊ฒ ๊ฐ์ต๋๋ค. ์ถ๊ฐ๋ก ์ซ์๋ค๋ ์์ ์ฒ๋ฆฌํด์ฃผ๋ฉด ๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -1,10 +1,33 @@
+import exception.*;
+import java.util.List;
+
public class Application {
public static void main(String[] args) {
LottoGame game = new LottoGame();
- OutputView.printLottoCount(game.inputMoney(new Money(InputView.inputMoney()).getMoney()));
- OutputView.printLottoTicket(game.generateAutoLottoTicket());
- WinningLotto winningLotto = new WinningLotto(StringParsingUtils.parseToLottoNumber(InputView.inputWinningLottoNumber()));
- OutputView.printStatistics(game.calculateRankStatistics(winningLotto));
- OutputView.printEarningRate(game.calculateEarningRatio());
+ while (true) {
+ try {
+ OutputView.printLottoCount(game.calculateLottoCount(new Money(InputView.inputMoney()).getMoney()));
+ int manualLottoCount = InputView.manualLottoCount();
+
+ OutputView.printLottoTicket(game.generateLottoTicket(manualLottoCount));
+ List<LottoNumber> lottoNumbers = StringParsingUtils.parseToLottoNumber(InputView.inputWinningLottoNumber());
+ BonusNumber bonusNumber = InputView.inputBonusNumber();
+ WinningLotto winningLotto = new WinningLotto(lottoNumbers, bonusNumber);
+
+ OutputView.printStatistics(game.calculateRankStatistics(winningLotto));
+ OutputView.printEarningRate(game.calculateEarningRatio());
+ break;
+ } catch (MoneyUnderMinMoneyException moneyUnderMinMoneyException) {
+ System.out.println(moneyUnderMinMoneyException.getMessage());
+ } catch (LottoSizeMismatchException lottoSizeMismatchException) {
+ System.out.println(lottoSizeMismatchException.getMessage());
+ } catch (LottoIsNotUniqueException lottoIsNotUniqueException) {
+ System.out.println(lottoIsNotUniqueException.getMessage());
+ } catch (LottoNumberOutOfRangeException lottoNumberOutOfRangeException) {
+ System.out.println(lottoNumberOutOfRangeException.getMessage());
+ } catch (BonusNumberDuplicatedException bonusNumberDuplicatedException) {
+ System.out.println(bonusNumberDuplicatedException.getMessage());
+ }
+ }
}
}
\ No newline at end of file | Java | ํฐ ์์๋ ์๋๊ฒ ์ง๋ง ๊ด๋ จ์ฑ์ ๋ฐ๋ผ์ ๊ฐํ์ ์ถ๊ฐํด ๊ตฌ๋ถ ์ง์ด์ฃผ๋ ๊ฒ๋ ๊ฐ๋
์ฑ์ ๋์ด๋ ์์๋ผ๊ณ ์๊ฐํฉ๋๋ค! |
@@ -1,9 +1,14 @@
+import java.util.List;
import java.util.Scanner;
public class InputView {
private static final String INPUT_MONEY_MESSAGE = "๊ตฌ์
๊ธ์ก์ ์
๋ ฅํด ์ฃผ์ธ์.";
private static final String INPUT_WINNING_LOTTO_MESSAGE = "์ง๋ ์ฃผ ๋น์ฒจ ๋ฒํธ๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์.";
+ private static final String MANUAL_LOTTO_COUNT_MESSAGE = "์๋์ผ๋ก ๊ตฌ๋งคํ ๋ก๋ ์๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์.";
+ private static final String MANUAL_LOTTO_NUMBER_MESSAGE = "์๋์ผ๋ก ๊ตฌ๋งคํ ๋ฒํธ๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์.";
+
+ private static final String INPUT_BONUS_NUMBER_MESSAGE = "๋ณด๋์ค ๋ณผ์ ์
๋ ฅํด ์ฃผ์ธ์.";
private static Scanner scanner = new Scanner(System.in);
@@ -12,6 +17,30 @@ public static int inputMoney() {
return Integer.parseInt(scanner.nextLine());
}
+ public static int manualLottoCount() {
+ System.out.println(MANUAL_LOTTO_COUNT_MESSAGE);
+ return Integer.parseInt(scanner.nextLine());
+ }
+
+ public static List<LottoNumber> manualLotto(int i, int manualLottoCount) {
+ if (i == 0) {
+ System.out.println(MANUAL_LOTTO_NUMBER_MESSAGE);
+ }
+
+ String inputs = scanner.nextLine();
+ if (i != manualLottoCount - 1) {
+ scanner.nextLine();
+ }
+
+ return StringParsingUtils.parseToLottoNumber(inputs);
+ }
+
+ public static BonusNumber inputBonusNumber() {
+ System.out.println(INPUT_BONUS_NUMBER_MESSAGE);
+ int bonusNumber = Integer.parseInt(scanner.nextLine());
+ return new BonusNumber(new LottoNumber(bonusNumber));
+ }
+
public static String inputWinningLottoNumber() {
System.out.println(INPUT_WINNING_LOTTO_MESSAGE);
return scanner.nextLine(); | Java | InputView์์ ์๋ ๋ก๋์ ๋ํด ๋ฒํธ๋ฅผ ์
๋ ฅ ๋ฐ๋ ์ญํ ์ ๋ํด ์ง์ ๋ก๋๋ฅผ ์์ฑํ๋ ์ญํ ๊น์ง ํ๊ณ ์๋ค์. ์ญํ ์ ๋ถ๋ฆฌํด๋ณผ ์ ์์๊น์? ๋ถ๋ฆฌํ์ ๋ ์ด๋ค ์ด์ ์ด ์๊ธธ๊น์? |
@@ -4,44 +4,36 @@
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
-import java.util.HashMap;
import java.util.List;
-import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
public class LottoGameTest {
@Test
- @DisplayName("์ค์ ๋ก๋ ์์ต๋ฅ ๊ณผ ์์ํ ๋ก๋ ์์ต๋ฅ ์ด ๊ฐ๋ค๋ฉด ์ฑ๊ณต์ด๋ค.")
- public void should_success_when_real_lotto_earning_ratio_matches_expected_lotto_yield() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
- // given
+ public void should_success_when_real_lotto_earning_ratio_matches_expected_lotto_yield() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
LottoGame lottoGame = new LottoGame();
- lottoGame.inputMoney(1000);
-
- List<LottoNumber> testWinningLotto = new ArrayList<>();
-
- for (int i = 1; i < 7; i++){
- testWinningLotto.add(new LottoNumber(i));
+ lottoGame.calculateLottoCount(1000);
+ List<LottoNumber> lottoNumbers = new ArrayList<>();
+ for(int i=1; i<7; i++) {
+ lottoNumbers.add(new LottoNumber(i));
}
+ List<Lotto> lottos = new ArrayList<>();
+ lottos.add(new Lotto(lottoNumbers));
- List<Lotto> autoGeneratedLottos = new ArrayList<>();
- autoGeneratedLottos.add(new Lotto(testWinningLotto));
-
- Method method = lottoGame.getClass().getDeclaredMethod("generateLottoTicket",List.class);
+ Method method = lottoGame.getClass().getDeclaredMethod("makeLottoTicket", List.class);
method.setAccessible(true);
- method.invoke(lottoGame, autoGeneratedLottos);
-
- lottoGame.calculateRankStatistics(new WinningLotto(testWinningLotto));
+ method.invoke(lottoGame, lottos);
- String expectedEarningRatio = "200000000.0";
+ WinningLotto winningLotto = new WinningLotto(lottoNumbers, new BonusNumber(new LottoNumber(7)));
+ lottoGame.calculateRankStatistics(winningLotto);
- // when
+ //when
String earningRatio = lottoGame.calculateEarningRatio();
// then
- assertThat(earningRatio).isEqualTo(expectedEarningRatio);
+ assertThat(earningRatio).isEqualTo("200000000.0");
}
@Test
@@ -53,9 +45,35 @@ public void should_success_when_input_money_return_lotto_as_much_as_input_money(
LottoGame lottoGame = new LottoGame();
// when
- int lottoCount = lottoGame.inputMoney(money);
+ int lottoCount = lottoGame.calculateLottoCount(money);
// then
assertThat(lottoCount).isEqualTo(expectedLottoCount);
}
+
+ @Test
+ @DisplayName("๊ตฌ์
์ฅ์๋งํผ ๋ก๋ ํฐ์ผ์ ๋ก๋๊ฐ ์ถ๊ฐ๋๋ค๋ฉด ์ฑ๊ณต์ด๋ค.")
+ public void should_success_when_lotto_ticket_can_add_lottos_as_much_as_money() {
+ // given
+ int manualLottoCount = 1;
+
+ LottoGame lottoGame = new LottoGame();
+ int lottoCount = lottoGame.calculateLottoCount(3000);
+
+ List<LottoNumber> lottoNumbers = new ArrayList<>();
+ for (int i = 1; i < 7; i++) {
+ lottoNumbers.add(new LottoNumber(i));
+ }
+
+ List<Lotto> manualLotto = new ArrayList<>();
+ for (int i = 0; i < manualLottoCount; i++) {
+ manualLotto.add(new Lotto(lottoNumbers));
+ }
+
+ // when
+ LottoTicket lottoTicket = lottoGame.generateLottoTicket(manualLottoCount);
+
+ // then
+ assertThat(lottoTicket.getLottoTicket().size()).isEqualTo(lottoCount);
+ }
}
\ No newline at end of file | Java | `inputMoney()`๋ผ๋ ์ด๋ฆ์ ๋ฉ์๋์ ๊ฒฐ๊ณผ๊ฐ์ผ๋ก ๋ก๋ ๊ฐฏ์๊ฐ ๋์ค๋๊ฒ ์กฐ๊ธ ์ด์ํ ๊ฒ ๊ฐ์ต๋๋ค. ์
๋ ฅ๋ฐ๋ ๋ฉ์๋์ ๊ฐฏ์๋ฅผ ๋ฐํํ๋ ๋ฉ์๋๋ก ๋ถ๋ฆฌํด๋ณด๋ฉด ์ด๋จ๊น์? |
@@ -4,44 +4,36 @@
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
-import java.util.HashMap;
import java.util.List;
-import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
public class LottoGameTest {
@Test
- @DisplayName("์ค์ ๋ก๋ ์์ต๋ฅ ๊ณผ ์์ํ ๋ก๋ ์์ต๋ฅ ์ด ๊ฐ๋ค๋ฉด ์ฑ๊ณต์ด๋ค.")
- public void should_success_when_real_lotto_earning_ratio_matches_expected_lotto_yield() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
- // given
+ public void should_success_when_real_lotto_earning_ratio_matches_expected_lotto_yield() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
LottoGame lottoGame = new LottoGame();
- lottoGame.inputMoney(1000);
-
- List<LottoNumber> testWinningLotto = new ArrayList<>();
-
- for (int i = 1; i < 7; i++){
- testWinningLotto.add(new LottoNumber(i));
+ lottoGame.calculateLottoCount(1000);
+ List<LottoNumber> lottoNumbers = new ArrayList<>();
+ for(int i=1; i<7; i++) {
+ lottoNumbers.add(new LottoNumber(i));
}
+ List<Lotto> lottos = new ArrayList<>();
+ lottos.add(new Lotto(lottoNumbers));
- List<Lotto> autoGeneratedLottos = new ArrayList<>();
- autoGeneratedLottos.add(new Lotto(testWinningLotto));
-
- Method method = lottoGame.getClass().getDeclaredMethod("generateLottoTicket",List.class);
+ Method method = lottoGame.getClass().getDeclaredMethod("makeLottoTicket", List.class);
method.setAccessible(true);
- method.invoke(lottoGame, autoGeneratedLottos);
-
- lottoGame.calculateRankStatistics(new WinningLotto(testWinningLotto));
+ method.invoke(lottoGame, lottos);
- String expectedEarningRatio = "200000000.0";
+ WinningLotto winningLotto = new WinningLotto(lottoNumbers, new BonusNumber(new LottoNumber(7)));
+ lottoGame.calculateRankStatistics(winningLotto);
- // when
+ //when
String earningRatio = lottoGame.calculateEarningRatio();
// then
- assertThat(earningRatio).isEqualTo(expectedEarningRatio);
+ assertThat(earningRatio).isEqualTo("200000000.0");
}
@Test
@@ -53,9 +45,35 @@ public void should_success_when_input_money_return_lotto_as_much_as_input_money(
LottoGame lottoGame = new LottoGame();
// when
- int lottoCount = lottoGame.inputMoney(money);
+ int lottoCount = lottoGame.calculateLottoCount(money);
// then
assertThat(lottoCount).isEqualTo(expectedLottoCount);
}
+
+ @Test
+ @DisplayName("๊ตฌ์
์ฅ์๋งํผ ๋ก๋ ํฐ์ผ์ ๋ก๋๊ฐ ์ถ๊ฐ๋๋ค๋ฉด ์ฑ๊ณต์ด๋ค.")
+ public void should_success_when_lotto_ticket_can_add_lottos_as_much_as_money() {
+ // given
+ int manualLottoCount = 1;
+
+ LottoGame lottoGame = new LottoGame();
+ int lottoCount = lottoGame.calculateLottoCount(3000);
+
+ List<LottoNumber> lottoNumbers = new ArrayList<>();
+ for (int i = 1; i < 7; i++) {
+ lottoNumbers.add(new LottoNumber(i));
+ }
+
+ List<Lotto> manualLotto = new ArrayList<>();
+ for (int i = 0; i < manualLottoCount; i++) {
+ manualLotto.add(new Lotto(lottoNumbers));
+ }
+
+ // when
+ LottoTicket lottoTicket = lottoGame.generateLottoTicket(manualLottoCount);
+
+ // then
+ assertThat(lottoTicket.getLottoTicket().size()).isEqualTo(lottoCount);
+ }
}
\ No newline at end of file | Java | ๊ฒฐ๊ณผ๊ฐ๊ณผ ๋น๊ตํ๋ ๊ฐ์ lottoCount๊ฐ ์๋ ์ง์ ์ ์ธ ์ซ์๋ก ๋น๊ตํ๋ฉด ์ด๋จ๊น์? ๋ง์ฝ ์ค์๋ก lottoGame.inputMoney()์์ ์
๋ ฅ๋ฐ์ ๋์ ๋ฐ์ฌ๋ฆผํด์ ์ฅ์๋ฅผ ์ถ๋ ฅํ๋๋ก ํด๋ฒ๋ ธ๋ค๋ฉด ํฐ์ผ์ ์ฌ์ด์ฆ๊ฐ 4๋๋ผ๋ ํ
์คํธ๊ฐ ํต๊ณผํ๊ฒ ๋ ๊ฒ ๊ฐ์ต๋๋ค. ์ฌ์ค ์ง๊ธ ํ
์คํธ ์ฝ๋๋ `lottoGame.inputMoney()`๊ฐ ๋จผ์ ๋ณด์ฅ๋์ด์ผํ๋๋ง ์ ํํ ํ
์คํธ๊ฐ ๊ฐ๋ฅํ ์ฝ๋๋ผ๊ณ ๋ณผ ์ ์์ ๊ฒ ๊ฐ์ต๋๋ค. ํ
์คํธ๋ฅผ ํ๋ค๋ณด๋ฉด ์ด์ฉ ์ ์๋ ๋ถ๋ถ์ผ ์๋ ์๊ณ , ์ ๋ง์ด ์ ๋ต์ ์๋์ง๋ง ๊ฒฐ๊ณผ๊ฐ์ ๊ฐ๊ธ์ ๋ ์ ํํ ๊ฒ์ ์์กดํด์ผํ์ง ์์๊น ์๊ฐ์ด ๋ค์ด ๋ฆฌ๋ทฐ ๋จ๊ฒจ๋ดค์ต๋๋ค. |
@@ -1,9 +1,14 @@
+import java.util.List;
import java.util.Scanner;
public class InputView {
private static final String INPUT_MONEY_MESSAGE = "๊ตฌ์
๊ธ์ก์ ์
๋ ฅํด ์ฃผ์ธ์.";
private static final String INPUT_WINNING_LOTTO_MESSAGE = "์ง๋ ์ฃผ ๋น์ฒจ ๋ฒํธ๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์.";
+ private static final String MANUAL_LOTTO_COUNT_MESSAGE = "์๋์ผ๋ก ๊ตฌ๋งคํ ๋ก๋ ์๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์.";
+ private static final String MANUAL_LOTTO_NUMBER_MESSAGE = "์๋์ผ๋ก ๊ตฌ๋งคํ ๋ฒํธ๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์.";
+
+ private static final String INPUT_BONUS_NUMBER_MESSAGE = "๋ณด๋์ค ๋ณผ์ ์
๋ ฅํด ์ฃผ์ธ์.";
private static Scanner scanner = new Scanner(System.in);
@@ -12,6 +17,30 @@ public static int inputMoney() {
return Integer.parseInt(scanner.nextLine());
}
+ public static int manualLottoCount() {
+ System.out.println(MANUAL_LOTTO_COUNT_MESSAGE);
+ return Integer.parseInt(scanner.nextLine());
+ }
+
+ public static List<LottoNumber> manualLotto(int i, int manualLottoCount) {
+ if (i == 0) {
+ System.out.println(MANUAL_LOTTO_NUMBER_MESSAGE);
+ }
+
+ String inputs = scanner.nextLine();
+ if (i != manualLottoCount - 1) {
+ scanner.nextLine();
+ }
+
+ return StringParsingUtils.parseToLottoNumber(inputs);
+ }
+
+ public static BonusNumber inputBonusNumber() {
+ System.out.println(INPUT_BONUS_NUMBER_MESSAGE);
+ int bonusNumber = Integer.parseInt(scanner.nextLine());
+ return new BonusNumber(new LottoNumber(bonusNumber));
+ }
+
public static String inputWinningLottoNumber() {
System.out.println(INPUT_WINNING_LOTTO_MESSAGE);
return scanner.nextLine(); | Java | ์๋์ด ์๋ ์๋์ผ๋ก ์
๋ ฅํ ๊ฐฏ์๋งํผ ์
๋ ฅ์ ๋ฐ๋๋ก ์๊ตฌ์ฌํญ์ด ๊ธฐ์ฌ๋์ด ์๊ธฐ ๋๋ฌธ์, ๋ง์ฝ `์๋์ผ๋ก ๊ตฌ๋งคํ ๋ก๋ ์๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์.` ์์ 2๊ฐ๋ฅผ ์
๋ ฅํ๋ค๋ฉด, 2์ค์ ์
๋ ฅ ๊ฐ์ ๋ฃ์ด์ฃผ์ด์ผ ํฉ๋๋ค! |
@@ -1,9 +1,14 @@
+import java.util.List;
import java.util.Scanner;
public class InputView {
private static final String INPUT_MONEY_MESSAGE = "๊ตฌ์
๊ธ์ก์ ์
๋ ฅํด ์ฃผ์ธ์.";
private static final String INPUT_WINNING_LOTTO_MESSAGE = "์ง๋ ์ฃผ ๋น์ฒจ ๋ฒํธ๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์.";
+ private static final String MANUAL_LOTTO_COUNT_MESSAGE = "์๋์ผ๋ก ๊ตฌ๋งคํ ๋ก๋ ์๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์.";
+ private static final String MANUAL_LOTTO_NUMBER_MESSAGE = "์๋์ผ๋ก ๊ตฌ๋งคํ ๋ฒํธ๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์.";
+
+ private static final String INPUT_BONUS_NUMBER_MESSAGE = "๋ณด๋์ค ๋ณผ์ ์
๋ ฅํด ์ฃผ์ธ์.";
private static Scanner scanner = new Scanner(System.in);
@@ -12,6 +17,30 @@ public static int inputMoney() {
return Integer.parseInt(scanner.nextLine());
}
+ public static int manualLottoCount() {
+ System.out.println(MANUAL_LOTTO_COUNT_MESSAGE);
+ return Integer.parseInt(scanner.nextLine());
+ }
+
+ public static List<LottoNumber> manualLotto(int i, int manualLottoCount) {
+ if (i == 0) {
+ System.out.println(MANUAL_LOTTO_NUMBER_MESSAGE);
+ }
+
+ String inputs = scanner.nextLine();
+ if (i != manualLottoCount - 1) {
+ scanner.nextLine();
+ }
+
+ return StringParsingUtils.parseToLottoNumber(inputs);
+ }
+
+ public static BonusNumber inputBonusNumber() {
+ System.out.println(INPUT_BONUS_NUMBER_MESSAGE);
+ int bonusNumber = Integer.parseInt(scanner.nextLine());
+ return new BonusNumber(new LottoNumber(bonusNumber));
+ }
+
public static String inputWinningLottoNumber() {
System.out.println(INPUT_WINNING_LOTTO_MESSAGE);
return scanner.nextLine(); | Java | <img width="370" alt="แแ
ณแแ
ณแ
แ
ตแซแแ
ฃแบ 2022-07-04 แแ
ฉแแ
ฎ 7 14 35" src="https://user-images.githubusercontent.com/62830487/177134400-0365bef0-a31c-4a57-9020-e294daa65100.png">
๋ก์ง์ ๋ฌธ์ ๊ฐ ์์ด๋ณด์ด๋ค์. ์๋ ๋ก๋ 2์ฅ์ ๊ตฌ๋งคํด์ ๋ก๋ 2์ฅ์ ๋ฒํธ๋ฅผ ์
๋ ฅํ๋๋ฐ ์
๋ ฅ์ ํ ๋ฒ ๋ ๊ธฐ๋ค๋ฆฌ๊ณ ์๋ค์. ํ์ธ ๋ถํ๋๋ ค์. |
@@ -9,19 +9,24 @@ public LottoGame() {
statistics = new TreeMap<>();
}
- public int inputMoney(int money) {
+ public int calculateLottoCount(int money) {
return lottoCount = money / Lotto.LOTTO_PRICE;
}
- public LottoTicket generateAutoLottoTicket() {
+ public LottoTicket generateLottoTicket(int manualLottoCount) {
List<Lotto> lottos = new ArrayList<>();
- for(int i = 0; i < lottoCount; i++) {
+
+ for (int i = 0; i < manualLottoCount; i++) {
+ lottos.add(ManualLottoGenerator.generate(i, manualLottoCount));
+ }
+
+ for(int i = manualLottoCount; i < lottoCount; i++) {
lottos.add(AutoLottoGenerator.generate());
}
- return generateLottoTicket(lottos);
+ return makeLottoTicket(lottos);
}
- private LottoTicket generateLottoTicket(List<Lotto> lottos) {
+ private LottoTicket makeLottoTicket(List<Lotto> lottos) {
return lottoTicket = new LottoTicket(lottos);
}
| Java | ๊ฒฐ๊ตญ์ ์๋ ๋ก๋์ ์๋ ๋ก๋ ๋ชจ๋ ํ๋์ ๋ก๋ ํฐ์ผ์ผ๋ก ํฉ์ณ์ง๋ ๋ถ๋ถ์ด ํ์ํ๊ธฐ ๋๋ฌธ์, ํ์ฌ `generateLottoTicket()` ๋ด์ ์๋๊ณผ ์๋ ๋ก๋ ์์ฑ ๊ฐ๊ฐ์ ๋ฐ๋ณต๋ฌธ์ `generateManualLottoTicket()`๊ณผ `generateAutoLottoTicket()` ์ผ๋ก ๋ฉ์๋๋ฅผ ๋ถ๋ฆฌํด๋ณด๋๋ก ํ๊ฒ ์ต๋๋ค |
@@ -0,0 +1,12 @@
+public class BonusNumber {
+ private LottoNumber bonusNumber;
+
+ public BonusNumber(LottoNumber bonusNumber) {
+ this.bonusNumber = bonusNumber;
+ }
+
+ public LottoNumber getBonusNumber() {
+ return bonusNumber;
+ }
+}
+ | Java | @sunghyuki ๊ธฐ์กด์ Lotto ๊ฐ์ฒด๋ก๋ง ๊ตฌ์ฑ๋ WinningLotto์ BonusNumber๋ฅผ ์ถ๊ฐํ์ฌ, ๋ก๋ ๋น์ฒจ ๋ฒํธ ์ค 5๊ฐ๊ฐ ์ผ์นํ๋ ๊ฒฝ์ฐ BonusNumber ์ผ์น ์ฌ๋ถ ํ์ธ์ ๋ถ๋ช
ํ๊ฒ ํ๊ธฐ ์ํด LottoNumber ํ์
์ผ๋ก ๊ตฌ์ฑ๋ BonusNumber๋ฅผ ์์ฑํ์ต๋๋ค~ |
@@ -4,44 +4,36 @@
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
-import java.util.HashMap;
import java.util.List;
-import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
public class LottoGameTest {
@Test
- @DisplayName("์ค์ ๋ก๋ ์์ต๋ฅ ๊ณผ ์์ํ ๋ก๋ ์์ต๋ฅ ์ด ๊ฐ๋ค๋ฉด ์ฑ๊ณต์ด๋ค.")
- public void should_success_when_real_lotto_earning_ratio_matches_expected_lotto_yield() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
- // given
+ public void should_success_when_real_lotto_earning_ratio_matches_expected_lotto_yield() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
LottoGame lottoGame = new LottoGame();
- lottoGame.inputMoney(1000);
-
- List<LottoNumber> testWinningLotto = new ArrayList<>();
-
- for (int i = 1; i < 7; i++){
- testWinningLotto.add(new LottoNumber(i));
+ lottoGame.calculateLottoCount(1000);
+ List<LottoNumber> lottoNumbers = new ArrayList<>();
+ for(int i=1; i<7; i++) {
+ lottoNumbers.add(new LottoNumber(i));
}
+ List<Lotto> lottos = new ArrayList<>();
+ lottos.add(new Lotto(lottoNumbers));
- List<Lotto> autoGeneratedLottos = new ArrayList<>();
- autoGeneratedLottos.add(new Lotto(testWinningLotto));
-
- Method method = lottoGame.getClass().getDeclaredMethod("generateLottoTicket",List.class);
+ Method method = lottoGame.getClass().getDeclaredMethod("makeLottoTicket", List.class);
method.setAccessible(true);
- method.invoke(lottoGame, autoGeneratedLottos);
-
- lottoGame.calculateRankStatistics(new WinningLotto(testWinningLotto));
+ method.invoke(lottoGame, lottos);
- String expectedEarningRatio = "200000000.0";
+ WinningLotto winningLotto = new WinningLotto(lottoNumbers, new BonusNumber(new LottoNumber(7)));
+ lottoGame.calculateRankStatistics(winningLotto);
- // when
+ //when
String earningRatio = lottoGame.calculateEarningRatio();
// then
- assertThat(earningRatio).isEqualTo(expectedEarningRatio);
+ assertThat(earningRatio).isEqualTo("200000000.0");
}
@Test
@@ -53,9 +45,35 @@ public void should_success_when_input_money_return_lotto_as_much_as_input_money(
LottoGame lottoGame = new LottoGame();
// when
- int lottoCount = lottoGame.inputMoney(money);
+ int lottoCount = lottoGame.calculateLottoCount(money);
// then
assertThat(lottoCount).isEqualTo(expectedLottoCount);
}
+
+ @Test
+ @DisplayName("๊ตฌ์
์ฅ์๋งํผ ๋ก๋ ํฐ์ผ์ ๋ก๋๊ฐ ์ถ๊ฐ๋๋ค๋ฉด ์ฑ๊ณต์ด๋ค.")
+ public void should_success_when_lotto_ticket_can_add_lottos_as_much_as_money() {
+ // given
+ int manualLottoCount = 1;
+
+ LottoGame lottoGame = new LottoGame();
+ int lottoCount = lottoGame.calculateLottoCount(3000);
+
+ List<LottoNumber> lottoNumbers = new ArrayList<>();
+ for (int i = 1; i < 7; i++) {
+ lottoNumbers.add(new LottoNumber(i));
+ }
+
+ List<Lotto> manualLotto = new ArrayList<>();
+ for (int i = 0; i < manualLottoCount; i++) {
+ manualLotto.add(new Lotto(lottoNumbers));
+ }
+
+ // when
+ LottoTicket lottoTicket = lottoGame.generateLottoTicket(manualLottoCount);
+
+ // then
+ assertThat(lottoTicket.getLottoTicket().size()).isEqualTo(lottoCount);
+ }
}
\ No newline at end of file | Java | @Bellroute ์ ํฌ๋ ์
๋ ฅ ๊ธ์ก๋งํผ ๋ก๋ ๋ฆฌ์คํธ๊ฐ ์ ์ถ๊ฐ๋๋์ง ํ
์คํธํ๋ ค๊ณ ์์ฑํ๋๋ฐ, ์ ์ด์ฃผ์ ๋ฆฌ๋ทฐ๋ฅผ ์ ์ดํดํ์ง ๋ชปํ ๊ฒ ๊ฐ์ต๋๋ค. ๋ถ์ฐ ์ค๋ช
๋ถํ๋๋ ค๋ ๋ ๊น์?? |
@@ -1,9 +1,14 @@
+import java.util.List;
import java.util.Scanner;
public class InputView {
private static final String INPUT_MONEY_MESSAGE = "๊ตฌ์
๊ธ์ก์ ์
๋ ฅํด ์ฃผ์ธ์.";
private static final String INPUT_WINNING_LOTTO_MESSAGE = "์ง๋ ์ฃผ ๋น์ฒจ ๋ฒํธ๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์.";
+ private static final String MANUAL_LOTTO_COUNT_MESSAGE = "์๋์ผ๋ก ๊ตฌ๋งคํ ๋ก๋ ์๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์.";
+ private static final String MANUAL_LOTTO_NUMBER_MESSAGE = "์๋์ผ๋ก ๊ตฌ๋งคํ ๋ฒํธ๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์.";
+
+ private static final String INPUT_BONUS_NUMBER_MESSAGE = "๋ณด๋์ค ๋ณผ์ ์
๋ ฅํด ์ฃผ์ธ์.";
private static Scanner scanner = new Scanner(System.in);
@@ -12,6 +17,30 @@ public static int inputMoney() {
return Integer.parseInt(scanner.nextLine());
}
+ public static int manualLottoCount() {
+ System.out.println(MANUAL_LOTTO_COUNT_MESSAGE);
+ return Integer.parseInt(scanner.nextLine());
+ }
+
+ public static List<LottoNumber> manualLotto(int i, int manualLottoCount) {
+ if (i == 0) {
+ System.out.println(MANUAL_LOTTO_NUMBER_MESSAGE);
+ }
+
+ String inputs = scanner.nextLine();
+ if (i != manualLottoCount - 1) {
+ scanner.nextLine();
+ }
+
+ return StringParsingUtils.parseToLottoNumber(inputs);
+ }
+
+ public static BonusNumber inputBonusNumber() {
+ System.out.println(INPUT_BONUS_NUMBER_MESSAGE);
+ int bonusNumber = Integer.parseInt(scanner.nextLine());
+ return new BonusNumber(new LottoNumber(bonusNumber));
+ }
+
public static String inputWinningLottoNumber() {
System.out.println(INPUT_WINNING_LOTTO_MESSAGE);
return scanner.nextLine(); | Java | @Bellroute ๊ธฐ์กด์ ์ ํฌ๊ฐ ์์ฑํ ์ฝ๋๋ ์ง์ ํด์ฃผ์ ๊ฒ์ฒ๋ผ Lottoame ์ฑ
์์ InputView์์ ๋ถ์ฌํ๊ณ ์์ต๋๋ค. ์ด ๊ฒฝ์ฐ ๋ณ๊ฒฝ์ฌํญ์ด ์๊ธธ ๋, InputView์ Lotto๋ฅผ ์์ฑํ๋ LottoGame์ ๋ชจ๋ ์์ ํด์ผํฉ๋๋ค.
ํ์ธํด๋ณด๋ LottoGame์ ๊ธฐ์กด์ ์์ฑํด๋ Lotto ์์ฑ ๋ฉ์๋๋ฅผ ํ์ฉํด์ ๋ฆฌํํ ๋งํ์์ต๋๋ค. |
@@ -0,0 +1,24 @@
+import UIKit
+
+extension UIImageView {
+ func loadImage(of key: String) {
+ let cacheKey = NSString(string: key)
+ if let cachedImage = ImageCacheManager.shared.object(forKey: cacheKey) {
+ self.image = cachedImage
+ return
+ }
+
+ DispatchQueue.global().async {
+ guard let imageURL = URL(string: key),
+ let imageData = try? Data(contentsOf: imageURL),
+ let loadedImage = UIImage(data: imageData) else {
+ return
+ }
+ ImageCacheManager.shared.setObject(loadedImage, forKey: cacheKey)
+
+ DispatchQueue.main.async {
+ self.image = loadedImage
+ }
+ }
+ }
+} | Swift | `func loadImage(of key: String)` ๋ง ๋ณด๊ณ key๊ฐ ๋ฌด์์ธ์ง, key๊ฐ Image์ ์ด๋ค ์ฐ๊ด์ด ์๋์ง ์๊ธฐ ์ด๋ ต๋ค์.
loadCachedImage(of key: String) ์ ๋ ์ ์๋๋ฆฝ๋๋ค. |
@@ -0,0 +1,22 @@
+import UIKit
+
+extension UIStackView {
+ func style(axis: NSLayoutConstraint.Axis,
+ alignment: UIStackView.Alignment,
+ distribution: UIStackView.Distribution,
+ spacing: CGFloat = .zero) {
+ self.translatesAutoresizingMaskIntoConstraints = false
+ self.axis = axis
+ self.alignment = alignment
+ self.distribution = distribution
+ self.spacing = spacing
+ }
+
+ func setupMargins(verticalInset: CGFloat = .zero, horizontalInset: CGFloat = .zero) {
+ self.layoutMargins = UIEdgeInsets(top: verticalInset,
+ left: horizontalInset,
+ bottom: verticalInset,
+ right: horizontalInset)
+ self.isLayoutMarginsRelativeArrangement = true
+ }
+} | Swift | method๋ฅผ ํตํด property๋ฅผ setํ๋ ์ด์ ๋ฅผ ์ถ์ธกํ๊ธฐ ์ด๋ ต๋ค์. |
@@ -0,0 +1,18 @@
+import Foundation
+
+extension URLRequest {
+ init?(api: APIProtocol) {
+ guard let url = api.url else {
+ return nil
+ }
+
+ self.init(url: url)
+ self.httpMethod = "\(api.method)"
+
+ if let postableAPI = api as? Postable {
+ self.addValue(postableAPI.identifier, forHTTPHeaderField: "identifier")
+ self.addValue(postableAPI.contentType, forHTTPHeaderField: "Content-Type")
+ self.httpBody = postableAPI.body
+ }
+ }
+} | Swift | ์ถ์ํํ์ ๋, Specificํ Type์ผ๋ก casting์ด ํ์ํ๋ค๋ ๊ฑด ์ถ์ํ๊ฐ ์๋ชป๋์๋ค๋ ๋ฐ์ฆ์ด ๋ฉ๋๋ค.
Header setํ๋ ์ฝ๋์ httpBody setํ๋ ๋ถ๋ถ์ APIProtocol Level๋ก ์ฌ๋ ค์ ๊ตฌํ๋ค๋ฉด Postable๋ก์ Casting์ด ํ์์์ ๊ฒ ๊ฐ์ต๋๋ค. ์ด ๋ฐฉํฅ์ผ๋ก ๊ณ ๋ฏผํด์ฃผ์ธ์. |
@@ -0,0 +1,120 @@
+import UIKit
+
+struct MultipartFormData {
+ private(set) var boundary: String
+ let contentType: String
+ private(set) var body: Data = Data()
+
+ init(uuid: String = UUID().uuidString) {
+ self.boundary = "Boundary-\(uuid)"
+ self.contentType = "multipart/form-data; boundary=\(self.boundary)"
+ }
+
+ mutating func appendToBody(from data: Data) {
+ self.body.append(data)
+ }
+
+ func createFormData<Item: Codable>(params: String, item: Item) -> Data {
+ var data = Data()
+ data.append(BoundaryGenerator.boundaryData(forBoundaryType: .startSymbol, boundary: boundary))
+ data.append(ContentDisposition.formData(params: params).bodyComponent)
+
+ let encodedResult = JSONParser<Item>().encode(from: item)
+ switch encodedResult {
+ case .success(let encodedData):
+ data.append(encodedData)
+ case .failure(let error):
+ print(error.localizedDescription)
+ }
+ data.append(BoundaryGenerator.boundaryData(forBoundaryType: .endSymbol, boundary: boundary))
+
+ return data
+ }
+
+ func createImageFormData(name: String, fileName: String, contentType: ImageContentType, image: UIImage) -> Data {
+ var data = Data()
+ data.append(BoundaryGenerator.boundaryData(forBoundaryType: .startSymbol, boundary: boundary))
+ data.append(ContentDisposition.imageFormData(name: name, filename: fileName).bodyComponent)
+ data.append(ContentDisposition.imageContentType(type: contentType).bodyComponent)
+
+ switch contentType {
+ case .png:
+ if let imageData = image.pngData() {
+ data.append(imageData)
+ }
+ case .jpeg:
+ if let imageData = image.jpegData(compressionQuality: 1) {
+ data.append(imageData)
+ }
+ }
+ data.append(BoundaryGenerator.boundaryData(forBoundaryType: .endSymbol, boundary: boundary))
+
+ return data
+ }
+
+ mutating func closeBody() {
+ self.body.append(BoundaryGenerator.boundaryData(forBoundaryType: .terminator, boundary: boundary))
+ }
+}
+
+enum ImageContentType: String, CustomStringConvertible {
+ case png
+ case jpeg
+
+ var description: String {
+ return "image/\(rawValue)"
+ }
+}
+
+enum ContentDisposition {
+ case formData(params: String)
+ case imageFormData(name: String, filename: String)
+ case imageContentType(type: ImageContentType)
+
+ var bodyComponent: String {
+ switch self {
+ case .formData(let params):
+ return "Content-Disposition: form-data; name=\"\(params)\""
+ + EncodingCharacters.doubleNewLine
+ case .imageFormData(let name, let filename):
+ return "Content-Disposition: form-data; name=\"\(name)\"; filename=\"\(filename)\""
+ + EncodingCharacters.newLine
+ case .imageContentType(let type):
+ return "Content-Type: \(type.description)" + EncodingCharacters.doubleNewLine
+ }
+ }
+}
+
+enum EncodingCharacters {
+ static let newLine = "\r\n"
+ static let doubleNewLine = "\r\n\r\n"
+}
+
+enum BoundaryGenerator {
+ enum BoundaryType {
+ case startSymbol, endSymbol, terminator
+ }
+
+ static func boundaryData(forBoundaryType boundaryType: BoundaryType, boundary: String) -> Data {
+ let boundaryText: String
+
+ switch boundaryType {
+ case .startSymbol:
+ boundaryText = "--\(boundary)\(EncodingCharacters.newLine)"
+ case .endSymbol:
+ boundaryText = "\(EncodingCharacters.newLine)"
+ case .terminator:
+ boundaryText = "--\(boundary)--"
+ }
+
+ return Data(boundaryText.utf8)
+ }
+}
+
+private extension Data {
+ mutating func append(_ string: String?) {
+ if let stringData = string?.data(using: .utf8) {
+ self.append(stringData)
+ }
+ }
+} | Swift | Type ์ด๋ฆ์ 'XXFormData'๊ฐ ํฌํจ๋์ด์์ผ๋ฏ๋ก, method ์ด๋ฆ์ FormData๊ฐ ํฌํจ๋์ง ์๋ ๊ฒ์ด ํธ์ถํ์ ๋ ์์ฐ์ค๋ฝ์ต๋๋ค.
multipartFormdata.create๋ง ํด๋ ๋งฅ๋ฝ์ ์ดํดํ๋๋ฐ ๋ฌธ์ ์์ด์.
๋ํ item์ด๋ผ๋ ํ๋ผ๋ฏธํฐ ์ด๋ฆ์ด ๋ชจํธํด๋ณด์
๋๋ค. ์ ํํ ์ ๊ฒ ๋ฌด์จ item์ธ์ง ๋ ์์ธํ๊ฒ ๋ช
์ธ๋์์ผ๋ฉด ํฉ๋๋ค. |
@@ -0,0 +1,120 @@
+import UIKit
+
+struct MultipartFormData {
+ private(set) var boundary: String
+ let contentType: String
+ private(set) var body: Data = Data()
+
+ init(uuid: String = UUID().uuidString) {
+ self.boundary = "Boundary-\(uuid)"
+ self.contentType = "multipart/form-data; boundary=\(self.boundary)"
+ }
+
+ mutating func appendToBody(from data: Data) {
+ self.body.append(data)
+ }
+
+ func createFormData<Item: Codable>(params: String, item: Item) -> Data {
+ var data = Data()
+ data.append(BoundaryGenerator.boundaryData(forBoundaryType: .startSymbol, boundary: boundary))
+ data.append(ContentDisposition.formData(params: params).bodyComponent)
+
+ let encodedResult = JSONParser<Item>().encode(from: item)
+ switch encodedResult {
+ case .success(let encodedData):
+ data.append(encodedData)
+ case .failure(let error):
+ print(error.localizedDescription)
+ }
+ data.append(BoundaryGenerator.boundaryData(forBoundaryType: .endSymbol, boundary: boundary))
+
+ return data
+ }
+
+ func createImageFormData(name: String, fileName: String, contentType: ImageContentType, image: UIImage) -> Data {
+ var data = Data()
+ data.append(BoundaryGenerator.boundaryData(forBoundaryType: .startSymbol, boundary: boundary))
+ data.append(ContentDisposition.imageFormData(name: name, filename: fileName).bodyComponent)
+ data.append(ContentDisposition.imageContentType(type: contentType).bodyComponent)
+
+ switch contentType {
+ case .png:
+ if let imageData = image.pngData() {
+ data.append(imageData)
+ }
+ case .jpeg:
+ if let imageData = image.jpegData(compressionQuality: 1) {
+ data.append(imageData)
+ }
+ }
+ data.append(BoundaryGenerator.boundaryData(forBoundaryType: .endSymbol, boundary: boundary))
+
+ return data
+ }
+
+ mutating func closeBody() {
+ self.body.append(BoundaryGenerator.boundaryData(forBoundaryType: .terminator, boundary: boundary))
+ }
+}
+
+enum ImageContentType: String, CustomStringConvertible {
+ case png
+ case jpeg
+
+ var description: String {
+ return "image/\(rawValue)"
+ }
+}
+
+enum ContentDisposition {
+ case formData(params: String)
+ case imageFormData(name: String, filename: String)
+ case imageContentType(type: ImageContentType)
+
+ var bodyComponent: String {
+ switch self {
+ case .formData(let params):
+ return "Content-Disposition: form-data; name=\"\(params)\""
+ + EncodingCharacters.doubleNewLine
+ case .imageFormData(let name, let filename):
+ return "Content-Disposition: form-data; name=\"\(name)\"; filename=\"\(filename)\""
+ + EncodingCharacters.newLine
+ case .imageContentType(let type):
+ return "Content-Type: \(type.description)" + EncodingCharacters.doubleNewLine
+ }
+ }
+}
+
+enum EncodingCharacters {
+ static let newLine = "\r\n"
+ static let doubleNewLine = "\r\n\r\n"
+}
+
+enum BoundaryGenerator {
+ enum BoundaryType {
+ case startSymbol, endSymbol, terminator
+ }
+
+ static func boundaryData(forBoundaryType boundaryType: BoundaryType, boundary: String) -> Data {
+ let boundaryText: String
+
+ switch boundaryType {
+ case .startSymbol:
+ boundaryText = "--\(boundary)\(EncodingCharacters.newLine)"
+ case .endSymbol:
+ boundaryText = "\(EncodingCharacters.newLine)"
+ case .terminator:
+ boundaryText = "--\(boundary)--"
+ }
+
+ return Data(boundaryText.utf8)
+ }
+}
+
+private extension Data {
+ mutating func append(_ string: String?) {
+ if let stringData = string?.data(using: .utf8) {
+ self.append(stringData)
+ }
+ }
+} | Swift | 'params: params' ์ ๊ฐ์ ๋ชจ์์ด ๋์จ๋ค๋ฉด, ์ธ๋๋ฐ๋ก ํ๋ผ๋ฏธํฐ๋ช
์ ์จ๊ธฐ๋ ๊ฒ์ ๊ณ ๋ คํด๋ณผ ์ ์์ต๋๋ค. |
@@ -0,0 +1,120 @@
+import UIKit
+
+struct MultipartFormData {
+ private(set) var boundary: String
+ let contentType: String
+ private(set) var body: Data = Data()
+
+ init(uuid: String = UUID().uuidString) {
+ self.boundary = "Boundary-\(uuid)"
+ self.contentType = "multipart/form-data; boundary=\(self.boundary)"
+ }
+
+ mutating func appendToBody(from data: Data) {
+ self.body.append(data)
+ }
+
+ func createFormData<Item: Codable>(params: String, item: Item) -> Data {
+ var data = Data()
+ data.append(BoundaryGenerator.boundaryData(forBoundaryType: .startSymbol, boundary: boundary))
+ data.append(ContentDisposition.formData(params: params).bodyComponent)
+
+ let encodedResult = JSONParser<Item>().encode(from: item)
+ switch encodedResult {
+ case .success(let encodedData):
+ data.append(encodedData)
+ case .failure(let error):
+ print(error.localizedDescription)
+ }
+ data.append(BoundaryGenerator.boundaryData(forBoundaryType: .endSymbol, boundary: boundary))
+
+ return data
+ }
+
+ func createImageFormData(name: String, fileName: String, contentType: ImageContentType, image: UIImage) -> Data {
+ var data = Data()
+ data.append(BoundaryGenerator.boundaryData(forBoundaryType: .startSymbol, boundary: boundary))
+ data.append(ContentDisposition.imageFormData(name: name, filename: fileName).bodyComponent)
+ data.append(ContentDisposition.imageContentType(type: contentType).bodyComponent)
+
+ switch contentType {
+ case .png:
+ if let imageData = image.pngData() {
+ data.append(imageData)
+ }
+ case .jpeg:
+ if let imageData = image.jpegData(compressionQuality: 1) {
+ data.append(imageData)
+ }
+ }
+ data.append(BoundaryGenerator.boundaryData(forBoundaryType: .endSymbol, boundary: boundary))
+
+ return data
+ }
+
+ mutating func closeBody() {
+ self.body.append(BoundaryGenerator.boundaryData(forBoundaryType: .terminator, boundary: boundary))
+ }
+}
+
+enum ImageContentType: String, CustomStringConvertible {
+ case png
+ case jpeg
+
+ var description: String {
+ return "image/\(rawValue)"
+ }
+}
+
+enum ContentDisposition {
+ case formData(params: String)
+ case imageFormData(name: String, filename: String)
+ case imageContentType(type: ImageContentType)
+
+ var bodyComponent: String {
+ switch self {
+ case .formData(let params):
+ return "Content-Disposition: form-data; name=\"\(params)\""
+ + EncodingCharacters.doubleNewLine
+ case .imageFormData(let name, let filename):
+ return "Content-Disposition: form-data; name=\"\(name)\"; filename=\"\(filename)\""
+ + EncodingCharacters.newLine
+ case .imageContentType(let type):
+ return "Content-Type: \(type.description)" + EncodingCharacters.doubleNewLine
+ }
+ }
+}
+
+enum EncodingCharacters {
+ static let newLine = "\r\n"
+ static let doubleNewLine = "\r\n\r\n"
+}
+
+enum BoundaryGenerator {
+ enum BoundaryType {
+ case startSymbol, endSymbol, terminator
+ }
+
+ static func boundaryData(forBoundaryType boundaryType: BoundaryType, boundary: String) -> Data {
+ let boundaryText: String
+
+ switch boundaryType {
+ case .startSymbol:
+ boundaryText = "--\(boundary)\(EncodingCharacters.newLine)"
+ case .endSymbol:
+ boundaryText = "\(EncodingCharacters.newLine)"
+ case .terminator:
+ boundaryText = "--\(boundary)--"
+ }
+
+ return Data(boundaryText.utf8)
+ }
+}
+
+private extension Data {
+ mutating func append(_ string: String?) {
+ if let stringData = string?.data(using: .utf8) {
+ self.append(stringData)
+ }
+ }
+} | Swift | static method๊ฐ ๋์ ๊ฑธ๋ฆฌ๋ค์.
์ ๋ ๊ฐ์ฒด ์์ฑ ํ๋ ๊ฒ์ด ๋ ์ข๋ค๊ณ ์๊ฐํฉ๋๋ค. ์ ํ์ด ๊ทธ๋ ๊ฒ ํ๊ณ ์๊ณ ์. (JsonDecoder ๋ฑ.)
BoundaryGenerator().data(forType: .startSymblol) ๊ณผ ๊ฐ์ ์คํ์ผ์ด ๋๋ฉด ์ข๊ฒ ์ต๋๋ค. |
@@ -0,0 +1,102 @@
+import Foundation
+import RxSwift
+
+enum NetworkError: Error, LocalizedError {
+ case statusCodeError
+ case unknownError
+ case urlIsNil
+
+ var errorDescription: String? {
+ switch self {
+ case .statusCodeError:
+ return "์ ์์ ์ธ StatusCode๊ฐ ์๋๋๋ค."
+ case .unknownError:
+ return "์์ ์๋ ์๋ฌ๊ฐ ๋ฐ์ํ์ต๋๋ค."
+ case .urlIsNil:
+ return "์ ์์ ์ธ URL์ด ์๋๋๋ค."
+ }
+ }
+}
+
+struct NetworkProvider {
+ private let session: URLSessionProtocol
+ private let disposeBag = DisposeBag()
+
+ init(session: URLSessionProtocol = URLSession.shared) {
+ self.session = session
+ }
+
+ private func loadData(request: URLRequest) -> Observable<Data> {
+ return Observable.create { emitter in
+ let task = session.dataTask(with: request) { data, response, _ in
+ let successStatusCode = 200..<300
+ guard let httpResponse = response as? HTTPURLResponse,
+ successStatusCode.contains(httpResponse.statusCode) else {
+ emitter.onError(NetworkError.statusCodeError)
+ return
+ }
+
+ if let data = data {
+ emitter.onNext(data)
+ }
+
+ emitter.onCompleted()
+ }
+ task.resume()
+
+ return Disposables.create {
+ task.cancel()
+ }
+ }
+ }
+
+ func request(api: APIProtocol) -> Observable<Data> {
+ return Observable.create { emitter in
+ guard let urlRequest = URLRequest(api: api) else {
+ emitter.onError(NetworkError.urlIsNil)
+ return Disposables.create()
+ }
+
+ _ = loadData(request: urlRequest)
+ .subscribe { event in
+ switch event {
+ case .next(let data):
+ emitter.onNext(data)
+ case .error(let error):
+ emitter.onError(error)
+ case .completed:
+ emitter.onCompleted()
+ }
+ emitter.onCompleted()
+ }
+ .disposed(by: disposeBag)
+
+ return Disposables.create()
+ }
+ }
+
+ func fetchData<T: Codable>(api: Gettable, decodingType: T.Type) -> Observable<T> {
+ return Observable.create { emitter in
+ _ = request(api: api)
+ .debug() // FIXME: ์์ผ๋ฉด products๊ฐ nil์ด ๋จ
+ .subscribe { event in
+ switch event {
+ case .next(let data):
+ guard let decodedData = JSONParser<T>().decode(from: data) else {
+ emitter.onError(JSONParserError.decodingFail)
+ return
+ }
+ emitter.onNext(decodedData)
+ case .error(let error):
+ emitter.onError(error)
+ case .completed:
+ emitter.onCompleted()
+ }
+ emitter.onCompleted()
+ }
+ .disposed(by: disposeBag)
+
+ return Disposables.create()
+ }
+ }
+} | Swift | NetworkProvider().request(api: api) ์ ๋ชจ์์ด ๋์ฌ ๊ฒ ๊ฐ์๋ฐ์.
๋งค ์ผ์ด์ค๋ง๋ค ๋ค๋ฅธ NetworkProvider๊ฐ ํ์ํด ๋ณด์ด์ง๋ ์๊ณ ์.
NetworkProvider ๋ฅผ ๋งค๋ฒ ์ป์ด์์ผ ํ๋๊ฒ ๋ฒ๊ฑฐ๋ก์๋ณด์ฌ์.
api.execute()๋ ์ด๋จ๊น์. excute ์์ NetworkProvider์ ๋ก์ง์ ๋ด๋๊ฑฐ์ฃ .
์๋ก ๋ค๋ฅธ provider๊ฐ ํ์ํ๋ค๋ฉด, APIProtocol ๋ด๋ถ์ ๋ช
์ํ๋ ์์ผ๋ก ํด๊ฒฐํ๋ฉด ๋ ๊ฒ ๊ฐ๊ณ ์. |
@@ -0,0 +1,102 @@
+import Foundation
+import RxSwift
+
+enum NetworkError: Error, LocalizedError {
+ case statusCodeError
+ case unknownError
+ case urlIsNil
+
+ var errorDescription: String? {
+ switch self {
+ case .statusCodeError:
+ return "์ ์์ ์ธ StatusCode๊ฐ ์๋๋๋ค."
+ case .unknownError:
+ return "์์ ์๋ ์๋ฌ๊ฐ ๋ฐ์ํ์ต๋๋ค."
+ case .urlIsNil:
+ return "์ ์์ ์ธ URL์ด ์๋๋๋ค."
+ }
+ }
+}
+
+struct NetworkProvider {
+ private let session: URLSessionProtocol
+ private let disposeBag = DisposeBag()
+
+ init(session: URLSessionProtocol = URLSession.shared) {
+ self.session = session
+ }
+
+ private func loadData(request: URLRequest) -> Observable<Data> {
+ return Observable.create { emitter in
+ let task = session.dataTask(with: request) { data, response, _ in
+ let successStatusCode = 200..<300
+ guard let httpResponse = response as? HTTPURLResponse,
+ successStatusCode.contains(httpResponse.statusCode) else {
+ emitter.onError(NetworkError.statusCodeError)
+ return
+ }
+
+ if let data = data {
+ emitter.onNext(data)
+ }
+
+ emitter.onCompleted()
+ }
+ task.resume()
+
+ return Disposables.create {
+ task.cancel()
+ }
+ }
+ }
+
+ func request(api: APIProtocol) -> Observable<Data> {
+ return Observable.create { emitter in
+ guard let urlRequest = URLRequest(api: api) else {
+ emitter.onError(NetworkError.urlIsNil)
+ return Disposables.create()
+ }
+
+ _ = loadData(request: urlRequest)
+ .subscribe { event in
+ switch event {
+ case .next(let data):
+ emitter.onNext(data)
+ case .error(let error):
+ emitter.onError(error)
+ case .completed:
+ emitter.onCompleted()
+ }
+ emitter.onCompleted()
+ }
+ .disposed(by: disposeBag)
+
+ return Disposables.create()
+ }
+ }
+
+ func fetchData<T: Codable>(api: Gettable, decodingType: T.Type) -> Observable<T> {
+ return Observable.create { emitter in
+ _ = request(api: api)
+ .debug() // FIXME: ์์ผ๋ฉด products๊ฐ nil์ด ๋จ
+ .subscribe { event in
+ switch event {
+ case .next(let data):
+ guard let decodedData = JSONParser<T>().decode(from: data) else {
+ emitter.onError(JSONParserError.decodingFail)
+ return
+ }
+ emitter.onNext(decodedData)
+ case .error(let error):
+ emitter.onError(error)
+ case .completed:
+ emitter.onCompleted()
+ }
+ emitter.onCompleted()
+ }
+ .disposed(by: disposeBag)
+
+ return Disposables.create()
+ }
+ }
+} | Swift | Observable.create ๊ฐ ํ์ํ์ง ์์๋ณด์
๋๋ค. |
@@ -0,0 +1,52 @@
+import Foundation
+
+struct OpenMarketBaseURL: BaseURLProtocol {
+ var baseURL = "https://market-training.yagom-academy.kr/"
+}
+
+struct HealthCheckerAPI: Gettable {
+ var url: URL?
+ var method: HttpMethod = .get
+
+ init(baseURL: BaseURLProtocol = OpenMarketBaseURL()) {
+ self.url = URL(string: "\(baseURL.baseURL)healthChecker")
+ }
+}
+
+struct ProductDetailAPI: Gettable {
+ var url: URL?
+ var method: HttpMethod = .get
+
+ init(id: Int, baseURL: BaseURLProtocol = OpenMarketBaseURL()) {
+ self.url = URL(string: "\(baseURL.baseURL)api/products/\(id)")
+ }
+}
+
+struct ProductPageAPI: Gettable {
+ var url: URL?
+ var method: HttpMethod = .get
+
+ init(pageNumber: Int, itemsPerPage: Int, baseURL: BaseURLProtocol = OpenMarketBaseURL()) {
+ var urlComponents = URLComponents(string: "\(baseURL.baseURL)api/products?")
+ let pageNumberQuery = URLQueryItem(name: "page_no", value: "\(pageNumber)")
+ let itemsPerPageQuery = URLQueryItem(name: "items_per_page", value: "\(itemsPerPage)")
+ urlComponents?.queryItems?.append(pageNumberQuery)
+ urlComponents?.queryItems?.append(itemsPerPageQuery)
+
+ self.url = urlComponents?.url
+ }
+}
+
+struct ProductRegisterAPI: Postable {
+ var url: URL?
+ var method: HttpMethod = .post
+ var identifier: String = "1061fe9a-7215-11ec-abfa-951effcf9a75"
+ var contentType: String
+ var body: Data?
+
+ init(boundary: String, body: Data, baseURL: BaseURLProtocol = OpenMarketBaseURL()) {
+ self.url = URL(string: "\(baseURL.baseURL)api/products")
+ self.contentType = "multipart/form-data; boundary=\(boundary)"
+ self.body = body
+ }
+} | Swift | var / let ํ์ธ ๋ฐ๋๋๋ค. |
@@ -0,0 +1,37 @@
+import UIKit
+
+struct FlowCoordinator {
+ // MARK: - Properties
+ weak private var navigationController: UINavigationController?
+ private var productListViewController: ProductListViewController!
+ private var productListViewModel: ProductListViewModel!
+ private var menuSegmentedControl: MenuSegmentedControl!
+ private var menuSegmentedControlViewModel: MenuSegmentedControlViewModel!
+
+ // MARK: - Initializers
+ init(navigationController: UINavigationController) {
+ self.navigationController = navigationController
+ }
+
+ // MARK: - Methods
+ mutating func start() {
+ let actions = ProductListViewModelAction(showProductDetail: showProductDetail)
+
+ productListViewModel = ProductListViewModel(actions: actions)
+ menuSegmentedControlViewModel = MenuSegmentedControlViewModel()
+ menuSegmentedControl = MenuSegmentedControl(viewModel: menuSegmentedControlViewModel)
+ productListViewController = ProductListViewController(viewModel: productListViewModel,
+ menuSegmentedControl: menuSegmentedControl)
+ menuSegmentedControlViewModel.delegate = productListViewController
+
+ navigationController?.pushViewController(productListViewController, animated: false)
+ }
+
+ func showProductDetail(with productID: Int) {
+ let productDetailViewModel = ProductDetailViewModel()
+ let productDetailViewController = ProductDetailViewController(viewModel: productDetailViewModel)
+ productDetailViewModel.setupProductID(productID)
+
+ navigationController?.pushViewController(productDetailViewController, animated: true)
+ }
+} | Swift | class type์ property๋ก ๋ค๊ณ ์์ผ๋, struct๋ณด๋ค๋ class๊ฐ ์ด์ธ๋ ค๋ณด์
๋๋ค. |
@@ -0,0 +1,37 @@
+import UIKit
+
+struct FlowCoordinator {
+ // MARK: - Properties
+ weak private var navigationController: UINavigationController?
+ private var productListViewController: ProductListViewController!
+ private var productListViewModel: ProductListViewModel!
+ private var menuSegmentedControl: MenuSegmentedControl!
+ private var menuSegmentedControlViewModel: MenuSegmentedControlViewModel!
+
+ // MARK: - Initializers
+ init(navigationController: UINavigationController) {
+ self.navigationController = navigationController
+ }
+
+ // MARK: - Methods
+ mutating func start() {
+ let actions = ProductListViewModelAction(showProductDetail: showProductDetail)
+
+ productListViewModel = ProductListViewModel(actions: actions)
+ menuSegmentedControlViewModel = MenuSegmentedControlViewModel()
+ menuSegmentedControl = MenuSegmentedControl(viewModel: menuSegmentedControlViewModel)
+ productListViewController = ProductListViewController(viewModel: productListViewModel,
+ menuSegmentedControl: menuSegmentedControl)
+ menuSegmentedControlViewModel.delegate = productListViewController
+
+ navigationController?.pushViewController(productListViewController, animated: false)
+ }
+
+ func showProductDetail(with productID: Int) {
+ let productDetailViewModel = ProductDetailViewModel()
+ let productDetailViewController = ProductDetailViewController(viewModel: productDetailViewModel)
+ productDetailViewModel.setupProductID(productID)
+
+ navigationController?.pushViewController(productDetailViewController, animated: true)
+ }
+} | Swift | !๋ ์ฐ์ง ์๋๊ฑธ๋ก ํด์. |
@@ -0,0 +1,37 @@
+import UIKit
+
+struct FlowCoordinator {
+ // MARK: - Properties
+ weak private var navigationController: UINavigationController?
+ private var productListViewController: ProductListViewController!
+ private var productListViewModel: ProductListViewModel!
+ private var menuSegmentedControl: MenuSegmentedControl!
+ private var menuSegmentedControlViewModel: MenuSegmentedControlViewModel!
+
+ // MARK: - Initializers
+ init(navigationController: UINavigationController) {
+ self.navigationController = navigationController
+ }
+
+ // MARK: - Methods
+ mutating func start() {
+ let actions = ProductListViewModelAction(showProductDetail: showProductDetail)
+
+ productListViewModel = ProductListViewModel(actions: actions)
+ menuSegmentedControlViewModel = MenuSegmentedControlViewModel()
+ menuSegmentedControl = MenuSegmentedControl(viewModel: menuSegmentedControlViewModel)
+ productListViewController = ProductListViewController(viewModel: productListViewModel,
+ menuSegmentedControl: menuSegmentedControl)
+ menuSegmentedControlViewModel.delegate = productListViewController
+
+ navigationController?.pushViewController(productListViewController, animated: false)
+ }
+
+ func showProductDetail(with productID: Int) {
+ let productDetailViewModel = ProductDetailViewModel()
+ let productDetailViewController = ProductDetailViewController(viewModel: productDetailViewModel)
+ productDetailViewModel.setupProductID(productID)
+
+ navigationController?.pushViewController(productDetailViewController, animated: true)
+ }
+} | Swift | FlowCoordinator ๊ฐ ๋ค๋ฅด๊ฒ ๋งํ๋ฉด AppLevel์ Coordinator๋ก ์ดํด๋๋๋ฐ์. ProductList์ ๋ก์ง๊ณผ ์์กด์ฑ์ด ์ปค์ ProductList ์ ์ฉ Coordinator ์ฒ๋ผ ๋ณด์
๋๋ค. ์ ๋ผ๋ฉด ProductListCoordinator ์ ๋๋ฅผ ๋ง๋ค์ด์ ProductList ๋ก์ง์ ๋ชจ๋ํํ๊ณ ์. FlowCoordinator์ rootCoordinator๋ฅผ ProductListCoordinator ๋ก ๋์ด์ FlowCoordinator์ ProductListCoordinator์ ๊ด๊ณ๋ฅผ ๋ถ๋ฆฌํ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,46 @@
+import UIKit
+
+class ProductDetailImageCell: UICollectionViewCell {
+ // MARK: - Properties
+ private let productImageView: UIImageView = {
+ let imageView = UIImageView()
+ imageView.translatesAutoresizingMaskIntoConstraints = false
+ imageView.contentMode = .scaleAspectFill
+ imageView.heightAnchor.constraint(equalTo: imageView.widthAnchor).isActive = true
+ imageView.layer.cornerRadius = 6
+ imageView.backgroundColor = .black
+ imageView.clipsToBounds = true
+ return imageView
+ }()
+
+ // MARK: - Initializers
+ override init(frame: CGRect) {
+ super.init(frame: frame)
+ configureUI()
+ }
+
+ required init?(coder: NSCoder) {
+ fatalError("init(coder:) has not been implemented")
+ }
+
+ // MARK: - Lifecycle Methods
+ override func prepareForReuse() {
+ super.prepareForReuse()
+ productImageView.image = nil
+ }
+
+ // MARK: - Methods
+ func apply(with imageURL: String) {
+ productImageView.loadImage(of: imageURL)
+ }
+
+ private func configureUI() {
+ addSubview(productImageView)
+ NSLayoutConstraint.activate([
+ productImageView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
+ productImageView.trailingAnchor.constraint(equalTo: self.trailingAnchor),
+ productImageView.topAnchor.constraint(equalTo: self.topAnchor),
+ productImageView.bottomAnchor.constraint(equalTo: self.bottomAnchor)
+ ])
+ }
+} | Swift | ์ด ๊ฒฝ์ฐ init์ param์ด ์์ผ๋ฏ๋ก, init coder ์ด๋ ค๋ ๋ ๊ฒ ๊ฐ์์.
required init?(coder: NSCoder) {
super.init(coder: coder)
configureUI()
} |
@@ -0,0 +1,57 @@
+import Foundation
+import RxSwift
+import UIKit
+
+class ProductDetailViewModel {
+ // MARK: - Nested Types
+ struct Input {
+ let invokedViewDidLoad: Observable<Void>
+ let cellDidScroll: Observable<IndexPath>
+ }
+
+ struct Output {
+ let product: Observable<DetailViewProduct>
+ let productImages: Observable<[ProductImage]>
+ }
+
+ // MARK: - Properties
+ private var productID: Int!
+ private let disposeBag = DisposeBag()
+
+ // MARK: - Methods
+ func setupProductID(_ productID: Int) {
+ self.productID = productID
+ }
+
+ func transform(_ input: Input) -> Output {
+ let product = PublishSubject<DetailViewProduct>()
+ let productImages = PublishSubject<[ProductImage]>()
+
+ configureViewDidLoadObserver(by: input.invokedViewDidLoad, productOutput: product, productImages: productImages)
+
+ let output = Output(product: product.asObservable(), productImages: productImages.asObservable())
+
+ return output
+ }
+
+ private func configureViewDidLoadObserver(by inputObserver: Observable<Void>,
+ productOutput: PublishSubject<DetailViewProduct>,
+ productImages: PublishSubject<[ProductImage]>) {
+ inputObserver
+ .subscribe(onNext: {[weak self] _ in
+ guard let self = self else { return }
+ _ = self.fetchProduct(with: self.productID).subscribe(onNext: { productDetail in
+ productOutput.onNext(productDetail)
+ productImages.onNext(productDetail.images)
+ })
+ })
+ .disposed(by: disposeBag)
+ }
+
+ private func fetchProduct(with id: Int) -> Observable<DetailViewProduct> {
+ let networkProvider = NetworkProvider()
+ let observable = networkProvider.fetchData(api: ProductDetailAPI(id: id), decodingType: DetailViewProduct.self)
+
+ return observable
+ }
+} | Swift | inputObserver ์ fetchProduct ๋ฅผ flatMap์ผ๋ก ์ฎ์ด์ product observer๋ฅผ ๋ง๋ค ์ ์์ ๊ฒ ๊ฐ๋ค์. ๊ณ ๋ฏผํด๋ด์ฃผ์ธ์. subscribe๋ ๊ผญ ํ์ํ ์์น์๋ง ํด์ฃผ์ธ์. |
@@ -0,0 +1,57 @@
+import Foundation
+import RxSwift
+import UIKit
+
+class ProductDetailViewModel {
+ // MARK: - Nested Types
+ struct Input {
+ let invokedViewDidLoad: Observable<Void>
+ let cellDidScroll: Observable<IndexPath>
+ }
+
+ struct Output {
+ let product: Observable<DetailViewProduct>
+ let productImages: Observable<[ProductImage]>
+ }
+
+ // MARK: - Properties
+ private var productID: Int!
+ private let disposeBag = DisposeBag()
+
+ // MARK: - Methods
+ func setupProductID(_ productID: Int) {
+ self.productID = productID
+ }
+
+ func transform(_ input: Input) -> Output {
+ let product = PublishSubject<DetailViewProduct>()
+ let productImages = PublishSubject<[ProductImage]>()
+
+ configureViewDidLoadObserver(by: input.invokedViewDidLoad, productOutput: product, productImages: productImages)
+
+ let output = Output(product: product.asObservable(), productImages: productImages.asObservable())
+
+ return output
+ }
+
+ private func configureViewDidLoadObserver(by inputObserver: Observable<Void>,
+ productOutput: PublishSubject<DetailViewProduct>,
+ productImages: PublishSubject<[ProductImage]>) {
+ inputObserver
+ .subscribe(onNext: {[weak self] _ in
+ guard let self = self else { return }
+ _ = self.fetchProduct(with: self.productID).subscribe(onNext: { productDetail in
+ productOutput.onNext(productDetail)
+ productImages.onNext(productDetail.images)
+ })
+ })
+ .disposed(by: disposeBag)
+ }
+
+ private func fetchProduct(with id: Int) -> Observable<DetailViewProduct> {
+ let networkProvider = NetworkProvider()
+ let observable = networkProvider.fetchData(api: ProductDetailAPI(id: id), decodingType: DetailViewProduct.self)
+
+ return observable
+ }
+} | Swift | output ํ๋ผ๋ฏธํฐ๊ฐ ๋ง์ด ๋ณด์ด๋๋ฐ์. ๋ง์น inout ํค์๋์ ๋น์ทํ ๊ธฐ๋ฅ์ ํ๋ ๊ฒ์ผ๋ก ์ข์ ์ฝ๋๋ก ๋ณด์ด์ง ์์ต๋๋ค. output์ ํ๊ณ ์ถ๋ค๋ฉด return type์ ์ฐ๋ฉด ๋ฉ๋๋ค. |
@@ -0,0 +1,53 @@
+import UIKit
+
+final class BannerCell: UICollectionViewCell {
+ // MARK: - Properties
+ private let stackView: UIStackView = {
+ let stackView = UIStackView()
+ stackView.style(axis: .vertical, alignment: .fill, distribution: .fill)
+ return stackView
+ }()
+ private let imageView: UIImageView = {
+ let imageView = UIImageView()
+ imageView.heightAnchor.constraint(equalTo: imageView.widthAnchor).isActive = true
+ imageView.translatesAutoresizingMaskIntoConstraints = false
+ imageView.contentMode = .scaleAspectFill
+ return imageView
+ }()
+
+ private(set) var productID: Int = 0
+
+ // MARK: - Initializers
+ override init(frame: CGRect) {
+ super.init(frame: frame)
+ configureUI()
+ }
+
+ @available(*, unavailable)
+ required init?(coder: NSCoder) {
+ fatalError("init(coder:) has not been implemented")
+ }
+
+ // MARK: - Lifecycle Methods
+ override func prepareForReuse() {
+ super.prepareForReuse()
+ imageView.image = nil
+ }
+
+ // MARK: - Methods
+ func apply(imageURL: String, productID: Int) {
+ imageView.loadImage(of: imageURL)
+ self.productID = productID
+ }
+
+ private func configureUI() {
+ addSubview(stackView)
+ stackView.addArrangedSubview(imageView)
+ NSLayoutConstraint.activate([
+ stackView.topAnchor.constraint(equalTo: self.topAnchor),
+ stackView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
+ stackView.trailingAnchor.constraint(equalTo: self.trailingAnchor),
+ stackView.bottomAnchor.constraint(equalTo: self.bottomAnchor)
+ ])
+ }
+} | Swift | reusable cell์ storable property๋ฅผ ๋ค๊ณ ์์ ์ด์ ๊ฐ ๊ฑฐ์ ์์ต๋๋ค.
cell์ UI ๊ป๋ฐ๊ธฐ ์ผ ๋ฟ์ด์ง, ํน์ ๋ฐ์ดํฐ๋ฅผ ๋ํํ ์ ์์ต๋๋ค.
apply์ชฝ์๋ UI ์ธํ
์ ์ํ ViewModel ๋ง ์ ๋ฌ ํ๋ฉด ๋๊ณ ์.
์ด cell์ด ์ด๋ค productID๋ก ๊ตฌ์ฑ๋์๋์ง ๊ถ๊ธํ๋ค๋ฉด, cell์ indexPath๋ฅผ ์ด์ฉํด์ ์ง์ ์ป์ด๋ด๋ฉด ๋ฉ๋๋ค. |
@@ -0,0 +1,53 @@
+import UIKit
+import RxSwift
+import RxCocoa
+
+final class FooterView: UICollectionReusableView {
+ // MARK: - Properties
+ private let bannerPageControl: UIPageControl = {
+ let pageControl = UIPageControl()
+ pageControl.translatesAutoresizingMaskIntoConstraints = false
+ pageControl.pageIndicatorTintColor = .systemGray2
+ pageControl.currentPageIndicatorTintColor = CustomColor.darkGreenColor
+ pageControl.currentPage = 0
+ pageControl.isUserInteractionEnabled = false
+ return pageControl
+ }()
+
+ private let disposeBag = DisposeBag()
+
+ // MARK: - Initializers
+ override init(frame: CGRect) {
+ super.init(frame: frame)
+ configureUI()
+ }
+
+ @available(*, unavailable)
+ required init?(coder: NSCoder) {
+ fatalError("init(coder:) has not been implemented")
+ }
+
+ // MARK: - Methods
+ func bind(input: Observable<Int>, indexPath: IndexPath, pageNumber: Int) {
+ bannerPageControl.numberOfPages = pageNumber
+ if indexPath.section == 1 {
+ self.isHidden = true
+ } else {
+ input
+ .subscribe(onNext: { [weak self] currentPage in
+ self?.bannerPageControl.currentPage = currentPage
+ })
+ .disposed(by: disposeBag)
+ }
+ }
+
+ private func configureUI() {
+ addSubview(bannerPageControl)
+ NSLayoutConstraint.activate([
+ bannerPageControl.topAnchor.constraint(equalTo: topAnchor),
+ bannerPageControl.bottomAnchor.constraint(equalTo: bottomAnchor),
+ bannerPageControl.leadingAnchor.constraint(equalTo: leadingAnchor),
+ bannerPageControl.trailingAnchor.constraint(equalTo: trailingAnchor)
+ ])
+ }
+} | Swift | bind๊ฐ N๋ฒ ํธ์ถ๋์์ ๋ subscribe๊ฐ N๋ฒ ๋ ๊ฐ๋ฅ์ฑ์ ์์์ง ๊ฒํ ๋ฐ๋๋๋ค. |
@@ -0,0 +1,176 @@
+import UIKit
+
+final class GridListCell: UICollectionViewCell {
+ // MARK: - Nested Types
+ private enum Design {
+ static let nameLabelTextColor: UIColor = .black
+ static let stockLabelTextColor: UIColor = .systemOrange
+ static let priceLabelTextColor: UIColor = .systemRed
+ static let discountedPriceLabelTextColor: UIColor = .systemGray
+ static let bargainRateLabelTextColor: UIColor = .systemRed
+
+ static let nameLabelFont: UIFont = .preferredFont(forTextStyle: .title3)
+ static let stockLabelFont: UIFont = .preferredFont(forTextStyle: .title3)
+ static let priceLabelFont: UIFont = .preferredFont(forTextStyle: .headline)
+ static let bargainRateLabelFont: UIFont = .preferredFont(forTextStyle: .body)
+
+ static let accessoryImageName: String = "chevron.right"
+ }
+
+ private enum Content {
+ static let outOfStockLabelText = "ํ์ "
+ }
+
+ // MARK: - Properties
+ private let containerStackView: UIStackView = {
+ let stackView = UIStackView()
+ stackView.style(axis: .vertical, alignment: .fill, distribution: .fill, spacing: 8)
+ stackView.setupMargins(verticalInset: 15, horizontalInset: 15)
+ return stackView
+ }()
+ private let imageView: UIImageView = {
+ let imageView = UIImageView()
+ imageView.translatesAutoresizingMaskIntoConstraints = false
+ imageView.contentMode = .scaleAspectFit
+ imageView.heightAnchor.constraint(equalTo: imageView.widthAnchor).isActive = true
+ imageView.layer.cornerRadius = 6
+ imageView.clipsToBounds = true
+ return imageView
+ }()
+ private let nameAndStockStackView: UIStackView = {
+ let stackView = UIStackView()
+ stackView.style(axis: .horizontal, alignment: .fill, distribution: .fill)
+ return stackView
+ }()
+ private let nameLabel: UILabel = {
+ let label = UILabel()
+ label.style(textAlignment: .left, font: Design.nameLabelFont, textColor: Design.nameLabelTextColor)
+ label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
+ return label
+ }()
+ private let stockLabel: UILabel = {
+ let label = UILabel()
+ label.style(textAlignment: .right, font: Design.stockLabelFont, textColor: Design.stockLabelTextColor)
+ label.setContentHuggingPriority(.defaultHigh, for: .horizontal)
+ return label
+ }()
+ private let priceContainerStackView: UIStackView = {
+ let stackView = UIStackView()
+ stackView.style(axis: .horizontal, alignment: .top, distribution: .fill, spacing: 8)
+ return stackView
+ }()
+ private let priceAndBargainpriceStackView: UIStackView = {
+ let stackView = UIStackView()
+ stackView.style(axis: .vertical, alignment: .fill, distribution: .fill)
+ return stackView
+ }()
+ private let priceLabel: UILabel = {
+ let label = UILabel()
+ label.style(textAlignment: .left, font: Design.priceLabelFont, textColor: Design.priceLabelTextColor)
+ label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
+ return label
+ }()
+ private let bargainPriceLabel: UILabel = {
+ let label = UILabel()
+ label.style(textAlignment: .left, font: Design.priceLabelFont, textColor: Design.priceLabelTextColor)
+ label.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
+ return label
+ }()
+ private let bargainRateLabel: UILabel = {
+ let label = UILabel()
+ label.style(textAlignment: .right, font: Design.bargainRateLabelFont, textColor: Design.bargainRateLabelTextColor)
+ return label
+ }()
+
+ private(set) var productID: Int = 0
+
+ // MARK: - Initializers
+ override init(frame: CGRect) {
+ super.init(frame: frame)
+ configureUI()
+ }
+
+ @available(*, unavailable)
+ required init?(coder: NSCoder) {
+ fatalError("init(coder:) has not been implemented")
+ }
+
+ // MARK: - Lifecycle Methods
+ override func prepareForReuse() {
+ super.prepareForReuse()
+ imageView.image = nil
+ nameLabel.text = nil
+ stockLabel.text = nil
+ bargainPriceLabel.text = nil
+ bargainPriceLabel.isHidden = true
+ bargainRateLabel.text = nil
+ priceLabel.attributedText = nil
+ priceLabel.text = nil
+ priceLabel.textColor = Design.priceLabelTextColor
+ stockLabel.isHidden = true
+ }
+
+ // MARK: - Methods
+ func apply(data: Product) {
+ imageView.loadImage(of: data.thumbnail)
+ nameLabel.text = data.name
+ changePriceAndDiscountedPriceLabel(price: data.price,
+ discountedPrice: data.discountedPrice,
+ bargainPrice: data.bargainPrice,
+ currency: data.currency)
+ changeStockLabel(by: data.stock)
+ calculateBargainRate(price: data.price, discountedPrice: data.discountedPrice)
+ self.productID = data.id
+ }
+
+ private func configureUI() {
+ addSubview(containerStackView)
+ NSLayoutConstraint.activate([
+ containerStackView.topAnchor.constraint(equalTo: self.topAnchor),
+ containerStackView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
+ containerStackView.trailingAnchor.constraint(equalTo: self.trailingAnchor),
+ containerStackView.bottomAnchor.constraint(equalTo: self.bottomAnchor)
+ ])
+ containerStackView.addArrangedSubview(imageView)
+ containerStackView.addArrangedSubview(nameAndStockStackView)
+ containerStackView.addArrangedSubview(priceContainerStackView)
+
+ nameAndStockStackView.addArrangedSubview(nameLabel)
+ nameAndStockStackView.addArrangedSubview(stockLabel)
+
+ priceContainerStackView.addArrangedSubview(priceAndBargainpriceStackView)
+ priceContainerStackView.addArrangedSubview(bargainRateLabel)
+ priceAndBargainpriceStackView.addArrangedSubview(bargainPriceLabel)
+ priceAndBargainpriceStackView.addArrangedSubview(priceLabel)
+ }
+
+ private func changePriceAndDiscountedPriceLabel(price: Double,
+ discountedPrice: Double,
+ bargainPrice: Double,
+ currency: Currency) {
+ if discountedPrice == 0 {
+ priceLabel.text = "\(currency.rawValue) \(price.formattedWithComma())"
+ } else {
+ let priceText = "\(currency.rawValue) \(price.formattedWithComma())"
+ priceLabel.strikeThrough(text: priceText)
+ priceLabel.textColor = Design.discountedPriceLabelTextColor
+ bargainPriceLabel.isHidden = false
+ bargainPriceLabel.text = "\(currency.rawValue) \(bargainPrice.formattedWithComma())"
+ }
+ }
+
+ private func changeStockLabel(by stock: Int) {
+ if stock == 0 {
+ stockLabel.isHidden = false
+ stockLabel.text = Content.outOfStockLabelText
+ }
+ }
+
+ private func calculateBargainRate(price: Double, discountedPrice: Double) {
+ let bargainRate = ceil(discountedPrice / price * 100)
+
+ if discountedPrice != .zero {
+ bargainRateLabel.text = "\(String(format: "%.0f", bargainRate))%"
+ }
+ }
+} | Swift | ์ ๋ Design์ ํ์ผ ์ต ํ๋จ์ผ๋ก ๋บด๊ณ ์์ต๋๋ค.
ํ ๋ฒ ์์ฑ๋๋ฉด ๋ณผ ์ผ์ด ๊ฑฐ์ ์๋ ์ฝ๋๋ผ์์. |
@@ -0,0 +1,22 @@
+import UIKit
+
+extension UIStackView {
+ func style(axis: NSLayoutConstraint.Axis,
+ alignment: UIStackView.Alignment,
+ distribution: UIStackView.Distribution,
+ spacing: CGFloat = .zero) {
+ self.translatesAutoresizingMaskIntoConstraints = false
+ self.axis = axis
+ self.alignment = alignment
+ self.distribution = distribution
+ self.spacing = spacing
+ }
+
+ func setupMargins(verticalInset: CGFloat = .zero, horizontalInset: CGFloat = .zero) {
+ self.layoutMargins = UIEdgeInsets(top: verticalInset,
+ left: horizontalInset,
+ bottom: verticalInset,
+ right: horizontalInset)
+ self.isLayoutMarginsRelativeArrangement = true
+ }
+} | Swift | ์ด๋ถ๋ถ์ ํ๋กํผํฐ๋ฅผ ํด๋ก์ ๋ก ์์ฑํ๋ ๋ถ๋ถ์์ ๋ฐ๋ณต๋๋ ๋ถ๋ถ์ด ๋ง์ ๋ฉ์๋๋ฅผ ํตํด ํ๋กํผํฐ๋ฅผ setํ ์ ์๋๋ก ํ์ต๋๋ค!! |
@@ -0,0 +1,24 @@
+import UIKit
+
+extension UIImageView {
+ func loadImage(of key: String) {
+ let cacheKey = NSString(string: key)
+ if let cachedImage = ImageCacheManager.shared.object(forKey: cacheKey) {
+ self.image = cachedImage
+ return
+ }
+
+ DispatchQueue.global().async {
+ guard let imageURL = URL(string: key),
+ let imageData = try? Data(contentsOf: imageURL),
+ let loadedImage = UIImage(data: imageData) else {
+ return
+ }
+ ImageCacheManager.shared.setObject(loadedImage, forKey: cacheKey)
+
+ DispatchQueue.main.async {
+ self.image = loadedImage
+ }
+ }
+ }
+} | Swift | ๋ง์ํด์ฃผ์ ๋๋ก ๋ฉ์๋์ด๋ฆ๋ง ๋ด์๋ Cache ๊ธฐ๋ฅ์ ๋ดํฌํ๋ ๊ฒ์ ์ ์ ์์ด์ loadCachedImage(of key: String)๋ก ์์ ํ์ต๋๋ค! |
@@ -0,0 +1,120 @@
+import UIKit
+
+struct MultipartFormData {
+ private(set) var boundary: String
+ let contentType: String
+ private(set) var body: Data = Data()
+
+ init(uuid: String = UUID().uuidString) {
+ self.boundary = "Boundary-\(uuid)"
+ self.contentType = "multipart/form-data; boundary=\(self.boundary)"
+ }
+
+ mutating func appendToBody(from data: Data) {
+ self.body.append(data)
+ }
+
+ func createFormData<Item: Codable>(params: String, item: Item) -> Data {
+ var data = Data()
+ data.append(BoundaryGenerator.boundaryData(forBoundaryType: .startSymbol, boundary: boundary))
+ data.append(ContentDisposition.formData(params: params).bodyComponent)
+
+ let encodedResult = JSONParser<Item>().encode(from: item)
+ switch encodedResult {
+ case .success(let encodedData):
+ data.append(encodedData)
+ case .failure(let error):
+ print(error.localizedDescription)
+ }
+ data.append(BoundaryGenerator.boundaryData(forBoundaryType: .endSymbol, boundary: boundary))
+
+ return data
+ }
+
+ func createImageFormData(name: String, fileName: String, contentType: ImageContentType, image: UIImage) -> Data {
+ var data = Data()
+ data.append(BoundaryGenerator.boundaryData(forBoundaryType: .startSymbol, boundary: boundary))
+ data.append(ContentDisposition.imageFormData(name: name, filename: fileName).bodyComponent)
+ data.append(ContentDisposition.imageContentType(type: contentType).bodyComponent)
+
+ switch contentType {
+ case .png:
+ if let imageData = image.pngData() {
+ data.append(imageData)
+ }
+ case .jpeg:
+ if let imageData = image.jpegData(compressionQuality: 1) {
+ data.append(imageData)
+ }
+ }
+ data.append(BoundaryGenerator.boundaryData(forBoundaryType: .endSymbol, boundary: boundary))
+
+ return data
+ }
+
+ mutating func closeBody() {
+ self.body.append(BoundaryGenerator.boundaryData(forBoundaryType: .terminator, boundary: boundary))
+ }
+}
+
+enum ImageContentType: String, CustomStringConvertible {
+ case png
+ case jpeg
+
+ var description: String {
+ return "image/\(rawValue)"
+ }
+}
+
+enum ContentDisposition {
+ case formData(params: String)
+ case imageFormData(name: String, filename: String)
+ case imageContentType(type: ImageContentType)
+
+ var bodyComponent: String {
+ switch self {
+ case .formData(let params):
+ return "Content-Disposition: form-data; name=\"\(params)\""
+ + EncodingCharacters.doubleNewLine
+ case .imageFormData(let name, let filename):
+ return "Content-Disposition: form-data; name=\"\(name)\"; filename=\"\(filename)\""
+ + EncodingCharacters.newLine
+ case .imageContentType(let type):
+ return "Content-Type: \(type.description)" + EncodingCharacters.doubleNewLine
+ }
+ }
+}
+
+enum EncodingCharacters {
+ static let newLine = "\r\n"
+ static let doubleNewLine = "\r\n\r\n"
+}
+
+enum BoundaryGenerator {
+ enum BoundaryType {
+ case startSymbol, endSymbol, terminator
+ }
+
+ static func boundaryData(forBoundaryType boundaryType: BoundaryType, boundary: String) -> Data {
+ let boundaryText: String
+
+ switch boundaryType {
+ case .startSymbol:
+ boundaryText = "--\(boundary)\(EncodingCharacters.newLine)"
+ case .endSymbol:
+ boundaryText = "\(EncodingCharacters.newLine)"
+ case .terminator:
+ boundaryText = "--\(boundary)--"
+ }
+
+ return Data(boundaryText.utf8)
+ }
+}
+
+private extension Data {
+ mutating func append(_ string: String?) {
+ if let stringData = string?.data(using: .utf8) {
+ self.append(stringData)
+ }
+ }
+} | Swift | createFormData์ createImageFormData ๋ชจ๋ create๋ก ๋ฉ์๋ ์ด๋ฆ์ ๋ณ๊ฒฝํ๊ณ , ๋งค๊ฐ๋ณ์๋ฅผ ํตํด ๊ตฌ๋ถํ ์ ์๋๋ก ํ์ต๋๋ค. ํ์ฌ ํ๋ก์ ํธ์์ Postํ๋ ํ์
์ด product ๋ฐ์ ์์ผ๋ฏ๋ก item์ product๋ผ๋ ์ด๋ฆ์ผ๋ก ๊ตฌ์ฒดํ์์ผฐ์ต๋๋ค. |
@@ -0,0 +1,52 @@
+import Foundation
+
+struct OpenMarketBaseURL: BaseURLProtocol {
+ var baseURL = "https://market-training.yagom-academy.kr/"
+}
+
+struct HealthCheckerAPI: Gettable {
+ var url: URL?
+ var method: HttpMethod = .get
+
+ init(baseURL: BaseURLProtocol = OpenMarketBaseURL()) {
+ self.url = URL(string: "\(baseURL.baseURL)healthChecker")
+ }
+}
+
+struct ProductDetailAPI: Gettable {
+ var url: URL?
+ var method: HttpMethod = .get
+
+ init(id: Int, baseURL: BaseURLProtocol = OpenMarketBaseURL()) {
+ self.url = URL(string: "\(baseURL.baseURL)api/products/\(id)")
+ }
+}
+
+struct ProductPageAPI: Gettable {
+ var url: URL?
+ var method: HttpMethod = .get
+
+ init(pageNumber: Int, itemsPerPage: Int, baseURL: BaseURLProtocol = OpenMarketBaseURL()) {
+ var urlComponents = URLComponents(string: "\(baseURL.baseURL)api/products?")
+ let pageNumberQuery = URLQueryItem(name: "page_no", value: "\(pageNumber)")
+ let itemsPerPageQuery = URLQueryItem(name: "items_per_page", value: "\(itemsPerPage)")
+ urlComponents?.queryItems?.append(pageNumberQuery)
+ urlComponents?.queryItems?.append(itemsPerPageQuery)
+
+ self.url = urlComponents?.url
+ }
+}
+
+struct ProductRegisterAPI: Postable {
+ var url: URL?
+ var method: HttpMethod = .post
+ var identifier: String = "1061fe9a-7215-11ec-abfa-951effcf9a75"
+ var contentType: String
+ var body: Data?
+
+ init(boundary: String, body: Data, baseURL: BaseURLProtocol = OpenMarketBaseURL()) {
+ self.url = URL(string: "\(baseURL.baseURL)api/products")
+ self.contentType = "multipart/form-data; boundary=\(boundary)"
+ self.body = body
+ }
+} | Swift | ๋ชจ๋ initializer์์ ์ง์ ํ๋ ํ๋กํผํฐ๋ผ์ let์ผ๋ก ๋ณ๊ฒฝํ์ต๋๋ค. |
@@ -0,0 +1,72 @@
+package com.frame2.server.core.board.api;
+
+import com.frame2.server.core.board.application.ProductReviewService;
+import com.frame2.server.core.board.payload.request.ProductReviewModifyRequest;
+import com.frame2.server.core.board.payload.request.ProductReviewRequest;
+import com.frame2.server.core.board.payload.response.ProductReviewResponse;
+import com.frame2.server.core.support.annotations.Auth;
+import com.frame2.server.core.support.annotations.MemberOnly;
+import com.frame2.server.core.support.request.User;
+import jakarta.validation.Valid;
+import lombok.RequiredArgsConstructor;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.*;
+
+import java.util.List;
+
+@RestController
+@RequiredArgsConstructor
+@RequestMapping("/products/{saleProductId}/reviews")
+public class ProductReviewApi implements ProductReviewApiSpec {
+
+ private final ProductReviewService productReviewService;
+
+ // create
+ @Override
+ @MemberOnly
+ @PostMapping
+ public void createProductReview(
+ @Valid @RequestBody ProductReviewRequest productReviewRequest,
+ @Auth User user,
+ @PathVariable("saleProductId") Long saleProductId
+ ) {
+ productReviewService.productReviewCreate(productReviewRequest, user.id(), saleProductId);
+ }
+
+ // update
+ @Override
+ @MemberOnly
+ @PatchMapping("/{productReviewId}")
+ public void updateProductReview(
+ @Valid @RequestBody ProductReviewModifyRequest ProductReviewModifyRequest,
+ @Auth User user,
+ @PathVariable("productReviewId") Long productReviewId
+ ) {
+ productReviewService.productReviewModify(ProductReviewModifyRequest, productReviewId);
+ }
+
+ // delete
+ @Override
+ @MemberOnly
+ @DeleteMapping("/{productReviewId}")
+ public void deleteProductReview(@PathVariable("productReviewId") Long id, @Auth User user) {
+ productReviewService.remove(id);
+ }
+
+ // ๋จ๊ฑด ์กฐํ
+ @Override
+ @GetMapping("/{productReviewId}")
+ public ResponseEntity<ProductReviewResponse> getProductReview(@PathVariable("productReviewId") Long productReviewId) {
+ ProductReviewResponse productReviewResponse = productReviewService.getProductReview(productReviewId);
+ return ResponseEntity.ok().body(productReviewResponse);
+ }
+
+ // ํ ์ํ์ ๋ํ ์ ์ฒด ๋ฆฌ๋ทฐ ์กฐํ
+ @Override
+ @GetMapping
+ public ResponseEntity<List<ProductReviewResponse>> getProductReviewList(
+ @PathVariable("saleProductId") Long saleProductId) {
+ List<ProductReviewResponse> productReviewList = productReviewService.getProductReviewList(saleProductId);
+ return ResponseEntity.ok().body(productReviewList);
+ }
+} | Java | @PatchMapping์ ์๋ํฌ์ธํธ๊ฐ ์ ์๋์ด ์๋๊ฑฐ ๊ฐ์ง ์์ต๋๋ค !
/reviews๋ก ๋ค์ด๊ฐ์ ์ด๋ค ๋ฆฌ๋ทฐ๋ฅผ ์์ ํ๋ ๊ฑธ๊น์? |
@@ -0,0 +1,72 @@
+package com.frame2.server.core.board.api;
+
+import com.frame2.server.core.board.application.ProductReviewService;
+import com.frame2.server.core.board.payload.request.ProductReviewModifyRequest;
+import com.frame2.server.core.board.payload.request.ProductReviewRequest;
+import com.frame2.server.core.board.payload.response.ProductReviewResponse;
+import com.frame2.server.core.support.annotations.Auth;
+import com.frame2.server.core.support.annotations.MemberOnly;
+import com.frame2.server.core.support.request.User;
+import jakarta.validation.Valid;
+import lombok.RequiredArgsConstructor;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.*;
+
+import java.util.List;
+
+@RestController
+@RequiredArgsConstructor
+@RequestMapping("/products/{saleProductId}/reviews")
+public class ProductReviewApi implements ProductReviewApiSpec {
+
+ private final ProductReviewService productReviewService;
+
+ // create
+ @Override
+ @MemberOnly
+ @PostMapping
+ public void createProductReview(
+ @Valid @RequestBody ProductReviewRequest productReviewRequest,
+ @Auth User user,
+ @PathVariable("saleProductId") Long saleProductId
+ ) {
+ productReviewService.productReviewCreate(productReviewRequest, user.id(), saleProductId);
+ }
+
+ // update
+ @Override
+ @MemberOnly
+ @PatchMapping("/{productReviewId}")
+ public void updateProductReview(
+ @Valid @RequestBody ProductReviewModifyRequest ProductReviewModifyRequest,
+ @Auth User user,
+ @PathVariable("productReviewId") Long productReviewId
+ ) {
+ productReviewService.productReviewModify(ProductReviewModifyRequest, productReviewId);
+ }
+
+ // delete
+ @Override
+ @MemberOnly
+ @DeleteMapping("/{productReviewId}")
+ public void deleteProductReview(@PathVariable("productReviewId") Long id, @Auth User user) {
+ productReviewService.remove(id);
+ }
+
+ // ๋จ๊ฑด ์กฐํ
+ @Override
+ @GetMapping("/{productReviewId}")
+ public ResponseEntity<ProductReviewResponse> getProductReview(@PathVariable("productReviewId") Long productReviewId) {
+ ProductReviewResponse productReviewResponse = productReviewService.getProductReview(productReviewId);
+ return ResponseEntity.ok().body(productReviewResponse);
+ }
+
+ // ํ ์ํ์ ๋ํ ์ ์ฒด ๋ฆฌ๋ทฐ ์กฐํ
+ @Override
+ @GetMapping
+ public ResponseEntity<List<ProductReviewResponse>> getProductReviewList(
+ @PathVariable("saleProductId") Long saleProductId) {
+ List<ProductReviewResponse> productReviewList = productReviewService.getProductReviewList(saleProductId);
+ return ResponseEntity.ok().body(productReviewList);
+ }
+} | Java | `createProductReview()`, `getProductReview()`์ ๊ฐ์ด `update()`์ `delete()`์๋ `ProductReview`๋ฅผ ์ถ๊ฐํ๋ฉด ์ข ๋ ์ผ๊ด์ฑ ์๋ ๋ฉ์๋ ์ด๋ฆ์ด ๋ ๊ฒ ๊ฐ์๋ฐ ์ด๋ ์ธ์~?๐ |
@@ -0,0 +1,72 @@
+package com.frame2.server.core.board.api;
+
+import com.frame2.server.core.board.application.ProductReviewService;
+import com.frame2.server.core.board.payload.request.ProductReviewModifyRequest;
+import com.frame2.server.core.board.payload.request.ProductReviewRequest;
+import com.frame2.server.core.board.payload.response.ProductReviewResponse;
+import com.frame2.server.core.support.annotations.Auth;
+import com.frame2.server.core.support.annotations.MemberOnly;
+import com.frame2.server.core.support.request.User;
+import jakarta.validation.Valid;
+import lombok.RequiredArgsConstructor;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.*;
+
+import java.util.List;
+
+@RestController
+@RequiredArgsConstructor
+@RequestMapping("/products/{saleProductId}/reviews")
+public class ProductReviewApi implements ProductReviewApiSpec {
+
+ private final ProductReviewService productReviewService;
+
+ // create
+ @Override
+ @MemberOnly
+ @PostMapping
+ public void createProductReview(
+ @Valid @RequestBody ProductReviewRequest productReviewRequest,
+ @Auth User user,
+ @PathVariable("saleProductId") Long saleProductId
+ ) {
+ productReviewService.productReviewCreate(productReviewRequest, user.id(), saleProductId);
+ }
+
+ // update
+ @Override
+ @MemberOnly
+ @PatchMapping("/{productReviewId}")
+ public void updateProductReview(
+ @Valid @RequestBody ProductReviewModifyRequest ProductReviewModifyRequest,
+ @Auth User user,
+ @PathVariable("productReviewId") Long productReviewId
+ ) {
+ productReviewService.productReviewModify(ProductReviewModifyRequest, productReviewId);
+ }
+
+ // delete
+ @Override
+ @MemberOnly
+ @DeleteMapping("/{productReviewId}")
+ public void deleteProductReview(@PathVariable("productReviewId") Long id, @Auth User user) {
+ productReviewService.remove(id);
+ }
+
+ // ๋จ๊ฑด ์กฐํ
+ @Override
+ @GetMapping("/{productReviewId}")
+ public ResponseEntity<ProductReviewResponse> getProductReview(@PathVariable("productReviewId") Long productReviewId) {
+ ProductReviewResponse productReviewResponse = productReviewService.getProductReview(productReviewId);
+ return ResponseEntity.ok().body(productReviewResponse);
+ }
+
+ // ํ ์ํ์ ๋ํ ์ ์ฒด ๋ฆฌ๋ทฐ ์กฐํ
+ @Override
+ @GetMapping
+ public ResponseEntity<List<ProductReviewResponse>> getProductReviewList(
+ @PathVariable("saleProductId") Long saleProductId) {
+ List<ProductReviewResponse> productReviewList = productReviewService.getProductReviewList(saleProductId);
+ return ResponseEntity.ok().body(productReviewList);
+ }
+} | Java | ๋ฆฌ๋ทฐ ๋จ๊ฑด ์กฐํ์ ์ ์ฒด ์กฐํ์์๋ง ReponseEntity.ok()๋ฅผ ์ฌ์ฉํ์
จ๋๋ฐ,
๋ฆฌ๋ทฐ ๋ฑ๋ก ์ฑ๊ณต์ ๊ฒฝ์ฐ `ResponseEntity.create()`์ ์ฌ์ฉํ ์๋ ์์ ๊ฒ ๊ฐ์์!
ResponseEntity ์ฌ์ฉ๊ณผ Http ์ํ์ฝ๋์ ๋ํด ๊ฐ๋ตํ๊ฒ ์ดํด๋ณด์๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค !!
(์์ ์ด ํ์ํ๋ค๊ณ ์๊ฐํ์ง ์์ต๋๋คโ) |
@@ -0,0 +1,45 @@
+package com.frame2.server.core.board.domain;
+
+import com.frame2.server.core.member.domain.Member;
+import com.frame2.server.core.order.domain.OrderDetail;
+import com.frame2.server.core.product.domain.SaleProduct;
+import com.frame2.server.core.support.entity.BaseEntity;
+import jakarta.persistence.*;
+import lombok.*;
+
+@Entity
+@Getter
+@Builder
+@AllArgsConstructor
+@Table(name = "product_reviews")
+@NoArgsConstructor(access = AccessLevel.PROTECTED)
+public class ProductReview extends BaseEntity {
+
+ @ManyToOne(fetch = FetchType.LAZY)
+ @JoinColumn(name = "sale_product_id", nullable = false)
+ private SaleProduct saleProduct;
+
+ @ManyToOne(fetch = FetchType.LAZY)
+ @JoinColumn(name = "member_id", nullable = false)
+ private Member member;
+
+ @OneToOne(fetch = FetchType.LAZY)
+ @JoinColumn(name = "order_detail_id", nullable = false)
+ private OrderDetail orderDetail;
+
+ // ํ์
+ @Column(nullable = false)
+ private int rating;
+
+ //๋ฆฌ๋ทฐ ๋ด์ฉ
+ @Column(nullable = false)
+ private String contents;
+
+ private String image;
+
+ public void updateProductReview(ProductReview newProductReview) {
+ this.rating = newProductReview.getRating();
+ this.contents = newProductReview.getContents();
+ this.image = newProductReview.getImage();
+ }
+} | Java | `ProductReview` ์ํฐํฐ๋ `BaseEntity`๋ฅผ ์์ ๋ฐ๊ณ ์์ต๋๋ค !
`BaseEntity`๋ฅผ ๋ณด์๋ฉด `deletStatus` ๋ผ๋ ์ญ์ ์ฌ๋ถ๋ฅผ ๊ด๋ฆฌํ๋ ํ๋๊ฐ ์์ด์.
ํด๋น ํ๋์ ์ํ ๋ฆฌ๋ทฐ ๊ธฐ๋ฅ ๊ตฌํ ๋ด์์ ๋ฆฌ๋ทฐ ์ญ์ ๋ก์ง์ด ์ถฉ๋ํ์ง๋ ์๋์ง ๊ณ ๋ฏผํด๋ณด์
จ์ผ๋ฉด ์ข๊ฒ ์ต๋๋ค๐ |
@@ -0,0 +1,70 @@
+package com.frame2.server.core.board.application;
+
+import com.frame2.server.core.board.domain.ProductReview;
+import com.frame2.server.core.board.infrastructure.ProductReviewRepository;
+import com.frame2.server.core.board.payload.request.ProductReviewModifyRequest;
+import com.frame2.server.core.board.payload.request.ProductReviewRequest;
+import com.frame2.server.core.board.payload.response.ProductReviewResponse;
+import com.frame2.server.core.member.domain.Member;
+import com.frame2.server.core.member.infrastructure.MemberRepository;
+import com.frame2.server.core.order.domain.OrderDetail;
+import com.frame2.server.core.order.infrastructure.OrderDetailRepository;
+import com.frame2.server.core.product.domain.SaleProduct;
+import com.frame2.server.core.product.infrastructure.SaleProductRepository;
+import lombok.RequiredArgsConstructor;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import java.util.List;
+
+@Service
+@Transactional
+@RequiredArgsConstructor
+public class ProductReviewServiceImpl implements ProductReviewService {
+
+ private final ProductReviewRepository productReviewRepository;
+ private final SaleProductRepository saleProductRepository;
+ private final MemberRepository memberRepository;
+ private final OrderDetailRepository orderDetailRepository;
+
+ // ์์ฑ
+ @Override
+ public void productReviewCreate(ProductReviewRequest request, Long memberId, Long saleProductId) {
+ Member member = memberRepository.findOne(memberId);
+ SaleProduct saleProduct = saleProductRepository.findOne(saleProductId);
+ OrderDetail orderDetail = orderDetailRepository.findOne(request.orderDetailId());
+
+ ProductReview productReview = request.toEntity(member, saleProduct, orderDetail);
+ productReviewRepository.save(productReview);
+ }
+
+ // ์์
+ @Override
+ public void productReviewModify(ProductReviewModifyRequest request, Long productReviewId) {
+ productReviewRepository.findOne(productReviewId).updateProductReview(request.toEntity());
+ }
+
+ // ์ญ์
+ @Override
+ public void remove(Long productReviewId) {
+ productReviewRepository.findOne(productReviewId).delete();
+ }
+
+ // ๋จ๊ฑด ์กฐํ
+ @Override
+ @Transactional(readOnly = true)
+ public ProductReviewResponse getProductReview(Long productReviewId) {
+ ProductReview productReview = productReviewRepository.findOne(productReviewId);
+ return ProductReviewResponse.from(productReview);
+ }
+
+ // ํ ์ํ์ ๋ํ ์ ์ฒด ๋ฆฌ๋ทฐ ์กฐํ
+ @Override
+ @Transactional(readOnly = true)
+ public List<ProductReviewResponse> getProductReviewList(Long saleProductId) {
+ List<ProductReview> productReviewList = productReviewRepository.findAllBySaleProductId(saleProductId);
+ return productReviewList.stream()
+ .map(ProductReviewResponse::from)
+ .toList();
+ }
+} | Java | ๋ง์ฝ ํด๋น `id`๋ฅผ ๊ฐ์ง ๋ฆฌ๋ทฐ๊ฐ ์๋ค๋ฉด ์ด๋กํ์ฃ ..?!
๋ฆฌ๋ทฐ๊ฐ ์๋์ง ์๋์ง ๋จผ์ ํ์ธํด๋ณด๋ ์์
์ด ํ์ํ๋ค๊ณ ์๊ฐํฉ๋๋ค! |
@@ -0,0 +1,70 @@
+package com.frame2.server.core.board.application;
+
+import com.frame2.server.core.board.domain.ProductReview;
+import com.frame2.server.core.board.infrastructure.ProductReviewRepository;
+import com.frame2.server.core.board.payload.request.ProductReviewModifyRequest;
+import com.frame2.server.core.board.payload.request.ProductReviewRequest;
+import com.frame2.server.core.board.payload.response.ProductReviewResponse;
+import com.frame2.server.core.member.domain.Member;
+import com.frame2.server.core.member.infrastructure.MemberRepository;
+import com.frame2.server.core.order.domain.OrderDetail;
+import com.frame2.server.core.order.infrastructure.OrderDetailRepository;
+import com.frame2.server.core.product.domain.SaleProduct;
+import com.frame2.server.core.product.infrastructure.SaleProductRepository;
+import lombok.RequiredArgsConstructor;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import java.util.List;
+
+@Service
+@Transactional
+@RequiredArgsConstructor
+public class ProductReviewServiceImpl implements ProductReviewService {
+
+ private final ProductReviewRepository productReviewRepository;
+ private final SaleProductRepository saleProductRepository;
+ private final MemberRepository memberRepository;
+ private final OrderDetailRepository orderDetailRepository;
+
+ // ์์ฑ
+ @Override
+ public void productReviewCreate(ProductReviewRequest request, Long memberId, Long saleProductId) {
+ Member member = memberRepository.findOne(memberId);
+ SaleProduct saleProduct = saleProductRepository.findOne(saleProductId);
+ OrderDetail orderDetail = orderDetailRepository.findOne(request.orderDetailId());
+
+ ProductReview productReview = request.toEntity(member, saleProduct, orderDetail);
+ productReviewRepository.save(productReview);
+ }
+
+ // ์์
+ @Override
+ public void productReviewModify(ProductReviewModifyRequest request, Long productReviewId) {
+ productReviewRepository.findOne(productReviewId).updateProductReview(request.toEntity());
+ }
+
+ // ์ญ์
+ @Override
+ public void remove(Long productReviewId) {
+ productReviewRepository.findOne(productReviewId).delete();
+ }
+
+ // ๋จ๊ฑด ์กฐํ
+ @Override
+ @Transactional(readOnly = true)
+ public ProductReviewResponse getProductReview(Long productReviewId) {
+ ProductReview productReview = productReviewRepository.findOne(productReviewId);
+ return ProductReviewResponse.from(productReview);
+ }
+
+ // ํ ์ํ์ ๋ํ ์ ์ฒด ๋ฆฌ๋ทฐ ์กฐํ
+ @Override
+ @Transactional(readOnly = true)
+ public List<ProductReviewResponse> getProductReviewList(Long saleProductId) {
+ List<ProductReview> productReviewList = productReviewRepository.findAllBySaleProductId(saleProductId);
+ return productReviewList.stream()
+ .map(ProductReviewResponse::from)
+ .toList();
+ }
+} | Java | `productReviewCreate()`๋ `ProductReview` ์ํฐํฐ๋ฅผ ๋ฐํํ๊ณ ์์ต๋๋ค.
๊ทธ๋ฐ๋ฐ ํด๋น ๋ฉ์๋๋ฅผ ํธ์ถํ๋ ๊ณณ์์ ์ด ์ํฐํฐ๋ฅผ ํ์๋ก ํ๊ณ ์์ง ์์๋ณด์
๋๋ค ! |
@@ -0,0 +1,70 @@
+package com.frame2.server.core.board.application;
+
+import com.frame2.server.core.board.domain.ProductReview;
+import com.frame2.server.core.board.infrastructure.ProductReviewRepository;
+import com.frame2.server.core.board.payload.request.ProductReviewModifyRequest;
+import com.frame2.server.core.board.payload.request.ProductReviewRequest;
+import com.frame2.server.core.board.payload.response.ProductReviewResponse;
+import com.frame2.server.core.member.domain.Member;
+import com.frame2.server.core.member.infrastructure.MemberRepository;
+import com.frame2.server.core.order.domain.OrderDetail;
+import com.frame2.server.core.order.infrastructure.OrderDetailRepository;
+import com.frame2.server.core.product.domain.SaleProduct;
+import com.frame2.server.core.product.infrastructure.SaleProductRepository;
+import lombok.RequiredArgsConstructor;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import java.util.List;
+
+@Service
+@Transactional
+@RequiredArgsConstructor
+public class ProductReviewServiceImpl implements ProductReviewService {
+
+ private final ProductReviewRepository productReviewRepository;
+ private final SaleProductRepository saleProductRepository;
+ private final MemberRepository memberRepository;
+ private final OrderDetailRepository orderDetailRepository;
+
+ // ์์ฑ
+ @Override
+ public void productReviewCreate(ProductReviewRequest request, Long memberId, Long saleProductId) {
+ Member member = memberRepository.findOne(memberId);
+ SaleProduct saleProduct = saleProductRepository.findOne(saleProductId);
+ OrderDetail orderDetail = orderDetailRepository.findOne(request.orderDetailId());
+
+ ProductReview productReview = request.toEntity(member, saleProduct, orderDetail);
+ productReviewRepository.save(productReview);
+ }
+
+ // ์์
+ @Override
+ public void productReviewModify(ProductReviewModifyRequest request, Long productReviewId) {
+ productReviewRepository.findOne(productReviewId).updateProductReview(request.toEntity());
+ }
+
+ // ์ญ์
+ @Override
+ public void remove(Long productReviewId) {
+ productReviewRepository.findOne(productReviewId).delete();
+ }
+
+ // ๋จ๊ฑด ์กฐํ
+ @Override
+ @Transactional(readOnly = true)
+ public ProductReviewResponse getProductReview(Long productReviewId) {
+ ProductReview productReview = productReviewRepository.findOne(productReviewId);
+ return ProductReviewResponse.from(productReview);
+ }
+
+ // ํ ์ํ์ ๋ํ ์ ์ฒด ๋ฆฌ๋ทฐ ์กฐํ
+ @Override
+ @Transactional(readOnly = true)
+ public List<ProductReviewResponse> getProductReviewList(Long saleProductId) {
+ List<ProductReview> productReviewList = productReviewRepository.findAllBySaleProductId(saleProductId);
+ return productReviewList.stream()
+ .map(ProductReviewResponse::from)
+ .toList();
+ }
+} | Java | productReviewModify()๋ ProductReview ์ํฐํฐ๋ฅผ ๋ฐํํ๊ณ ์์ต๋๋ค.
๊ทธ๋ฐ๋ฐ ํด๋น ๋ฉ์๋๋ฅผ ํธ์ถํ๋ ๊ณณ์์ ์ด ์ํฐํฐ๋ฅผ ํ์๋ก ํ๊ณ ์์ง ์์๋ณด์
๋๋ค ! |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.