code stringlengths 41 34.3k | lang stringclasses 8
values | review stringlengths 1 4.74k |
|---|---|---|
@@ -0,0 +1,49 @@
+import { Random } from "@woowacourse/mission-utils";
+import {
+ VALID_INPUT_LENGTH,
+ MIN_RANDOM_NUMBER,
+ MAX_RANDOM_NUMBER,
+} from "./gameConstants.js";
+
+class Computer {
+ #solution;
+
+ seeSolution() {
+ return this.#solution;
+ }
+
+ makeSolution() {
+ const computer = [];
+ while (computer.length < VALID_INPUT_LENGTH) {
+ const number = Random.pickNumberInRange(
+ MIN_RANDOM_NUMBER,
+ MAX_RANDOM_NUMBER
+ );
+ if (!computer.includes(number)) {
+ computer.push(number);
+ }
+ }
+ this.#solution = computer;
+ }
+
+ assessUserInput(input) {
+ let strike = 0;
+ let ball = 0;
+ const userInput = input.split("").map(Number);
+ userInput.forEach((item, index) => {
+ if (
+ this.#solution.indexOf(item) === index &&
+ this.#solution.includes(item)
+ )
+ strike += 1;
+ else if (
+ this.#solution.indexOf(item) !== index &&
+ this.#solution.includes(item)
+ )
+ ball += 1;
+ });
+ return { strike, ball };
+ }
+}
+
+export default Computer; | JavaScript | 1. ์ด๋ ๊ฒ๋ ๋ฉ๋๋ค.
```suggestion
const userInput = input.split("").map(Number);
```
2. ๋ฐฐ์ด์ด๋ฉด.. s๊ฐ ๋ถ์ผ๋ฉด ์ข์ง ์์๊น์? |
@@ -0,0 +1,49 @@
+import { Random } from "@woowacourse/mission-utils";
+import {
+ VALID_INPUT_LENGTH,
+ MIN_RANDOM_NUMBER,
+ MAX_RANDOM_NUMBER,
+} from "./gameConstants.js";
+
+class Computer {
+ #solution;
+
+ seeSolution() {
+ return this.#solution;
+ }
+
+ makeSolution() {
+ const computer = [];
+ while (computer.length < VALID_INPUT_LENGTH) {
+ const number = Random.pickNumberInRange(
+ MIN_RANDOM_NUMBER,
+ MAX_RANDOM_NUMBER
+ );
+ if (!computer.includes(number)) {
+ computer.push(number);
+ }
+ }
+ this.#solution = computer;
+ }
+
+ assessUserInput(input) {
+ let strike = 0;
+ let ball = 0;
+ const userInput = input.split("").map(Number);
+ userInput.forEach((item, index) => {
+ if (
+ this.#solution.indexOf(item) === index &&
+ this.#solution.includes(item)
+ )
+ strike += 1;
+ else if (
+ this.#solution.indexOf(item) !== index &&
+ this.#solution.includes(item)
+ )
+ ball += 1;
+ });
+ return { strike, ball };
+ }
+}
+
+export default Computer; | JavaScript | reduce๋ฅผ ์จ์๋ ๊ตฌํํ ์ ์๊ฒ ๋ค์
```js
const strikeAndBall = userInput.reduce((acc, cur) => {
if ((this.#solution.indexOf(item) === index) && this.#solution.includes(item)) return { ...acc, strike: acc.strike + 1 }
if ((this.#solution.indexOf(item) !== index) && this.#solution.includes(item)) return { ...acc, ball:acc.ball + 1}
return acc;
}, { strike: 0, ball: 0})
``` |
@@ -0,0 +1,15 @@
+{
+ "arrowParens": "always",
+ "bracketSpacing": true,
+ "jsxBracketSameLine": false,
+ "jsxSingleQuote": false,
+ "printWidth": 80,
+ "proseWrap": "always",
+ "quoteProps": "as-needed",
+ "semi": true,
+ "singleQuote": false,
+ "tabWidth": 2,
+ "trailingComma": "es5",
+ "useTabs": false,
+ "endOfLine": "auto"
+}
\ No newline at end of file | Unknown | ์ฝ๋๋ฅผ ๋ณด๋ฉด prettier๊ฐ ์ ์ฉ๋์ด์์ง ์์๋ฐ, ํ์ธํ๋ฒ ํด๋ณด์ธ์ฉ |
@@ -0,0 +1,49 @@
+import { Random } from "@woowacourse/mission-utils";
+import {
+ VALID_INPUT_LENGTH,
+ MIN_RANDOM_NUMBER,
+ MAX_RANDOM_NUMBER,
+} from "./gameConstants.js";
+
+class Computer {
+ #solution;
+
+ seeSolution() {
+ return this.#solution;
+ }
+
+ makeSolution() {
+ const computer = [];
+ while (computer.length < VALID_INPUT_LENGTH) {
+ const number = Random.pickNumberInRange(
+ MIN_RANDOM_NUMBER,
+ MAX_RANDOM_NUMBER
+ );
+ if (!computer.includes(number)) {
+ computer.push(number);
+ }
+ }
+ this.#solution = computer;
+ }
+
+ assessUserInput(input) {
+ let strike = 0;
+ let ball = 0;
+ const userInput = input.split("").map(Number);
+ userInput.forEach((item, index) => {
+ if (
+ this.#solution.indexOf(item) === index &&
+ this.#solution.includes(item)
+ )
+ strike += 1;
+ else if (
+ this.#solution.indexOf(item) !== index &&
+ this.#solution.includes(item)
+ )
+ ball += 1;
+ });
+ return { strike, ball };
+ }
+}
+
+export default Computer; | JavaScript | ์ด๊ฑธ ๋ฆฌํดํ๋ ์ด์ ๊ฐ ๋ญ๊ฐ์ ? |
@@ -1,5 +1,62 @@
+import { Console } from "@woowacourse/mission-utils";
+import User from "./User.js";
+import Computer from "./Computer.js";
+import Validator from "./Validator.js";
+import GameMessage from "./GameMessage.js";
+import { RETRY_RESPONSE, FULL_STRIKE } from "./gameConstants.js";
+
class App {
- async play() {}
+ constructor() {
+ this.user = new User();
+ this.computer = new Computer();
+ }
+
+ async play() {
+ this.computer.makeSolution();
+ Console.print(GameMessage.START_MESSAGE);
+ await this.mainLogic();
+ }
+
+ async mainLogic() {
+ await this.setUserInput();
+ this.printStrikeBall();
+ if (
+ this.computer.assessUserInput(this.user.getNumber()).strike !==
+ FULL_STRIKE
+ )
+ await this.mainLogic();
+ else {
+ const replayResponse = await Console.readLineAsync(
+ "๊ฒ์์ ์๋ก ์์ํ๋ ค๋ฉด 1, ์ข
๋ฃํ๋ ค๋ฉด 2๋ฅผ ์
๋ ฅํ์ธ์."
+ );
+ if (parseInt(replayResponse, 10) === RETRY_RESPONSE) {
+ this.computer.makeSolution();
+ this.mainLogic();
+ }
+ }
+ }
+
+ async setUserInput() {
+ const input = await Console.readLineAsync("์ซ์๋ฅผ ์
๋ ฅํด์ฃผ์ธ์ : ");
+ if (Validator.isValidInput(input)) {
+ this.user.setNumber(input);
+ }
+ }
+
+ printStrikeBall() {
+ const { strike, ball } = this.computer.assessUserInput(
+ this.user.getNumber()
+ );
+ if (strike === 0 && ball === 0) {
+ Console.print(GameMessage.NOTHING_MESSAGE);
+ } else if (strike > 0 && ball > 0) {
+ Console.print(`${strike}๋ณผ ${ball}์คํธ๋ผ์ดํฌ`);
+ } else if (strike === FULL_STRIKE) {
+ Console.print(GameMessage.SOLVED_MESSAGE);
+ } else {
+ Console.print(`${strike}์คํธ๋ผ์ดํฌ ${ball}๋ณผ`);
+ }
+ }
}
export default App; | JavaScript | indent๊ฐ.. |
@@ -1,5 +1,62 @@
+import { Console } from "@woowacourse/mission-utils";
+import User from "./User.js";
+import Computer from "./Computer.js";
+import Validator from "./Validator.js";
+import GameMessage from "./GameMessage.js";
+import { RETRY_RESPONSE, FULL_STRIKE } from "./gameConstants.js";
+
class App {
- async play() {}
+ constructor() {
+ this.user = new User();
+ this.computer = new Computer();
+ }
+
+ async play() {
+ this.computer.makeSolution();
+ Console.print(GameMessage.START_MESSAGE);
+ await this.mainLogic();
+ }
+
+ async mainLogic() {
+ await this.setUserInput();
+ this.printStrikeBall();
+ if (
+ this.computer.assessUserInput(this.user.getNumber()).strike !==
+ FULL_STRIKE
+ )
+ await this.mainLogic();
+ else {
+ const replayResponse = await Console.readLineAsync(
+ "๊ฒ์์ ์๋ก ์์ํ๋ ค๋ฉด 1, ์ข
๋ฃํ๋ ค๋ฉด 2๋ฅผ ์
๋ ฅํ์ธ์."
+ );
+ if (parseInt(replayResponse, 10) === RETRY_RESPONSE) {
+ this.computer.makeSolution();
+ this.mainLogic();
+ }
+ }
+ }
+
+ async setUserInput() {
+ const input = await Console.readLineAsync("์ซ์๋ฅผ ์
๋ ฅํด์ฃผ์ธ์ : ");
+ if (Validator.isValidInput(input)) {
+ this.user.setNumber(input);
+ }
+ }
+
+ printStrikeBall() {
+ const { strike, ball } = this.computer.assessUserInput(
+ this.user.getNumber()
+ );
+ if (strike === 0 && ball === 0) {
+ Console.print(GameMessage.NOTHING_MESSAGE);
+ } else if (strike > 0 && ball > 0) {
+ Console.print(`${strike}๋ณผ ${ball}์คํธ๋ผ์ดํฌ`);
+ } else if (strike === FULL_STRIKE) {
+ Console.print(GameMessage.SOLVED_MESSAGE);
+ } else {
+ Console.print(`${strike}์คํธ๋ผ์ดํฌ ${ball}๋ณผ`);
+ }
+ }
}
export default App; | JavaScript | ๋งค์ง๋๋ฒ๊ฐ ์ด์์ด์๋ค์ฉ |
@@ -1,5 +1,62 @@
+import { Console } from "@woowacourse/mission-utils";
+import User from "./User.js";
+import Computer from "./Computer.js";
+import Validator from "./Validator.js";
+import GameMessage from "./GameMessage.js";
+import { RETRY_RESPONSE, FULL_STRIKE } from "./gameConstants.js";
+
class App {
- async play() {}
+ constructor() {
+ this.user = new User();
+ this.computer = new Computer();
+ }
+
+ async play() {
+ this.computer.makeSolution();
+ Console.print(GameMessage.START_MESSAGE);
+ await this.mainLogic();
+ }
+
+ async mainLogic() {
+ await this.setUserInput();
+ this.printStrikeBall();
+ if (
+ this.computer.assessUserInput(this.user.getNumber()).strike !==
+ FULL_STRIKE
+ )
+ await this.mainLogic();
+ else {
+ const replayResponse = await Console.readLineAsync(
+ "๊ฒ์์ ์๋ก ์์ํ๋ ค๋ฉด 1, ์ข
๋ฃํ๋ ค๋ฉด 2๋ฅผ ์
๋ ฅํ์ธ์."
+ );
+ if (parseInt(replayResponse, 10) === RETRY_RESPONSE) {
+ this.computer.makeSolution();
+ this.mainLogic();
+ }
+ }
+ }
+
+ async setUserInput() {
+ const input = await Console.readLineAsync("์ซ์๋ฅผ ์
๋ ฅํด์ฃผ์ธ์ : ");
+ if (Validator.isValidInput(input)) {
+ this.user.setNumber(input);
+ }
+ }
+
+ printStrikeBall() {
+ const { strike, ball } = this.computer.assessUserInput(
+ this.user.getNumber()
+ );
+ if (strike === 0 && ball === 0) {
+ Console.print(GameMessage.NOTHING_MESSAGE);
+ } else if (strike > 0 && ball > 0) {
+ Console.print(`${strike}๋ณผ ${ball}์คํธ๋ผ์ดํฌ`);
+ } else if (strike === FULL_STRIKE) {
+ Console.print(GameMessage.SOLVED_MESSAGE);
+ } else {
+ Console.print(`${strike}์คํธ๋ผ์ดํฌ ${ball}๋ณผ`);
+ }
+ }
}
export default App; | JavaScript | ์ด๋ ๊ฒ eslint ๊ท์น์ ๋ฌด์ํ ๊ฑฐ๋ฉด eslint๋ฅผ ์ ์ฌ์ฉํ์๋์? |
@@ -1,20 +1,36 @@
package model;
+import java.util.ArrayList;
import java.util.List;
public class Lotto {
- private List<String> lottoNumbers;
+ private List<LottoNo> lottoNumbers;
- public Lotto(List<String> lottoNumbers) {
+ public Lotto(List<LottoNo> lottoNumbers) {
this.lottoNumbers = lottoNumbers;
}
- public int getCorrectNumberCount(List<String> winningNumber) {
- return (int) winningNumber.stream().filter((x) -> lottoNumbers.contains(x)).count();
+ public Lotto(String[] lottoNumbers) {
+ this.lottoNumbers = new ArrayList<>();
+ for (int i = 0; i < lottoNumbers.length; i++)
+ this.lottoNumbers.add(new LottoNo(Integer.parseInt(lottoNumbers[i])));
}
public String showLotto() {
- return lottoNumbers.toString();
+ List<String> lotto = new ArrayList<>();
+
+ for (LottoNo lottoNo : lottoNumbers)
+ lotto.add(lottoNo.getStringNumber());
+
+ return lotto.toString();
+ }
+
+ public int getCorrectCount(List<String> winningNumbers) {
+ return (int) lottoNumbers.stream().filter((x) -> winningNumbers.contains(x.getStringNumber())).count();
+ }
+
+ public boolean isContain(String stringNumber) {
+ return (int)lottoNumbers.stream().filter(x -> x.getStringNumber().equals(stringNumber)).count() != 0;
}
} | Java | ๋ก๋ ๋ฒํธ๋ฅผ Set ์ผ๋ก ๊ตฌํํ๋ ๊ฒ๊ณผ List ๋ก ๊ตฌํํ๋ ๊ฒ์ ๋น๊ตํด ๋ณด์์ ๋ ์ด๋ค ์ฅ๋จ์ ์ด ์์๊น์? ์ฌ๊ธฐ์๋ ์ด๋ค ์๋ฃ๊ตฌ์กฐ๊ฐ ์ด์ธ๋ฆด๊น์? |
@@ -1,20 +1,36 @@
package model;
+import java.util.ArrayList;
import java.util.List;
public class Lotto {
- private List<String> lottoNumbers;
+ private List<LottoNo> lottoNumbers;
- public Lotto(List<String> lottoNumbers) {
+ public Lotto(List<LottoNo> lottoNumbers) {
this.lottoNumbers = lottoNumbers;
}
- public int getCorrectNumberCount(List<String> winningNumber) {
- return (int) winningNumber.stream().filter((x) -> lottoNumbers.contains(x)).count();
+ public Lotto(String[] lottoNumbers) {
+ this.lottoNumbers = new ArrayList<>();
+ for (int i = 0; i < lottoNumbers.length; i++)
+ this.lottoNumbers.add(new LottoNo(Integer.parseInt(lottoNumbers[i])));
}
public String showLotto() {
- return lottoNumbers.toString();
+ List<String> lotto = new ArrayList<>();
+
+ for (LottoNo lottoNo : lottoNumbers)
+ lotto.add(lottoNo.getStringNumber());
+
+ return lotto.toString();
+ }
+
+ public int getCorrectCount(List<String> winningNumbers) {
+ return (int) lottoNumbers.stream().filter((x) -> winningNumbers.contains(x.getStringNumber())).count();
+ }
+
+ public boolean isContain(String stringNumber) {
+ return (int)lottoNumbers.stream().filter(x -> x.getStringNumber().equals(stringNumber)).count() != 0;
}
} | Java | ํ์ค์ด๋๋ผ๋ ๊ดํธ๋ฅผ ๋ถ์ฌ์ฃผ๋๊ฑธ ์ปจ๋ฒค์
์ผ๋ก ํฉ์๋ค.
์ด๊ฒ์ด ๊ฐ๊ฒฐํ๋๋ผ๋ ์ฝ๋ ์ฌ๋ ์
์ฅ์ผ๋ก ์ฝ๋๋ฅผ ๋ณด๋ฉด
๋น์ฐํ ์์ด์ผํ ๊ณณ์ ๋ฌด์ธ๊ฐ๊ฐ ๋น ์ง๊ฒ ๋๋ฉด ๊ฐ๋
์ฑ์ด ์ ํ๋ฉ๋๋ค. (์ฑ
์ฝ์ ๋์ ๋น์ท)
๊ทธ๋ฆฌ๊ณ ์์ฑ์์์ ๋ญ๊ฐ ๋ง์ ์ผ์ ํด์ฃผ๋๊ฒ ์์ฝ๋ค์ |
@@ -1,20 +1,36 @@
package model;
+import java.util.ArrayList;
import java.util.List;
public class Lotto {
- private List<String> lottoNumbers;
+ private List<LottoNo> lottoNumbers;
- public Lotto(List<String> lottoNumbers) {
+ public Lotto(List<LottoNo> lottoNumbers) {
this.lottoNumbers = lottoNumbers;
}
- public int getCorrectNumberCount(List<String> winningNumber) {
- return (int) winningNumber.stream().filter((x) -> lottoNumbers.contains(x)).count();
+ public Lotto(String[] lottoNumbers) {
+ this.lottoNumbers = new ArrayList<>();
+ for (int i = 0; i < lottoNumbers.length; i++)
+ this.lottoNumbers.add(new LottoNo(Integer.parseInt(lottoNumbers[i])));
}
public String showLotto() {
- return lottoNumbers.toString();
+ List<String> lotto = new ArrayList<>();
+
+ for (LottoNo lottoNo : lottoNumbers)
+ lotto.add(lottoNo.getStringNumber());
+
+ return lotto.toString();
+ }
+
+ public int getCorrectCount(List<String> winningNumbers) {
+ return (int) lottoNumbers.stream().filter((x) -> winningNumbers.contains(x.getStringNumber())).count();
+ }
+
+ public boolean isContain(String stringNumber) {
+ return (int)lottoNumbers.stream().filter(x -> x.getStringNumber().equals(stringNumber)).count() != 0;
}
} | Java | boolean์ int ๋ก ๋ณํํด์ฃผ๋ ์ด์ ๋ ๋ญ๊ฐ์? |
@@ -1,20 +1,36 @@
package model;
+import java.util.ArrayList;
import java.util.List;
public class Lotto {
- private List<String> lottoNumbers;
+ private List<LottoNo> lottoNumbers;
- public Lotto(List<String> lottoNumbers) {
+ public Lotto(List<LottoNo> lottoNumbers) {
this.lottoNumbers = lottoNumbers;
}
- public int getCorrectNumberCount(List<String> winningNumber) {
- return (int) winningNumber.stream().filter((x) -> lottoNumbers.contains(x)).count();
+ public Lotto(String[] lottoNumbers) {
+ this.lottoNumbers = new ArrayList<>();
+ for (int i = 0; i < lottoNumbers.length; i++)
+ this.lottoNumbers.add(new LottoNo(Integer.parseInt(lottoNumbers[i])));
}
public String showLotto() {
- return lottoNumbers.toString();
+ List<String> lotto = new ArrayList<>();
+
+ for (LottoNo lottoNo : lottoNumbers)
+ lotto.add(lottoNo.getStringNumber());
+
+ return lotto.toString();
+ }
+
+ public int getCorrectCount(List<String> winningNumbers) {
+ return (int) lottoNumbers.stream().filter((x) -> winningNumbers.contains(x.getStringNumber())).count();
+ }
+
+ public boolean isContain(String stringNumber) {
+ return (int)lottoNumbers.stream().filter(x -> x.getStringNumber().equals(stringNumber)).count() != 0;
}
} | Java | ์ด ๋ถ๋ถ ์ข ๋ ๊ฐ์ ํด๋ณด์ธ์ |
@@ -1,20 +1,36 @@
package model;
+import java.util.ArrayList;
import java.util.List;
public class Lotto {
- private List<String> lottoNumbers;
+ private List<LottoNo> lottoNumbers;
- public Lotto(List<String> lottoNumbers) {
+ public Lotto(List<LottoNo> lottoNumbers) {
this.lottoNumbers = lottoNumbers;
}
- public int getCorrectNumberCount(List<String> winningNumber) {
- return (int) winningNumber.stream().filter((x) -> lottoNumbers.contains(x)).count();
+ public Lotto(String[] lottoNumbers) {
+ this.lottoNumbers = new ArrayList<>();
+ for (int i = 0; i < lottoNumbers.length; i++)
+ this.lottoNumbers.add(new LottoNo(Integer.parseInt(lottoNumbers[i])));
}
public String showLotto() {
- return lottoNumbers.toString();
+ List<String> lotto = new ArrayList<>();
+
+ for (LottoNo lottoNo : lottoNumbers)
+ lotto.add(lottoNo.getStringNumber());
+
+ return lotto.toString();
+ }
+
+ public int getCorrectCount(List<String> winningNumbers) {
+ return (int) lottoNumbers.stream().filter((x) -> winningNumbers.contains(x.getStringNumber())).count();
+ }
+
+ public boolean isContain(String stringNumber) {
+ return (int)lottoNumbers.stream().filter(x -> x.getStringNumber().equals(stringNumber)).count() != 0;
}
} | Java | x ๋ฅผ ์ข ๋ ์๋ฏธ์๋ ๋ณ์์ด๋ฆ์ผ๋ก ์ง์์ผ๋ฉด ์ข์์ ๊ฒ ๊ฐ์ต๋๋ค.
๊ทธ๋ฆฌ๊ณ ๋ฉ์๋ ์ฒด์ด๋ ๋ฐฉ์์์๋ ๊ธธ์ด๊ฐ ๊ธธ์ด์ง๋ฉด IDE์์ ํ๋์ ํ์ธํ๊ธฐ ํ๋๋๊น
๊ฐ๋
์ฑ์ ์ํด ์ํฐ๋ก ๋ผ์ธ์ ๋ฆฌ๋ฅผ ์ด๋์ ๋ ํด์ฃผ๋ ๊ฒ์ด ์ข์ต๋๋ค.
์ด๋ฅผ ์ํ ์ปจ๋ฒค์
๋ intellij code style ์์ ์๋์ ๋ ฌ ์ค์ ํ ์ ์๊ธด ํฉ๋๋ค(์ ๋ ์ฌ์ฉ์ค) |
@@ -1,10 +1,8 @@
package model;
-import util.ListGenerator;
import util.SplitGenerator;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@@ -13,43 +11,44 @@ public class LottoMachine {
private static int LOTTO_NUMBER_RANGE = 45;
private static int LOTTO_NUMBER_COUNT = 6;
private static int LOTTO_PRICE = 1000;
- List<Lotto> lottos = new ArrayList<>();
- public List<String> buyLotto(int totalLottoPrice) {
- for (int i = 0; i < getLottoCount(totalLottoPrice); i++)
- lottos.add(new Lotto(getRandomNumbers(LOTTO_NUMBER_RANGE)));
- return showLottoHistory();
+ private int tryCount = 0;
+
+ public Lotto getAutoLotto() {
+ decreaseCount();
+ return new Lotto(getRandomNumbers(getNumbersInRange(LOTTO_NUMBER_RANGE)));
}
- private int getLottoCount(int totalPrice) {
- return totalPrice / LOTTO_PRICE;
+ public void inputMoney(int money) {
+ tryCount += money / LOTTO_PRICE;
}
- private List<String> getRandomNumbers(int range) {
- List<String> numbersInRange = ListGenerator.getNumbersInRange(range);
- Collections.shuffle(numbersInRange);
- return numbersInRange.subList(0, LOTTO_NUMBER_COUNT);
+ public boolean canLotto() {
+ return tryCount > 0;
}
- public int[] getStatistic(String winningNumber) {
- return createStatistic(toStringList(winningNumber));
+ private void decreaseCount() {
+ if (canLotto() == false)
+ throw new RuntimeException("๋ ๋ฃ์ด!!");
+ tryCount--;
}
- private List<String> toStringList(String winningNumber) {
- return Arrays.asList(SplitGenerator.splitWithSign(winningNumber, ", "));
+ private List<LottoNo> getNumbersInRange(int range) {
+ List<LottoNo> numbersInRange = new ArrayList<>();
+
+ for (int i = 1; i <= range; i++)
+ numbersInRange.add(new LottoNo(i));
+
+ return numbersInRange;
}
- private int[] createStatistic(List<String> winningNumber) {
- int[] statistic = new int[LOTTO_NUMBER_COUNT + 1];
- for (Lotto lotto : lottos)
- statistic[lotto.getCorrectNumberCount(winningNumber)]++;
- return statistic;
+ private List<LottoNo> getRandomNumbers(List<LottoNo> numbersInRange) {
+ Collections.shuffle(numbersInRange);
+ return numbersInRange.subList(0, LOTTO_NUMBER_COUNT);
}
- private List<String> showLottoHistory() {
- List<String> lottoHistory = new ArrayList<>();
- for (Lotto lotto : lottos)
- lottoHistory.add(lotto.showLotto());
- return lottoHistory;
+ public Lotto getDirectLotto(String numbers) {
+ decreaseCount();
+ return new Lotto(SplitGenerator.splitWithSign(numbers, ", "));
}
} | Java | getter ์ ํท๊ฐ๋ฆฌ๋ฏ๋ก calculateRandomNumbers ์ฒ๋ผ ๋ค๋ฅธ ๋จ์ด๋ฅผ ํ์ฉํด๋ณด์๋๊ฑธ ์ถ์ฒ |
@@ -1,20 +1,36 @@
package model;
+import java.util.ArrayList;
import java.util.List;
public class Lotto {
- private List<String> lottoNumbers;
+ private List<LottoNo> lottoNumbers;
- public Lotto(List<String> lottoNumbers) {
+ public Lotto(List<LottoNo> lottoNumbers) {
this.lottoNumbers = lottoNumbers;
}
- public int getCorrectNumberCount(List<String> winningNumber) {
- return (int) winningNumber.stream().filter((x) -> lottoNumbers.contains(x)).count();
+ public Lotto(String[] lottoNumbers) {
+ this.lottoNumbers = new ArrayList<>();
+ for (int i = 0; i < lottoNumbers.length; i++)
+ this.lottoNumbers.add(new LottoNo(Integer.parseInt(lottoNumbers[i])));
}
public String showLotto() {
- return lottoNumbers.toString();
+ List<String> lotto = new ArrayList<>();
+
+ for (LottoNo lottoNo : lottoNumbers)
+ lotto.add(lottoNo.getStringNumber());
+
+ return lotto.toString();
+ }
+
+ public int getCorrectCount(List<String> winningNumbers) {
+ return (int) lottoNumbers.stream().filter((x) -> winningNumbers.contains(x.getStringNumber())).count();
+ }
+
+ public boolean isContain(String stringNumber) {
+ return (int)lottoNumbers.stream().filter(x -> x.getStringNumber().equals(stringNumber)).count() != 0;
}
} | Java | int ๊ฐ์ผ๋ก ๋ฐํํ๋ ๋ฉ์๋๋ก ์ฒ์ ๊ตฌํํ์๋๋ฐ ๋ฆฌํฉํ ๋ง ๊ณผ์ ์์ boolean ํ์
์ผ๋ก ๋ฐ๊ฟ๋ ๊น๋นกํ ๊ฒ๊ฐ๋ค์.. ์ค์ํ์ง ์๋๋ก ์ฃผ์ํ๊ฒ ์ต๋๋ค |
@@ -1,20 +1,36 @@
package model;
+import java.util.ArrayList;
import java.util.List;
public class Lotto {
- private List<String> lottoNumbers;
+ private List<LottoNo> lottoNumbers;
- public Lotto(List<String> lottoNumbers) {
+ public Lotto(List<LottoNo> lottoNumbers) {
this.lottoNumbers = lottoNumbers;
}
- public int getCorrectNumberCount(List<String> winningNumber) {
- return (int) winningNumber.stream().filter((x) -> lottoNumbers.contains(x)).count();
+ public Lotto(String[] lottoNumbers) {
+ this.lottoNumbers = new ArrayList<>();
+ for (int i = 0; i < lottoNumbers.length; i++)
+ this.lottoNumbers.add(new LottoNo(Integer.parseInt(lottoNumbers[i])));
}
public String showLotto() {
- return lottoNumbers.toString();
+ List<String> lotto = new ArrayList<>();
+
+ for (LottoNo lottoNo : lottoNumbers)
+ lotto.add(lottoNo.getStringNumber());
+
+ return lotto.toString();
+ }
+
+ public int getCorrectCount(List<String> winningNumbers) {
+ return (int) lottoNumbers.stream().filter((x) -> winningNumbers.contains(x.getStringNumber())).count();
+ }
+
+ public boolean isContain(String stringNumber) {
+ return (int)lottoNumbers.stream().filter(x -> x.getStringNumber().equals(stringNumber)).count() != 0;
}
} | Java | set๊ณผ List์ ๊ฐ์ฅ ํฐ ์ฐจ์ด์ ์ ์ค๋ณต์ ํ์ฉํ๋์ง ์ํ๋์ง๋ก ์๊ณ ์์ต๋๋ค.
์ด๋ถ๋ถ์์ set์ ํ์ฉํ์๋ ๋ก๋ ๋ฒํธ๊ฐ 6๊ฐ๊ฐ ๋ ๋๊น์ง ๋๋ค ์ซ์๋ฅผ ๋ฐ๋ ๋ฐฉ๋ฒ์ด ์๊ฒ ๋ค์ ์๋ํด๋ณด๊ฒ ์ต๋๋ค. |
@@ -0,0 +1,135 @@
+package christmas.validator;
+
+import christmas.constant.Constants;
+import christmas.constant.ErrorMessage;
+import christmas.constant.Menu;
+import christmas.util.Utils;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+public class OrderValidator implements Validator {
+ @Override
+ public void check(String input) {
+ chechDefaultTemplate(input);
+ checkValidatedForm(input);
+ checkIfStringMenu(input);
+ checkQuantityRange(input);
+ checkIfMenuExists(input);
+ checkForDuplicateMenu(input);
+ checkTotalMenuCount(input);
+ checkBeverageOnly(input);
+ }
+
+ private void chechDefaultTemplate(final String input) {
+ List<String> orderItems = Arrays.asList(input.split(","));
+
+ orderItems.stream()
+ .map(item -> item.split("-"))
+ .forEach(parts -> {
+ try {
+ if (parts.length != 2 || !parts[1].matches("\\d+")) {
+ throw new IllegalArgumentException(ErrorMessage.NOT_VALIDATED_ORDER.getMessage());
+ }
+ } catch (IllegalArgumentException e) {
+ throw new IllegalArgumentException(ErrorMessage.NOT_VALIDATED_ORDER.getMessage());
+ }
+ });
+ }
+
+ private void checkValidatedForm(final String input) { // ์ ํจํ์ง์์ ์
๋ ฅ (๊ธฐ๋ณธ ํ
ํ๋ฆฟ ์
๋ ฅ์ด ์๋ ๊ฒฝ์ฐ) [์์ฒญ ์ฌํญ ์กด์ฌ]
+ try {
+ Map<String, Integer> resultMap = Stream.of(input.split(","))
+ .map(s -> s.split("-")).collect(Collectors.toMap(
+ arr -> arr[0],
+ arr -> Integer.parseInt(arr[1]),
+ (existing, replacement) -> existing,
+ HashMap::new
+ ));
+ // {"ํด์ฐ๋ฌผํ์คํ": 2, "๋ ๋์์ธ": 1, ...}
+ } catch (IllegalArgumentException e) {
+ throw new IllegalArgumentException(ErrorMessage.NOT_VALIDATED_ORDER.getMessage());
+ }
+ }
+
+ private void checkIfStringMenu(final String input) { // ๋ฉ๋ด(key) ๋ถ๋ถ์ด String, ์ฆ ๋ฌธ์์ด(ํ๊ธ,์์ด)์ด ์๋๋ฉด ์์ธ์ฒ๋ฆฌ [์์ฒญ ํ
ํ๋ฆฟ]
+ Map<String, Integer> menu = Utils.makeStringToHashMap(input);
+ menu.keySet().stream()
+ .filter(key -> !key.matches("[a-zA-Z๊ฐ-ํฃ]+"))
+ .findAny()
+ .ifPresent(invalidKey -> {
+ throw new IllegalArgumentException(ErrorMessage.NOT_VALIDATED_ORDER.getMessage());
+ });
+ }
+
+ private void checkQuantityRange(final String input) { // ์๋์ด ๊ฐ๊ฐ 1์ด์ 20์ดํ ๊ฐ ์๋๋ฉด ์์ธ์ฒ๋ฆฌ [์์ฒญ ์ฌํญ ์กด์ฌ]
+ try {
+ Map<String, Integer> menu = Utils.makeStringToHashMap(input);
+ menu.entrySet().stream()
+ .filter(entry -> entry.getValue() < 1 || entry.getValue() > 20)
+ .findAny()
+ .ifPresent(entry -> {
+ throw new IllegalArgumentException(ErrorMessage.NOT_VALIDATED_ORDER.getMessage());
+ });
+ } catch (IllegalArgumentException e) {
+ throw new IllegalArgumentException(ErrorMessage.NOT_VALIDATED_ORDER.getMessage());
+ }
+ }
+
+ private void checkIfMenuExists(final String input) { // ์๋ ๋ฉ๋ด์ผ์ง ์์ธ์ฒ๋ฆฌ ( ex) T๋ณธ์คํ
์ดํฌ ) [์์ฒญ ์ฌํญ ์กด์ฌ]
+ Map<String, Integer> menu = Utils.makeStringToHashMap(input);
+
+ Set<String> availableMenuItems = Arrays.stream(Menu.values())
+ .map(menuEnum -> menuEnum.getName())
+ .collect(Collectors.toSet());
+
+ menu.keySet().stream()
+ .filter(inputMenu -> !availableMenuItems.contains(inputMenu))
+ .findAny()
+ .ifPresent(invalidKey -> {
+ throw new IllegalArgumentException(ErrorMessage.NOT_VALIDATED_ORDER.getMessage());
+ });
+ }
+
+ private void checkForDuplicateMenu(final String input) {
+ Map<String, Integer> resultMap = Stream.of(input.split(","))
+ .map(s -> s.split("-"))
+ .collect(Collectors.toMap(
+ arr -> arr[0],
+ arr -> Integer.parseInt(arr[1]),
+ (existing, replacement) -> {
+ throw new IllegalArgumentException(ErrorMessage.NOT_VALIDATED_ORDER.getMessage());
+ },
+ HashMap::new
+ ));
+ }
+
+ private void checkTotalMenuCount(final String input) {
+ // ๋ฉ๋ด ๊ฐ์์ ํฉ์ด 20๊ฐ๊ฐ ์ด๊ณผํ ์ ์์ธ์ฒ๋ฆฌ
+ Map<String, Integer> menu = Utils.makeStringToHashMap(input);
+ int total = menu.values().stream().mapToInt(Integer::intValue).sum();
+
+ if (total > Constants.MENU_LIMIT.getConstants()) {
+ throw new IllegalArgumentException(ErrorMessage.TOTAL_MENU_COUNT_IS_OVER.getMessage());
+ }
+ }
+
+ private void checkBeverageOnly(final String input) {
+ // ๊ฐ ๋ฉ๋ด์ ์๋ฃ ํด๋์ค๋ง ์์ผ๋ฉด ์์ธ์ฒ๋ฆฌ
+
+ Map<String, Integer> menu = Utils.makeStringToHashMap(input);
+ List<String> onlyBeverage = Menu.BEVERAGE_MENU;
+
+ List<String> matchCount = menu.keySet().stream()
+ .filter(onlyBeverage::contains)
+ .toList();
+
+ if (menu.size() == matchCount.size()) {
+ throw new IllegalArgumentException(ErrorMessage.ORDER_ONLY_BEVERAGE.getMessage());
+ }
+ }
+} | Java | https://www.inflearn.com/questions/819415/verify-validate-check-is
verify, validate, check, is ์ ๋ค์ด๋ฐ ์ฐจ์ด์ ๋ํด์ ์ค๋ช
ํ๋ ๊ธ์ธ๋ฐ ์ฐธ๊ณ ํ์๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,25 @@
+package christmas.validator;
+
+import christmas.constant.ErrorMessage;
+
+public class DateValidator implements Validator{
+ @Override
+ public void check(final String input) {
+ checkInteger(input);
+ checkOutOfRange(input);
+ }
+
+ private void checkInteger(final String input) {
+ try {
+ Integer.parseInt(input);
+ } catch (IllegalArgumentException e) {
+ throw new IllegalArgumentException(ErrorMessage.DATE_OUT_OF_RANGE.getMessage());
+ }
+ }
+ private void checkOutOfRange(final String input) {
+ int date = Integer.parseInt(input);
+ if (date < 1 || date > 31) {
+ throw new IllegalArgumentException(ErrorMessage.DATE_OUT_OF_RANGE.getMessage());
+ }
+ }
+} | Java | 1๊ณผ 31์ด ๋งค์ง๋๋ฒ๋ผ๊ณ ์๊ฐํด์! ์์๋ก ๋นผ์ฃผ๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,28 @@
+package christmas.domain;
+
+import christmas.util.Utils;
+import christmas.view.OutputView;
+
+public class OrderPrice {
+ // ๊ธ์ก๊ณผ ๊ด๋ จ๋ ํด๋์ค์
๋๋ค.
+ // ํ ์ธ ์ ์ด ์ฃผ๋ฌธ๊ธ์ก, ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก ๋ฑ์ ๊ด๋ฆฌํ๋ ํด๋์ค ์
๋๋ค.
+ private static final String UNIT = "์";
+ private OrderRepository orders;
+ private int totalAmount;
+
+ public OrderPrice(final OrderRepository orders) {
+ this.orders = orders;
+ }
+
+ public void printBeforeDiscountInfo() {
+ this.totalAmount = orders.calculateTotalAmount();
+
+ OutputView.printBeforeDiscount();
+ String result = Utils.makeFormattedNumberWithComma(this.totalAmount);
+ OutputView.printMessage(result + UNIT);
+ }
+
+ public int getTotalAmount() {
+ return totalAmount;
+ }
+} | Java | '์' ๊ฐ์ ๋จ์๋ ์ถ๋ ฅ ๋ฐ ํฌ๋งคํ
๊ณผ ๊ด๊ณ์์ผ๋ฏ๋ก OutputView์ ์๋ ๊ฒ์ด ์ข ๋ ์ ์ ํ๋ค๊ณ ์๊ฐํ๋๋ฐ ์ด๋ป๊ฒ ์๊ฐํ์๋์??ใ
ใ
|
@@ -0,0 +1,40 @@
+package christmas.domain;
+
+import christmas.view.OutputView;
+
+public class EventBadge {
+ // ์ด๋ฒคํธ ๋ฑ์ง๋ฅผ ๊ด๋ฆฌ ํ๋ ํด๋์ค ์
๋๋ค.
+ private static final int SANTA_MINIMUM_LIMIT = 20000;
+ private static final int TREE_MINIMUM_LIMIT = 20000;
+ private static final int STAR_MINIMUM_LIMIT = 20000;
+ private static final String SANTA = "์ฐํ";
+ private static final String TREE = "ํธ๋ฆฌ";
+ private static final String STAR = "๋ณ";
+
+ private static final String NOTHING = "์์";
+
+ private int discountAmount;
+
+ public EventBadge(final int discountAmount) {
+ this.discountAmount = discountAmount;
+ }
+
+ public void printEventBadge() {
+ OutputView.printEventBadge();
+ String badge = determineBadge(discountAmount);
+ OutputView.printMessage(badge);
+ }
+
+ private String determineBadge(final int discountAmount) {
+ if (-discountAmount >= SANTA_MINIMUM_LIMIT) {
+ return SANTA;
+ }
+ if (-discountAmount >= TREE_MINIMUM_LIMIT) {
+ return TREE;
+ }
+ if (-discountAmount >= STAR_MINIMUM_LIMIT) {
+ return STAR;
+ }
+ return NOTHING;
+ }
+} | Java | ์ฒ์๋ณด๋ ์ฌ๋์ discountAmount์ -๋ฅผ ์ ๋ถ์ด์ง? ๋ผ๊ณ ์๊ฐํ ์ ์๋ค๊ณ ์๊ฐํฉ๋๋ค!
์ ๋ ๋น์ทํ๊ฒ ๊ตฌํํ๊ณ ํผ๋๋ฐฑ์ ๋ฐ์๋๋ฐ
๋ณ์์ด๋ฆ๊ณผ final์ ์ด์ฉํด -๋ฅผ ๋ถ์ธ ๋ณ์๊ฐ ๋ฌด์์ ๋ปํ๋์ง ํ๋ฒ ๋ ์ ์ํด์ฃผ๋ ๊ฒ๋ ์ข๋ค๊ณ ์๊ฐํด์! |
@@ -0,0 +1,178 @@
+package christmas.domain;
+
+import christmas.constant.Constants;
+import christmas.constant.Menu;
+import christmas.constant.MenuType;
+import christmas.util.Utils;
+import christmas.view.OutputView;
+import java.time.DayOfWeek;
+import java.time.LocalDate;
+import java.util.ArrayList;
+import java.util.List;
+
+public class BenefitInformation {
+ // ๋ชจ๋ ํํ๊ณผ ๊ด๋ จ๋ ์ ๋ณด๋ฅผ ๊ด๋ฆฌํ๋ ํด๋์ค ์
๋๋ค.
+ private static final String UNIT = "์";
+ private static final int CHAMPAGNE_PRICE = 25000;
+ private Date date;
+ private OrderRepository orderRepository;
+
+ public BenefitInformation(final Date date, final OrderRepository orderRepository) {
+ this.date = date;
+ this.orderRepository = orderRepository;
+ }
+
+ public void printDiscountInfo() {
+ OutputView.printBenefit();
+ int totalAmount = orderRepository.calculateTotalAmount();
+
+ if (totalAmount < Constants.MINIMUM_DISCOUNT_ABLE_AMOUNT.getConstants()) {
+ OutputView.printNothing();
+ return;
+ }
+ List<String> discounts = calculateDiscounts(date, totalAmount);
+
+ if (discounts.isEmpty()) {
+ OutputView.printNothing();
+ return;
+ }
+ printDiscountMessages(discounts);
+ }
+
+ public void printTotalDiscount(final int Amount) {
+ OutputView.printTotalBenefit();
+
+ int totalAmount = Amount;
+
+ if (totalAmount < Constants.MINIMUM_DISCOUNT_ABLE_AMOUNT.getConstants()) {
+ OutputView.printMessage("0" + UNIT);
+ return;
+ }
+
+ int result = calculateTotalDiscount(totalAmount);
+ OutputView.printMessage(Utils.makeFormattedNumberWithComma(result) + UNIT);
+ }
+
+ public void printPaymentAmountAfterDiscount(final int totalAmount) {
+ OutputView.printAfterDiscount();
+
+ int result = calculateAfterDiscount(totalAmount);
+ OutputView.printMessage(Utils.makeFormattedNumberWithComma(result) + UNIT);
+ }
+
+ public int calculateTotalDiscount(final int totalAmount) {
+ int totalDiscount = 0;
+
+ if (totalAmount > 10000) {
+ totalDiscount += calculateChristmasDiscount(date);
+ totalDiscount += calculateWeekdayWeekendDiscount(date);
+ totalDiscount += calculateSpecialDiscount(date);
+ }
+
+ if (totalAmount > Constants.CHAMPAGNE_LIMIT.getConstants()) {
+ totalDiscount -= CHAMPAGNE_PRICE;
+ }
+
+ return totalDiscount;
+ }
+
+ private int calculateAfterDiscount(int totalAmount) {
+ if (totalAmount > Constants.CHAMPAGNE_LIMIT.getConstants()) {
+ totalAmount += CHAMPAGNE_PRICE;
+ }
+ int totalDiscount = calculateTotalDiscount(totalAmount);
+ return totalAmount + totalDiscount;
+ }
+
+ private List<String> calculateDiscounts(final Date date, final int totalAmount) {
+ List<String> discounts = new ArrayList<>();
+
+ addDiscountInfo(discounts, "ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ", calculateChristmasDiscount(date));
+ if (isWeekend(date)) {
+ addDiscountInfo(discounts, "์ฃผ๋ง ํ ์ธ", calculateWeekdayWeekendDiscount(date));
+ }
+ if (!isWeekend(date)) {
+ addDiscountInfo(discounts, "ํ์ผ ํ ์ธ", calculateWeekdayWeekendDiscount(date));
+ }
+ addDiscountInfo(discounts, "ํน๋ณ ํ ์ธ", calculateSpecialDiscount(date));
+
+ if (totalAmount > Constants.CHAMPAGNE_LIMIT.getConstants()) {
+ addDiscountInfo(discounts, "์ฆ์ ์ด๋ฒคํธ", -CHAMPAGNE_PRICE);
+ }
+ return discounts;
+ }
+
+ private boolean isWeekend(Date date) {
+ LocalDate localDate = LocalDate.of(Constants.THIS_YEAR.getConstants(), Constants.EVENT_MONTH.getConstants(),
+ date.getDate());
+ DayOfWeek dayOfWeek = localDate.getDayOfWeek();
+ return dayOfWeek == DayOfWeek.FRIDAY || dayOfWeek == DayOfWeek.SATURDAY;
+ }
+
+ private void printDiscountMessages(final List<String> discounts) {
+ discounts.forEach(OutputView::printMessage);
+ }
+
+ private void addDiscountInfo(final List<String> discounts, final String discountName, final int discountAmount) {
+ if (discountAmount != 0) {
+ discounts.add(discountName + ": " + Utils.makeFormattedNumberWithComma(discountAmount) + UNIT);
+ }
+ }
+
+ private int calculateChristmasDiscount(Date date) {
+ int christmasDiscount = 0;
+ int dayOfMonth = date.getDate();
+
+ if (dayOfMonth >= Constants.EVENT_START_DATE.getConstants()
+ && dayOfMonth <= Constants.EVENT_END_DATE.getConstants()) {
+ int discountPerDay = 1000 + (dayOfMonth - 1) * 100; // ์ผ์ผ ํ ์ธ์ก ๊ณ์ฐ
+ christmasDiscount += discountPerDay;
+ }
+
+ return -christmasDiscount;
+ }
+
+
+ private int calculateWeekdayWeekendDiscount(final Date date) {
+ int weekdayWeekendDiscount = 0;
+
+ LocalDate localDate = LocalDate.of(Constants.THIS_YEAR.getConstants(), Constants.EVENT_MONTH.getConstants(),
+ date.getDate());
+ DayOfWeek dayOfWeek = localDate.getDayOfWeek();
+
+ if (dayOfWeek == DayOfWeek.FRIDAY || dayOfWeek == DayOfWeek.SATURDAY) {
+ weekdayWeekendDiscount = -calculateMainDiscount();
+ return weekdayWeekendDiscount;
+ }
+
+ weekdayWeekendDiscount = -calculateDessertDiscount();
+ return weekdayWeekendDiscount;
+ }
+
+
+ private int calculateDessertDiscount() {
+ List<Order> orders = orderRepository.getOrderList();
+
+ return orders.stream().filter(order -> Menu.getMenuName(order.retrieveMenuName()).getType() == MenuType.DESSERT)
+ .mapToInt(order -> Constants.THIS_YEAR.getConstants() * order.retrieveMenuQuantity()).sum();
+ }
+
+ private int calculateMainDiscount() {
+ List<Order> orders = orderRepository.getOrderList();
+
+ return orders.stream().filter(order -> Menu.getMenuName(order.retrieveMenuName()).getType() == MenuType.MAIN)
+ .mapToInt(order -> Constants.THIS_YEAR.getConstants() * order.retrieveMenuQuantity()).sum();
+ }
+
+ private int calculateSpecialDiscount(final Date date) {
+ int specialDiscount = 0;
+
+ int day = date.getDate();
+
+ if (day == 3 || day == 10 || day == 17 || day == 24 || day == 25 || day == 31) {
+ specialDiscount = -1000;
+ }
+
+ return specialDiscount;
+ }
+} | Java | ๋งค์ง๋๋ฒ๊ฐ ๋ง์ด ์ฐ์ธ ๊ฒ ๊ฐ์ต๋๋ค! ์์์ ์์๋ก ์ ์ธํด์ฃผ๋ฉด ์ข์ ๊ฒ ๊ฐ์์~!! |
@@ -0,0 +1,105 @@
+package christmas.controller;
+
+import christmas.domain.BenefitInformation;
+import christmas.domain.Date;
+import christmas.domain.EventBadge;
+import christmas.domain.GiftMenu;
+import christmas.domain.Order;
+import christmas.domain.OrderManager;
+import christmas.domain.OrderPrice;
+import christmas.domain.OrderRepository;
+import christmas.view.InputView;
+import christmas.view.OutputView;
+import java.util.Map;
+
+public class EventPlannerController {
+ private final InputView inputView;
+ private final OrderRepository orderRepository;
+ private Date date;
+ private int Amount;
+
+ public EventPlannerController(final InputView inputView, final OrderRepository orderRepository) {
+ this.inputView = inputView;
+ this.orderRepository = orderRepository;
+ }
+
+ public void run() {
+ initialize();
+ printResult();
+
+ }
+
+ private void initialize() {
+ OutputView.printWelcome();
+ int dateInput = readDateUntilSuccess();
+ date = new Date(dateInput);
+ Map<String, Integer> menuOrder = readMenuAndQuantityForOrderUntilSuccess();
+
+ menuOrder.entrySet().stream()
+ .map(menu -> new Order(menu.getKey(), menu.getValue()))
+ .forEach(orderRepository::addOrder);
+ OutputView.printBenefit(date.getDate());
+ }
+
+ private void printResult() {
+ printOrderMenu();
+ printTotalOrderAmountBeforeDiscount();
+ printGiftMenu();
+ BenefitInformation benefitInformation = printBenefitDetail();
+ printEventBadge(benefitInformation);
+ }
+
+ private void printEventBadge(final BenefitInformation benefitInformation) {
+ int result = benefitInformation.calculateTotalDiscount(Amount);
+ EventBadge eventBadge = new EventBadge(result);
+ eventBadge.printEventBadge();
+ }
+
+ private BenefitInformation printBenefitDetail() {
+ BenefitInformation benefitInformation = new BenefitInformation(date, orderRepository);
+ benefitInformation.printDiscountInfo();
+
+ benefitInformation.printTotalDiscount(Amount);
+ benefitInformation.printPaymentAmountAfterDiscount(Amount);
+ return benefitInformation;
+ }
+
+ private void printGiftMenu() {
+ GiftMenu giftMenu = new GiftMenu(Amount);
+ giftMenu.printGiftInfo();
+ }
+
+ private void printTotalOrderAmountBeforeDiscount() {
+ OrderPrice orderPriceInfo = new OrderPrice(orderRepository);
+ orderPriceInfo.printBeforeDiscountInfo();
+ Amount = orderPriceInfo.getTotalAmount();
+ }
+
+ private void printOrderMenu() {
+ OrderManager orderInfo = new OrderManager(orderRepository);
+ orderInfo.printAllDetail();
+ }
+
+ private int readDateUntilSuccess() {
+ while (true) {
+ try {
+ int dateInput = inputView.readDate();
+ return dateInput;
+ } catch (IllegalArgumentException exception) {
+ OutputView.printMessage(exception.getMessage());
+ }
+ }
+ }
+
+ private Map<String, Integer> readMenuAndQuantityForOrderUntilSuccess() {
+ while (true) {
+ try {
+ Map<String, Integer> menuAndQuantityForOrder = inputView.readMenuAndQuantityForOrder();
+ return menuAndQuantityForOrder;
+ } catch (IllegalArgumentException exception) {
+ OutputView.printMessage(exception.getMessage());
+ }
+ }
+ }
+}
+ | Java | ๋๋ฉ์ธ๋ณด๋ค๋ controller์์ outputView๋ฅผ ํธ์ถํด์ฃผ๋ ๊ตฌ์กฐ๊ฐ ๋์ด์ผํ๋ค๊ณ ์๊ฐํฉ๋๋ค ใ
ใ
๋ง์ฝ mvc ๊ตฌ์กฐ๋ผ๋ฉด์!! |
@@ -0,0 +1,21 @@
+package christmas.constant;
+
+public enum Constants {
+ EVENT_START_DATE(1),
+ EVENT_END_DATE(25),
+ MENU_LIMIT(20),
+ CHAMPAGNE_LIMIT(120000),
+ MINIMUM_DISCOUNT_ABLE_AMOUNT(10000),
+ THIS_YEAR(2023),
+ EVENT_MONTH(12);
+
+ public int constants;
+
+ Constants(final int constants) {
+ this.constants = constants;
+ }
+
+ public int getConstants() {
+ return constants;
+ }
+} | Java | ํด๋น ์์ ๊ฐ๋ค์ ํ์ํ ๊ฐ ๋๋ฉ์ธ์ด ๋ค๊ณ ์๋ ๊ฒ์ ์ด๋ค๊ฐ์~~?? ๊ทธ๋ ๊ฒ ํ๋ฉด ํด๋์ค์ ์์ง๋๋ฅผ ์กฐ๊ธ ๋ ๋์ผ ์ ์์ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,13 @@
+package christmas.domain;
+
+public class Date {
+ private int date;
+
+ public Date(final int date) {
+ this.date = date;
+ }
+
+ public int getDate() {
+ return this.date;
+ }
+}
\ No newline at end of file | Java | ํด๋น ํด๋์ค๊ฐ ์กด์ฌํ๋ ์ด์ ๊ฐ ์๋์?!! ํด๋์ค๋ก์ ์์ ํ๋ ค๋ฉด Date์ ๊ด๋ จ๋ validate ์ฝ๋๊ฐ ์์ฑ์ ์์ ์์ด์ผํ ๊ฒ ๊ฐ์ต๋๋ค..!!! |
@@ -0,0 +1,13 @@
+package christmas.domain;
+
+public class Date {
+ private int date;
+
+ public Date(final int date) {
+ this.date = date;
+ }
+
+ public int getDate() {
+ return this.date;
+ }
+}
\ No newline at end of file | Java | ๋ํ record๋ก ๋ฐ๊ฟ๋ ์ข์ ๊ฒ ๊ฐ๋ค์ ใ
ใ
|
@@ -0,0 +1,21 @@
+package christmas.constant;
+
+public enum Constants {
+ EVENT_START_DATE(1),
+ EVENT_END_DATE(25),
+ MENU_LIMIT(20),
+ CHAMPAGNE_LIMIT(120000),
+ MINIMUM_DISCOUNT_ABLE_AMOUNT(10000),
+ THIS_YEAR(2023),
+ EVENT_MONTH(12);
+
+ public int constants;
+
+ Constants(final int constants) {
+ this.constants = constants;
+ }
+
+ public int getConstants() {
+ return constants;
+ }
+} | Java | ๊ฐ ๋๋ฉ์ธ์ด ๋ค๋ฉฐ ์์ง๋๋ฅผ ๋ํ๋ ๋ฐฉ๋ฒ๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค! ๐ซ |
@@ -0,0 +1,105 @@
+package christmas.controller;
+
+import christmas.domain.BenefitInformation;
+import christmas.domain.Date;
+import christmas.domain.EventBadge;
+import christmas.domain.GiftMenu;
+import christmas.domain.Order;
+import christmas.domain.OrderManager;
+import christmas.domain.OrderPrice;
+import christmas.domain.OrderRepository;
+import christmas.view.InputView;
+import christmas.view.OutputView;
+import java.util.Map;
+
+public class EventPlannerController {
+ private final InputView inputView;
+ private final OrderRepository orderRepository;
+ private Date date;
+ private int Amount;
+
+ public EventPlannerController(final InputView inputView, final OrderRepository orderRepository) {
+ this.inputView = inputView;
+ this.orderRepository = orderRepository;
+ }
+
+ public void run() {
+ initialize();
+ printResult();
+
+ }
+
+ private void initialize() {
+ OutputView.printWelcome();
+ int dateInput = readDateUntilSuccess();
+ date = new Date(dateInput);
+ Map<String, Integer> menuOrder = readMenuAndQuantityForOrderUntilSuccess();
+
+ menuOrder.entrySet().stream()
+ .map(menu -> new Order(menu.getKey(), menu.getValue()))
+ .forEach(orderRepository::addOrder);
+ OutputView.printBenefit(date.getDate());
+ }
+
+ private void printResult() {
+ printOrderMenu();
+ printTotalOrderAmountBeforeDiscount();
+ printGiftMenu();
+ BenefitInformation benefitInformation = printBenefitDetail();
+ printEventBadge(benefitInformation);
+ }
+
+ private void printEventBadge(final BenefitInformation benefitInformation) {
+ int result = benefitInformation.calculateTotalDiscount(Amount);
+ EventBadge eventBadge = new EventBadge(result);
+ eventBadge.printEventBadge();
+ }
+
+ private BenefitInformation printBenefitDetail() {
+ BenefitInformation benefitInformation = new BenefitInformation(date, orderRepository);
+ benefitInformation.printDiscountInfo();
+
+ benefitInformation.printTotalDiscount(Amount);
+ benefitInformation.printPaymentAmountAfterDiscount(Amount);
+ return benefitInformation;
+ }
+
+ private void printGiftMenu() {
+ GiftMenu giftMenu = new GiftMenu(Amount);
+ giftMenu.printGiftInfo();
+ }
+
+ private void printTotalOrderAmountBeforeDiscount() {
+ OrderPrice orderPriceInfo = new OrderPrice(orderRepository);
+ orderPriceInfo.printBeforeDiscountInfo();
+ Amount = orderPriceInfo.getTotalAmount();
+ }
+
+ private void printOrderMenu() {
+ OrderManager orderInfo = new OrderManager(orderRepository);
+ orderInfo.printAllDetail();
+ }
+
+ private int readDateUntilSuccess() {
+ while (true) {
+ try {
+ int dateInput = inputView.readDate();
+ return dateInput;
+ } catch (IllegalArgumentException exception) {
+ OutputView.printMessage(exception.getMessage());
+ }
+ }
+ }
+
+ private Map<String, Integer> readMenuAndQuantityForOrderUntilSuccess() {
+ while (true) {
+ try {
+ Map<String, Integer> menuAndQuantityForOrder = inputView.readMenuAndQuantityForOrder();
+ return menuAndQuantityForOrder;
+ } catch (IllegalArgumentException exception) {
+ OutputView.printMessage(exception.getMessage());
+ }
+ }
+ }
+}
+ | Java | MVC ๋ง์ด ๊ณต๋ถํด์ผ ๊ฒ ๋ค์ ใ
ใ
|
@@ -0,0 +1,13 @@
+package christmas.domain;
+
+public class Date {
+ private int date;
+
+ public Date(final int date) {
+ this.date = date;
+ }
+
+ public int getDate() {
+ return this.date;
+ }
+}
\ No newline at end of file | Java | recordํ์ ์์ฐ๋ ์ฝ๋ ๋ณด๋ฉด์ ์ฒ์ ๋ฐฐ์ ๋๋ฐ ์ ์ฉํ๊ฒ ์ ์ฌ์ฉํ ์ ์์ ๊ฒ ๊ฐ์ต๋๋ค !
`date`์ `validate`๊ฐ ์๋ ์ด์์ ์ฌ์ค ์๋ฏธ๊ฐ ์๋๊ฑฐ ๊ฐ๋ค์,,ใ
ใ
|
@@ -0,0 +1,40 @@
+package christmas.domain;
+
+import christmas.view.OutputView;
+
+public class EventBadge {
+ // ์ด๋ฒคํธ ๋ฑ์ง๋ฅผ ๊ด๋ฆฌ ํ๋ ํด๋์ค ์
๋๋ค.
+ private static final int SANTA_MINIMUM_LIMIT = 20000;
+ private static final int TREE_MINIMUM_LIMIT = 20000;
+ private static final int STAR_MINIMUM_LIMIT = 20000;
+ private static final String SANTA = "์ฐํ";
+ private static final String TREE = "ํธ๋ฆฌ";
+ private static final String STAR = "๋ณ";
+
+ private static final String NOTHING = "์์";
+
+ private int discountAmount;
+
+ public EventBadge(final int discountAmount) {
+ this.discountAmount = discountAmount;
+ }
+
+ public void printEventBadge() {
+ OutputView.printEventBadge();
+ String badge = determineBadge(discountAmount);
+ OutputView.printMessage(badge);
+ }
+
+ private String determineBadge(final int discountAmount) {
+ if (-discountAmount >= SANTA_MINIMUM_LIMIT) {
+ return SANTA;
+ }
+ if (-discountAmount >= TREE_MINIMUM_LIMIT) {
+ return TREE;
+ }
+ if (-discountAmount >= STAR_MINIMUM_LIMIT) {
+ return STAR;
+ }
+ return NOTHING;
+ }
+} | Java | ๋ชจ๋ฅด๋ ์ฌ๋์ด ์ฝ๋๋ฅผ ๋ณด๋ฉด ์ ์์ง? ์๊ฐํ ์๋ ์๊ฒ ๋ค์!
๋ณ์๋ช
๊ณผ, ์ฃผ์์ ํตํด ์๋ฏธ๋ฅผ ๋ํ๋ด๋ ๊ฒ๋ ์ข์ ๋ฐฉ๋ฒ์ธ ๊ฒ ๊ฐ๋ค์ ๐ซ |
@@ -0,0 +1,28 @@
+package christmas.domain;
+
+import christmas.util.Utils;
+import christmas.view.OutputView;
+
+public class OrderPrice {
+ // ๊ธ์ก๊ณผ ๊ด๋ จ๋ ํด๋์ค์
๋๋ค.
+ // ํ ์ธ ์ ์ด ์ฃผ๋ฌธ๊ธ์ก, ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก ๋ฑ์ ๊ด๋ฆฌํ๋ ํด๋์ค ์
๋๋ค.
+ private static final String UNIT = "์";
+ private OrderRepository orders;
+ private int totalAmount;
+
+ public OrderPrice(final OrderRepository orders) {
+ this.orders = orders;
+ }
+
+ public void printBeforeDiscountInfo() {
+ this.totalAmount = orders.calculateTotalAmount();
+
+ OutputView.printBeforeDiscount();
+ String result = Utils.makeFormattedNumberWithComma(this.totalAmount);
+ OutputView.printMessage(result + UNIT);
+ }
+
+ public int getTotalAmount() {
+ return totalAmount;
+ }
+} | Java | ๋ฐ๋ก OutputView ํด๋์ค์ ์ ์ธํ๋๊ฒ ์ข ๋ ์ ์ ํด ๋ณด์ด๋ค์ ใ
ใ
|
@@ -0,0 +1,135 @@
+package christmas.validator;
+
+import christmas.constant.Constants;
+import christmas.constant.ErrorMessage;
+import christmas.constant.Menu;
+import christmas.util.Utils;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+public class OrderValidator implements Validator {
+ @Override
+ public void check(String input) {
+ chechDefaultTemplate(input);
+ checkValidatedForm(input);
+ checkIfStringMenu(input);
+ checkQuantityRange(input);
+ checkIfMenuExists(input);
+ checkForDuplicateMenu(input);
+ checkTotalMenuCount(input);
+ checkBeverageOnly(input);
+ }
+
+ private void chechDefaultTemplate(final String input) {
+ List<String> orderItems = Arrays.asList(input.split(","));
+
+ orderItems.stream()
+ .map(item -> item.split("-"))
+ .forEach(parts -> {
+ try {
+ if (parts.length != 2 || !parts[1].matches("\\d+")) {
+ throw new IllegalArgumentException(ErrorMessage.NOT_VALIDATED_ORDER.getMessage());
+ }
+ } catch (IllegalArgumentException e) {
+ throw new IllegalArgumentException(ErrorMessage.NOT_VALIDATED_ORDER.getMessage());
+ }
+ });
+ }
+
+ private void checkValidatedForm(final String input) { // ์ ํจํ์ง์์ ์
๋ ฅ (๊ธฐ๋ณธ ํ
ํ๋ฆฟ ์
๋ ฅ์ด ์๋ ๊ฒฝ์ฐ) [์์ฒญ ์ฌํญ ์กด์ฌ]
+ try {
+ Map<String, Integer> resultMap = Stream.of(input.split(","))
+ .map(s -> s.split("-")).collect(Collectors.toMap(
+ arr -> arr[0],
+ arr -> Integer.parseInt(arr[1]),
+ (existing, replacement) -> existing,
+ HashMap::new
+ ));
+ // {"ํด์ฐ๋ฌผํ์คํ": 2, "๋ ๋์์ธ": 1, ...}
+ } catch (IllegalArgumentException e) {
+ throw new IllegalArgumentException(ErrorMessage.NOT_VALIDATED_ORDER.getMessage());
+ }
+ }
+
+ private void checkIfStringMenu(final String input) { // ๋ฉ๋ด(key) ๋ถ๋ถ์ด String, ์ฆ ๋ฌธ์์ด(ํ๊ธ,์์ด)์ด ์๋๋ฉด ์์ธ์ฒ๋ฆฌ [์์ฒญ ํ
ํ๋ฆฟ]
+ Map<String, Integer> menu = Utils.makeStringToHashMap(input);
+ menu.keySet().stream()
+ .filter(key -> !key.matches("[a-zA-Z๊ฐ-ํฃ]+"))
+ .findAny()
+ .ifPresent(invalidKey -> {
+ throw new IllegalArgumentException(ErrorMessage.NOT_VALIDATED_ORDER.getMessage());
+ });
+ }
+
+ private void checkQuantityRange(final String input) { // ์๋์ด ๊ฐ๊ฐ 1์ด์ 20์ดํ ๊ฐ ์๋๋ฉด ์์ธ์ฒ๋ฆฌ [์์ฒญ ์ฌํญ ์กด์ฌ]
+ try {
+ Map<String, Integer> menu = Utils.makeStringToHashMap(input);
+ menu.entrySet().stream()
+ .filter(entry -> entry.getValue() < 1 || entry.getValue() > 20)
+ .findAny()
+ .ifPresent(entry -> {
+ throw new IllegalArgumentException(ErrorMessage.NOT_VALIDATED_ORDER.getMessage());
+ });
+ } catch (IllegalArgumentException e) {
+ throw new IllegalArgumentException(ErrorMessage.NOT_VALIDATED_ORDER.getMessage());
+ }
+ }
+
+ private void checkIfMenuExists(final String input) { // ์๋ ๋ฉ๋ด์ผ์ง ์์ธ์ฒ๋ฆฌ ( ex) T๋ณธ์คํ
์ดํฌ ) [์์ฒญ ์ฌํญ ์กด์ฌ]
+ Map<String, Integer> menu = Utils.makeStringToHashMap(input);
+
+ Set<String> availableMenuItems = Arrays.stream(Menu.values())
+ .map(menuEnum -> menuEnum.getName())
+ .collect(Collectors.toSet());
+
+ menu.keySet().stream()
+ .filter(inputMenu -> !availableMenuItems.contains(inputMenu))
+ .findAny()
+ .ifPresent(invalidKey -> {
+ throw new IllegalArgumentException(ErrorMessage.NOT_VALIDATED_ORDER.getMessage());
+ });
+ }
+
+ private void checkForDuplicateMenu(final String input) {
+ Map<String, Integer> resultMap = Stream.of(input.split(","))
+ .map(s -> s.split("-"))
+ .collect(Collectors.toMap(
+ arr -> arr[0],
+ arr -> Integer.parseInt(arr[1]),
+ (existing, replacement) -> {
+ throw new IllegalArgumentException(ErrorMessage.NOT_VALIDATED_ORDER.getMessage());
+ },
+ HashMap::new
+ ));
+ }
+
+ private void checkTotalMenuCount(final String input) {
+ // ๋ฉ๋ด ๊ฐ์์ ํฉ์ด 20๊ฐ๊ฐ ์ด๊ณผํ ์ ์์ธ์ฒ๋ฆฌ
+ Map<String, Integer> menu = Utils.makeStringToHashMap(input);
+ int total = menu.values().stream().mapToInt(Integer::intValue).sum();
+
+ if (total > Constants.MENU_LIMIT.getConstants()) {
+ throw new IllegalArgumentException(ErrorMessage.TOTAL_MENU_COUNT_IS_OVER.getMessage());
+ }
+ }
+
+ private void checkBeverageOnly(final String input) {
+ // ๊ฐ ๋ฉ๋ด์ ์๋ฃ ํด๋์ค๋ง ์์ผ๋ฉด ์์ธ์ฒ๋ฆฌ
+
+ Map<String, Integer> menu = Utils.makeStringToHashMap(input);
+ List<String> onlyBeverage = Menu.BEVERAGE_MENU;
+
+ List<String> matchCount = menu.keySet().stream()
+ .filter(onlyBeverage::contains)
+ .toList();
+
+ if (menu.size() == matchCount.size()) {
+ throw new IllegalArgumentException(ErrorMessage.ORDER_ONLY_BEVERAGE.getMessage());
+ }
+ }
+} | Java | ์ข์ ์ ๋ณด ๊ฐ์ฌํฉ๋๋ค ๐ฅ๐ฅ |
@@ -1,5 +1,12 @@
+import EventController from "./controller/EventController.js";
+
class App {
- async run() {}
+ constructor() {
+ this.eventController = new EventController();
+ }
+ async run() {
+ await this.eventController.eventStart();
+ }
}
export default App; | JavaScript | App ์์ฒด๊ฐ Controller๋ผ๊ณ ์๊ฐํ๊ณ ๊ตฌํ์ ํ๋ ๋ฐฉ๋ฒ๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค |
@@ -0,0 +1,111 @@
+import { MENU, MESSAGE, ARRAY, CALENDAR, BENEFIT_AMOUNT, BADGE, BOUNDARY } from "../commons/constants.js";
+import Order from "./Order.js";
+import { getMenu, getMenuCount } from "../commons/utils.js";
+
+class Benefit {
+ #date;
+ #menu;
+ #order;
+ #benefitResult;
+
+ constructor(date, menu) {
+ this.#date = date;
+ this.#menu = menu;
+ this.#order = new Order(date, menu);
+ }
+
+ // ํํ ๋ด์ญ
+ benefitDetail() {
+ // benefitResult [ DDay | Weekday | Weekend | Special | Giveaway ]
+ this.#benefitResult = [0, 0, 0, 0, 0];
+
+ if (this.#isBenefit()) {
+ if (this.#isDDay()) this.#benefitResult[ARRAY.DDAY] = this.#applyDDay();
+ if (this.#isWeekday()) this.#benefitResult[ARRAY.WEEKDAY] = this.#applyWeekday();
+ if (this.#isWeekend()) this.#benefitResult[ARRAY.WEEKEND] = this.#applyWeekend();
+ if (this.#isSpecial()) this.#benefitResult[ARRAY.SPECIALDAY] = this.#applySpecial();
+ if (this.#isGiveaway()) this.#benefitResult[ARRAY.GIVEAWAY] = this.#applyGiveaway();
+ }
+
+ return this.#benefitResult;
+ }
+
+ // ์ด ํํ ๊ธ์ก
+ totalBenefit() {
+ let totalBenefit = 0;
+ this.#benefitResult.forEach((benefit) => {
+ totalBenefit += benefit;
+ });
+
+ return totalBenefit;
+ }
+
+ // ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก
+ expectedAmount() {
+ const totalDiscount = this.totalBenefit() - this.#benefitResult[ARRAY.GIVEAWAY];
+
+ return this.#order.getAllAmount() - totalDiscount;
+ }
+
+ // 12์ ์ด๋ฒคํธ ๋ฐฐ์ง
+ eventBadge() {
+ const totalBenefit = this.totalBenefit();
+
+ if (!this.#isBenefit()) return MESSAGE.NOTHING;
+ if (totalBenefit <= BOUNDARY.STAR_PRICE) return BADGE.STAR;
+ if (totalBenefit <= BOUNDARY.TREE_PRICE) return BADGE.TREE;
+
+ return BADGE.SANTA;
+ }
+
+ #isBenefit() {
+ return this.#order.getAllAmount() > BOUNDARY.BENEFIT_PRICE;
+ }
+
+ #isDDay() {
+ return this.#date <= BOUNDARY.DDAY_END;
+ }
+
+ #isWeekday() {
+ return CALENDAR.WEEKDAY.includes(this.#date);
+ }
+
+ #isWeekend() {
+ return CALENDAR.WEEKEND.includes(this.#date);
+ }
+
+ #isSpecial() {
+ return CALENDAR.SPECIAL.includes(this.#date);
+ }
+
+ #isGiveaway() {
+ return this.#order.getAllAmount() >= BOUNDARY.GIVEAWAY_PRICE;
+ }
+
+ #applyDDay() {
+ let discount = BENEFIT_AMOUNT.DDAY_START;
+ for (let day = 1; day < this.#date; day++) {
+ discount += BENEFIT_AMOUNT.DDAY_PLUS;
+ }
+ return discount;
+ }
+
+ #applyWeekday() {
+ const menuCount = getMenuCount(getMenu(MENU.DESSERT), this.#menu);
+ return menuCount * BENEFIT_AMOUNT.WEEKDAY;
+ }
+
+ #applyWeekend() {
+ const menuCount = getMenuCount(getMenu(MENU.MAIN), this.#menu);
+ return menuCount * BENEFIT_AMOUNT.WEEKEND;
+ }
+
+ #applySpecial() {
+ return BENEFIT_AMOUNT.SPECIALDAY;
+ }
+
+ #applyGiveaway() {
+ return BENEFIT_AMOUNT.GIVEAWAY;
+ }
+}
+export default Benefit; | JavaScript | benefitResult๋ฅผ Obejct๋ก ๊ตฌํํ๋ฉด ์ข ๋ ๊ฐ๋
์ฑ์ด ์ข์ง ์์๊น ์ถ์ต๋๋ค |
@@ -0,0 +1,88 @@
+import Benefit from "../src/model/Benefit.js";
+import { orderIntoArray } from "../src/commons/utils.js";
+
+describe("Benefit ํด๋์ค ํ
์คํธ(ํํ ์๋ ๊ฒฝ์ฐ)", () => {
+ //given
+ const date = "3";
+ const menu = orderIntoArray("ํฐ๋ณธ์คํ
์ดํฌ-1,๋ฐ๋นํ๋ฆฝ-1,์ด์ฝ์ผ์ดํฌ-2,์ ๋ก์ฝ๋ผ-1");
+ const benefit = new Benefit(date, menu);
+
+ test("Benefit Detail(ํํ ๋ด์ญ) ํ
์คํธ", () => {
+ // when
+ const result = benefit.benefitDetail();
+ // then
+ const expected = [1200, 4046, 0, 1000, 25000];
+
+ expect(result).toEqual(expected);
+ });
+
+ test("Total Beneift(์ด ํํ ๊ธ์ก) ํ
์คํธ", () => {
+ // when
+ const result = benefit.totalBenefit();
+ // then
+ const expected = 31246;
+
+ expect(result).toEqual(expected);
+ });
+
+ test("Expected Amount(์์ ๊ฒฐ์ ๊ธ์ก) ํ
์คํธ", () => {
+ // when
+ const result = benefit.expectedAmount();
+ // then
+ const expected = 135754;
+
+ expect(result).toEqual(expected);
+ });
+
+ test("Event Badge(์ด๋ฒคํธ ๋ฐฐ์ง) ํ
์คํธ", () => {
+ // when
+ const result = benefit.eventBadge();
+ // then
+ const expected = "์ฐํ";
+
+ expect(result).toEqual(expected);
+ });
+});
+
+describe("Benefit ํด๋์ค ํ
์คํธ(ํํ ์๋ ๊ฒฝ์ฐ)", () => {
+ //given
+ const date = "26";
+ const menu = orderIntoArray("ํํ์ค-1,์ ๋ก์ฝ๋ผ-1");
+ const benefit = new Benefit(date, menu);
+
+ test("Benefit Detail(ํํ ๋ด์ญ) ํ
์คํธ", () => {
+ // when
+ const result = benefit.benefitDetail();
+ // then
+ const expected = [0, 0, 0, 0, 0];
+
+ expect(result).toEqual(expected);
+ });
+
+ test("Total Beneift(์ด ํํ ๊ธ์ก) ํ
์คํธ", () => {
+ // when
+ const result = benefit.totalBenefit();
+ // then
+ const expected = 0;
+
+ expect(result).toEqual(expected);
+ });
+
+ test("Expected Amount(์์ ๊ฒฐ์ ๊ธ์ก) ํ
์คํธ", () => {
+ // when
+ const result = benefit.expectedAmount();
+ // then
+ const expected = 8500;
+
+ expect(result).toEqual(expected);
+ });
+
+ test("Event Badge(์ด๋ฒคํธ ๋ฐฐ์ง) ํ
์คํธ", () => {
+ // when
+ const result = benefit.eventBadge();
+ // then
+ const expected = "์์";
+
+ expect(result).toEqual(expected);
+ });
+}); | JavaScript | ํ
์คํธ๊ฐ ๋๋ฌด ํ์ ๋์ด ์๋๊ฒ ๊ฐ์ต๋๋ค test.each๋ฅผ ์ฌ์ฉํ์ฌ ์ข ๋ ๋ฒ์์ฑ ์๊ฒ ํ
์คํธ๋ฅผ ๊ตฌํํ๋ ๋ฐฉ๋ฒ์ด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค |
@@ -0,0 +1,63 @@
+import InputView from "../view/InputView.js";
+import OutputView from "../view/OutputView.js";
+import Order from "../model/Order.js";
+import Benefit from "../model/Benefit.js";
+import { print } from "../commons/utils.js";
+import { MENU } from "../commons/constants.js";
+
+class EventController {
+ #date;
+ #menu;
+
+ async eventStart() {
+ OutputView.printStart();
+
+ // ์ฃผ๋ฌธ ์ ๋ณด ์
๋ ฅ & ์ฃผ๋ฌธ ์ ๋ณด ์ถ๋ ฅ
+ await this.#getOrderInformation();
+ OutputView.printOrderInformation(this.#date, this.#menu);
+
+ // ์ฃผ๋ฌธ ํด๋์ค ์์ฑ & ์ด ์ฃผ๋ฌธ ๊ธ์ก ์ถ๋ ฅ
+ const order = new Order(this.#date, this.#menu);
+ OutputView.printAllAmount(order.getAllAmount());
+
+ // ํํ ํด๋์ค ์์ฑ & ํํ๊ณผ ๊ด๋ จ๋ ๋ฉ์ธ์ง ์ถ๋ ฅ
+ const benefit = new Benefit(this.#date, this.#menu);
+ this.#printBenefit(benefit);
+ }
+
+ async #getOrderInformation() {
+ await this.#getDate();
+ await this.#getMenu();
+ }
+
+ async #getDate() {
+ while (true) {
+ try {
+ this.#date = await InputView.inputDate();
+ break;
+ } catch (error) {
+ print(error);
+ }
+ }
+ }
+
+ async #getMenu() {
+ while (true) {
+ try {
+ this.#menu = await InputView.inputMenu();
+ break;
+ } catch (error) {
+ print(error);
+ }
+ }
+ }
+
+ #printBenefit(benefit) {
+ OutputView.printGiveaway(benefit.benefitDetail()); // <์ฆ์ ๋ฉ๋ด>
+ OutputView.printBenefitDetail(benefit.benefitDetail()); // <ํํ ๋ด์ญ>
+ OutputView.printTotalBenefit(benefit.totalBenefit()); // <์ด ํํ
๊ธ์ก>
+ OutputView.printExpectedAmount(benefit.expectedAmount()); // <ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก>
+ OutputView.printEventBadge(benefit.eventBadge()); // <12์ ์ด๋ฒคํธ ๋ฐฐ์ง>
+ }
+}
+export default EventController; | JavaScript | ๊ฐ๊ฐ์ ๋๋ ํ ๋ฆฌ์ index.js ๋ฅผ ์ถ๊ฐํ๊ณ , ๊ณตํต๋๊ฒ export ์ํค๋ฉด, import ๋ฅผ ๊ฐ๋จํ๊ฒ ํ ์ ์์ต๋๋ค!
*view/index.js*
```javascript
export {default as InputView.js} from './InputView.js'
export {default as OutputView.js} from './OutputView.js'
```
*EventController.js*
```javascript
import { InputView, OutputView } '../view/index.js'
``` |
@@ -0,0 +1,111 @@
+import { MENU, MESSAGE, ARRAY, CALENDAR, BENEFIT_AMOUNT, BADGE, BOUNDARY } from "../commons/constants.js";
+import Order from "./Order.js";
+import { getMenu, getMenuCount } from "../commons/utils.js";
+
+class Benefit {
+ #date;
+ #menu;
+ #order;
+ #benefitResult;
+
+ constructor(date, menu) {
+ this.#date = date;
+ this.#menu = menu;
+ this.#order = new Order(date, menu);
+ }
+
+ // ํํ ๋ด์ญ
+ benefitDetail() {
+ // benefitResult [ DDay | Weekday | Weekend | Special | Giveaway ]
+ this.#benefitResult = [0, 0, 0, 0, 0];
+
+ if (this.#isBenefit()) {
+ if (this.#isDDay()) this.#benefitResult[ARRAY.DDAY] = this.#applyDDay();
+ if (this.#isWeekday()) this.#benefitResult[ARRAY.WEEKDAY] = this.#applyWeekday();
+ if (this.#isWeekend()) this.#benefitResult[ARRAY.WEEKEND] = this.#applyWeekend();
+ if (this.#isSpecial()) this.#benefitResult[ARRAY.SPECIALDAY] = this.#applySpecial();
+ if (this.#isGiveaway()) this.#benefitResult[ARRAY.GIVEAWAY] = this.#applyGiveaway();
+ }
+
+ return this.#benefitResult;
+ }
+
+ // ์ด ํํ ๊ธ์ก
+ totalBenefit() {
+ let totalBenefit = 0;
+ this.#benefitResult.forEach((benefit) => {
+ totalBenefit += benefit;
+ });
+
+ return totalBenefit;
+ }
+
+ // ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก
+ expectedAmount() {
+ const totalDiscount = this.totalBenefit() - this.#benefitResult[ARRAY.GIVEAWAY];
+
+ return this.#order.getAllAmount() - totalDiscount;
+ }
+
+ // 12์ ์ด๋ฒคํธ ๋ฐฐ์ง
+ eventBadge() {
+ const totalBenefit = this.totalBenefit();
+
+ if (!this.#isBenefit()) return MESSAGE.NOTHING;
+ if (totalBenefit <= BOUNDARY.STAR_PRICE) return BADGE.STAR;
+ if (totalBenefit <= BOUNDARY.TREE_PRICE) return BADGE.TREE;
+
+ return BADGE.SANTA;
+ }
+
+ #isBenefit() {
+ return this.#order.getAllAmount() > BOUNDARY.BENEFIT_PRICE;
+ }
+
+ #isDDay() {
+ return this.#date <= BOUNDARY.DDAY_END;
+ }
+
+ #isWeekday() {
+ return CALENDAR.WEEKDAY.includes(this.#date);
+ }
+
+ #isWeekend() {
+ return CALENDAR.WEEKEND.includes(this.#date);
+ }
+
+ #isSpecial() {
+ return CALENDAR.SPECIAL.includes(this.#date);
+ }
+
+ #isGiveaway() {
+ return this.#order.getAllAmount() >= BOUNDARY.GIVEAWAY_PRICE;
+ }
+
+ #applyDDay() {
+ let discount = BENEFIT_AMOUNT.DDAY_START;
+ for (let day = 1; day < this.#date; day++) {
+ discount += BENEFIT_AMOUNT.DDAY_PLUS;
+ }
+ return discount;
+ }
+
+ #applyWeekday() {
+ const menuCount = getMenuCount(getMenu(MENU.DESSERT), this.#menu);
+ return menuCount * BENEFIT_AMOUNT.WEEKDAY;
+ }
+
+ #applyWeekend() {
+ const menuCount = getMenuCount(getMenu(MENU.MAIN), this.#menu);
+ return menuCount * BENEFIT_AMOUNT.WEEKEND;
+ }
+
+ #applySpecial() {
+ return BENEFIT_AMOUNT.SPECIALDAY;
+ }
+
+ #applyGiveaway() {
+ return BENEFIT_AMOUNT.GIVEAWAY;
+ }
+}
+export default Benefit; | JavaScript | ```javascript
this.#benefitResult = Array.from({length:5(ํํ์ ๊ธธ์ด๋ฅผ ๋ํ๋ด๋ ์์๋ก ์์ )}, () => 0)
```
์ ๊ฐ์ด ๋ฐ๊พธ๋ ๊ฒ์ ์ด๋จ๊น์? |
@@ -0,0 +1,111 @@
+import { MENU, MESSAGE, ARRAY, CALENDAR, BENEFIT_AMOUNT, BADGE, BOUNDARY } from "../commons/constants.js";
+import Order from "./Order.js";
+import { getMenu, getMenuCount } from "../commons/utils.js";
+
+class Benefit {
+ #date;
+ #menu;
+ #order;
+ #benefitResult;
+
+ constructor(date, menu) {
+ this.#date = date;
+ this.#menu = menu;
+ this.#order = new Order(date, menu);
+ }
+
+ // ํํ ๋ด์ญ
+ benefitDetail() {
+ // benefitResult [ DDay | Weekday | Weekend | Special | Giveaway ]
+ this.#benefitResult = [0, 0, 0, 0, 0];
+
+ if (this.#isBenefit()) {
+ if (this.#isDDay()) this.#benefitResult[ARRAY.DDAY] = this.#applyDDay();
+ if (this.#isWeekday()) this.#benefitResult[ARRAY.WEEKDAY] = this.#applyWeekday();
+ if (this.#isWeekend()) this.#benefitResult[ARRAY.WEEKEND] = this.#applyWeekend();
+ if (this.#isSpecial()) this.#benefitResult[ARRAY.SPECIALDAY] = this.#applySpecial();
+ if (this.#isGiveaway()) this.#benefitResult[ARRAY.GIVEAWAY] = this.#applyGiveaway();
+ }
+
+ return this.#benefitResult;
+ }
+
+ // ์ด ํํ ๊ธ์ก
+ totalBenefit() {
+ let totalBenefit = 0;
+ this.#benefitResult.forEach((benefit) => {
+ totalBenefit += benefit;
+ });
+
+ return totalBenefit;
+ }
+
+ // ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก
+ expectedAmount() {
+ const totalDiscount = this.totalBenefit() - this.#benefitResult[ARRAY.GIVEAWAY];
+
+ return this.#order.getAllAmount() - totalDiscount;
+ }
+
+ // 12์ ์ด๋ฒคํธ ๋ฐฐ์ง
+ eventBadge() {
+ const totalBenefit = this.totalBenefit();
+
+ if (!this.#isBenefit()) return MESSAGE.NOTHING;
+ if (totalBenefit <= BOUNDARY.STAR_PRICE) return BADGE.STAR;
+ if (totalBenefit <= BOUNDARY.TREE_PRICE) return BADGE.TREE;
+
+ return BADGE.SANTA;
+ }
+
+ #isBenefit() {
+ return this.#order.getAllAmount() > BOUNDARY.BENEFIT_PRICE;
+ }
+
+ #isDDay() {
+ return this.#date <= BOUNDARY.DDAY_END;
+ }
+
+ #isWeekday() {
+ return CALENDAR.WEEKDAY.includes(this.#date);
+ }
+
+ #isWeekend() {
+ return CALENDAR.WEEKEND.includes(this.#date);
+ }
+
+ #isSpecial() {
+ return CALENDAR.SPECIAL.includes(this.#date);
+ }
+
+ #isGiveaway() {
+ return this.#order.getAllAmount() >= BOUNDARY.GIVEAWAY_PRICE;
+ }
+
+ #applyDDay() {
+ let discount = BENEFIT_AMOUNT.DDAY_START;
+ for (let day = 1; day < this.#date; day++) {
+ discount += BENEFIT_AMOUNT.DDAY_PLUS;
+ }
+ return discount;
+ }
+
+ #applyWeekday() {
+ const menuCount = getMenuCount(getMenu(MENU.DESSERT), this.#menu);
+ return menuCount * BENEFIT_AMOUNT.WEEKDAY;
+ }
+
+ #applyWeekend() {
+ const menuCount = getMenuCount(getMenu(MENU.MAIN), this.#menu);
+ return menuCount * BENEFIT_AMOUNT.WEEKEND;
+ }
+
+ #applySpecial() {
+ return BENEFIT_AMOUNT.SPECIALDAY;
+ }
+
+ #applyGiveaway() {
+ return BENEFIT_AMOUNT.GIVEAWAY;
+ }
+}
+export default Benefit; | JavaScript | ํด๋์ค ๋ถ๋ฆฌ์ ๋๋ฌด ์ง์คํ๋๋ผ
ํํ์ ํ์ธํ๋ ํด๋์ค์ ํํ์ ์ ์ฉํ๋ ํด๋์ค๋ก ๋ถ๋ฆฌํด์ ์์ฑํ์๋๋ฐ,
ํ๋์ ํด๋์ค์ ๋ฌถ์ด์ ์์ฑํ๋ ๊ฒ๋ ๊ด์ฐฎ์ ๋ณด์ด๋ค์๐ |
@@ -0,0 +1,63 @@
+import InputView from "../view/InputView.js";
+import OutputView from "../view/OutputView.js";
+import Order from "../model/Order.js";
+import Benefit from "../model/Benefit.js";
+import { print } from "../commons/utils.js";
+import { MENU } from "../commons/constants.js";
+
+class EventController {
+ #date;
+ #menu;
+
+ async eventStart() {
+ OutputView.printStart();
+
+ // ์ฃผ๋ฌธ ์ ๋ณด ์
๋ ฅ & ์ฃผ๋ฌธ ์ ๋ณด ์ถ๋ ฅ
+ await this.#getOrderInformation();
+ OutputView.printOrderInformation(this.#date, this.#menu);
+
+ // ์ฃผ๋ฌธ ํด๋์ค ์์ฑ & ์ด ์ฃผ๋ฌธ ๊ธ์ก ์ถ๋ ฅ
+ const order = new Order(this.#date, this.#menu);
+ OutputView.printAllAmount(order.getAllAmount());
+
+ // ํํ ํด๋์ค ์์ฑ & ํํ๊ณผ ๊ด๋ จ๋ ๋ฉ์ธ์ง ์ถ๋ ฅ
+ const benefit = new Benefit(this.#date, this.#menu);
+ this.#printBenefit(benefit);
+ }
+
+ async #getOrderInformation() {
+ await this.#getDate();
+ await this.#getMenu();
+ }
+
+ async #getDate() {
+ while (true) {
+ try {
+ this.#date = await InputView.inputDate();
+ break;
+ } catch (error) {
+ print(error);
+ }
+ }
+ }
+
+ async #getMenu() {
+ while (true) {
+ try {
+ this.#menu = await InputView.inputMenu();
+ break;
+ } catch (error) {
+ print(error);
+ }
+ }
+ }
+
+ #printBenefit(benefit) {
+ OutputView.printGiveaway(benefit.benefitDetail()); // <์ฆ์ ๋ฉ๋ด>
+ OutputView.printBenefitDetail(benefit.benefitDetail()); // <ํํ ๋ด์ญ>
+ OutputView.printTotalBenefit(benefit.totalBenefit()); // <์ด ํํ
๊ธ์ก>
+ OutputView.printExpectedAmount(benefit.expectedAmount()); // <ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก>
+ OutputView.printEventBadge(benefit.eventBadge()); // <12์ ์ด๋ฒคํธ ๋ฐฐ์ง>
+ }
+}
+export default EventController; | JavaScript | Controller์ ํ๋๋ model์ ํ๋๋ฅผ ํตํด ๋ถ๋ฌ์ฌ ์ ์๋ค๊ณ ์๊ฐํฉ๋๋ค!
ํ๋๋ฅผ ์ค์ฌ๋ณด๋๊ฑด ์ด๋จ๊น์? |
@@ -0,0 +1,63 @@
+import InputView from "../view/InputView.js";
+import OutputView from "../view/OutputView.js";
+import Order from "../model/Order.js";
+import Benefit from "../model/Benefit.js";
+import { print } from "../commons/utils.js";
+import { MENU } from "../commons/constants.js";
+
+class EventController {
+ #date;
+ #menu;
+
+ async eventStart() {
+ OutputView.printStart();
+
+ // ์ฃผ๋ฌธ ์ ๋ณด ์
๋ ฅ & ์ฃผ๋ฌธ ์ ๋ณด ์ถ๋ ฅ
+ await this.#getOrderInformation();
+ OutputView.printOrderInformation(this.#date, this.#menu);
+
+ // ์ฃผ๋ฌธ ํด๋์ค ์์ฑ & ์ด ์ฃผ๋ฌธ ๊ธ์ก ์ถ๋ ฅ
+ const order = new Order(this.#date, this.#menu);
+ OutputView.printAllAmount(order.getAllAmount());
+
+ // ํํ ํด๋์ค ์์ฑ & ํํ๊ณผ ๊ด๋ จ๋ ๋ฉ์ธ์ง ์ถ๋ ฅ
+ const benefit = new Benefit(this.#date, this.#menu);
+ this.#printBenefit(benefit);
+ }
+
+ async #getOrderInformation() {
+ await this.#getDate();
+ await this.#getMenu();
+ }
+
+ async #getDate() {
+ while (true) {
+ try {
+ this.#date = await InputView.inputDate();
+ break;
+ } catch (error) {
+ print(error);
+ }
+ }
+ }
+
+ async #getMenu() {
+ while (true) {
+ try {
+ this.#menu = await InputView.inputMenu();
+ break;
+ } catch (error) {
+ print(error);
+ }
+ }
+ }
+
+ #printBenefit(benefit) {
+ OutputView.printGiveaway(benefit.benefitDetail()); // <์ฆ์ ๋ฉ๋ด>
+ OutputView.printBenefitDetail(benefit.benefitDetail()); // <ํํ ๋ด์ญ>
+ OutputView.printTotalBenefit(benefit.totalBenefit()); // <์ด ํํ
๊ธ์ก>
+ OutputView.printExpectedAmount(benefit.expectedAmount()); // <ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก>
+ OutputView.printEventBadge(benefit.eventBadge()); // <12์ ์ด๋ฒคํธ ๋ฐฐ์ง>
+ }
+}
+export default EventController; | JavaScript | ERROR์ ์ถ๋ ฅ๋ util ์ด ์๋ OutputView ์์ ํด์ฃผ๋๊ฑด ์ด๋จ๊น์? |
@@ -0,0 +1,56 @@
+import { print, priceToString } from "../commons/utils.js";
+import { MESSAGE, ARRAY, BENEFIT_AMOUNT } from "../commons/constants.js";
+
+const OutputView = {
+ printStart() {
+ print(MESSAGE.START);
+ },
+
+ printOrderInformation(date, menu) {
+ print(MESSAGE.MONTH + date + MESSAGE.SHOW_BENEFIT);
+ print(MESSAGE.MENU);
+ menu[ARRAY.MENU].forEach((menuName, index) => {
+ print(menuName + MESSAGE.BLANK + menu[ARRAY.COUNT][index] + MESSAGE.EA);
+ });
+ },
+
+ printAllAmount(amount) {
+ print(MESSAGE.TOTAL_AMOUNT);
+ print(priceToString(amount) + MESSAGE.WON);
+ },
+
+ printGiveaway(benefitResult) {
+ print(MESSAGE.GIVEAWAY);
+ if (benefitResult[ARRAY.GIVEAWAY] !== 0) print(MESSAGE.GIVEAWAY_ITEM);
+ else print(MESSAGE.NOTHING);
+ },
+
+ printBenefitDetail(benefitResult) {
+ print(MESSAGE.BENEFIT_DETAILS);
+ if (JSON.stringify(benefitResult) === "[0,0,0,0,0]") {
+ print(MESSAGE.NOTHING);
+ } else {
+ benefitResult.forEach((benefit, index) => {
+ if (benefit !== 0) print(MESSAGE.BENEFIT_DETAILS_TITLE[index] + priceToString(benefit) + MESSAGE.WON);
+ });
+ }
+ },
+
+ printTotalBenefit(totalBenefit) {
+ print(MESSAGE.TOTAL_BENEFIT);
+ if (totalBenefit > 0) print(MESSAGE.HYPEN + priceToString(totalBenefit) + MESSAGE.WON);
+ else print(priceToString(totalBenefit) + MESSAGE.WON);
+ },
+
+ printExpectedAmount(expectedAmount) {
+ print(MESSAGE.EXPECTED_AMOUNT);
+ print(priceToString(expectedAmount) + MESSAGE.WON);
+ },
+
+ printEventBadge(eventBadge) {
+ print(MESSAGE.EVENT_BADGE);
+ print(eventBadge);
+ },
+};
+
+export default OutputView; | JavaScript | else ๋ฅผ ์ง์ํ๋ผ๋ ์๊ตฌ์ฌํญ์ด ์์ด์,
์์ if๋ฌธ์ return ํด์ฃผ๋ ๋ฐฉ์์ ์ถ์ฒํฉ๋๋ค! |
@@ -2,6 +2,8 @@
import React, { useState } from "react";
+// ํ
์คํธ
+
export interface ButtonProps {
label: string;
onClick: () => void; | Unknown | ์ฝ๋๋ฅผ ์ดํด๋ณด์์ต๋๋ค. ์ฌ๊ธฐ ๋ช ๊ฐ์ง ์ฝ๋ฉํธ๋ฅผ ๋๋ฆฌ๊ฒ ์ต๋๋ค.
1. **์ฃผ์ ์ฌ์ฉ**: ์ถ๊ฐํ `// ํ
์คํธ` ์ฃผ์์ ์๋ฏธ๊ฐ ๋ถ๋ถ๋ช
ํฉ๋๋ค. ์ฃผ์์ ์ฝ๋์ ์๋๋ฅผ ๋ช
ํํ ํ๋ ๋ฐ ๋์์ด ๋์ด์ผ ํ๋ฏ๋ก, ์ ํ
์คํธ ์ฃผ์์ด ํ์ํ์ง ๊ตฌ์ฒด์ ์ผ๋ก ์ค๋ช
ํ๋ ๊ฒ์ด ์ข์ต๋๋ค. ์๋ฅผ ๋ค์ด, `// ๋ฒํผ ํ
์คํธ๋ฅผ ์ํด ์ถ๊ฐ๋ ์ฃผ์`๊ณผ ๊ฐ์ด ์์ฑํ๋ฉด ์ข์ต๋๋ค.
2. **ํ์
์ ์**: `ButtonProps` ์ธํฐํ์ด์ค๋ ์ ์ ์๋์ด ์์ต๋๋ค. ํ์ง๋ง ์ฌ์ฉ๋๋ ์ปดํฌ๋ํธ๊ฐ ์ค์ ๋ก ์๋ ๊ฒฝ์ฐ ์ด๋ฅผ ์ถ๊ฐ์ ์ผ๋ก ๋ณด์ฌ์ฃผ๋ฉด ์ฝ๋๊ฐ ๋์ฑ ์์ ํด์ง ์ ์์ต๋๋ค. ์๋ฅผ ๋ค์ด, `Button` ์ปดํฌ๋ํธ๊ฐ ์ด๋ป๊ฒ `ButtonProps`๋ฅผ ์ฌ์ฉํ๋์ง ๋ณด์ฌ์ฃผ๋ฉด ์ข์ต๋๋ค.
3. **์ฃผ์ ์์น**: ์ฝ๋์ ์๋จ์ ์ฃผ์์ ์ถ๊ฐํ๋ ๊ฒ์ ์ ์ฉํ ์ ์์ง๋ง, ๋ ๋ง์ ์ ๋ณด๊ฐ ํ์ํ ๊ฒฝ์ฐ ์ฃผ์์ด ์ ๋๋ก ์ค๋ช
๋๋ ๊ฒ์ด ์ค์ํฉ๋๋ค. ํ์ํ ๋ถ๋ถ์ ๋ํด ๋ ๊ตฌ์ฒด์ ์ผ๋ก ์ค๋ช
ํด ์ฃผ์ธ์.
์ถ๊ฐ ์ฝ๋๋ ํน์ ๊ธฐ๋ฅ์ ๋ํ ์ค๋ช
์ด ์๋ค๋ฉด ๋ ๋์ ํผ๋๋ฐฑ์ ์ ๊ณตํ ์ ์์ ๊ฒ์
๋๋ค. ํ์ํ์๋ฉด ๊ณ์ ๋ง์ํด ์ฃผ์ธ์! |
@@ -0,0 +1,88 @@
+import { createGlobalStyle } from 'styled-components'
+import reset from 'styled-reset'
+
+const MainStyles = createGlobalStyle`
+ .relative{position:relative}
+ .absolute{position:absolute}
+ .fixed{position:fixed}
+
+ .flex-center-between {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ }
+ .flex-center-center {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ }
+ .flex-center-start {
+ display: flex;
+ align-items: center;
+ justify-content: flex-start;
+ }
+ .gap-8{gap:8px}
+ .gap-9{gap:9px}
+ .gap-10{gap:10px}
+ .gap-20{gap:20px}
+ .gap-21{gap:21px}
+ .gap-22{gap:22px}
+ .gap-23{gap:23px}
+ .gap-24{gap:24px}
+ .gap-25{gap:25px}
+ .gap-26{gap:26px}
+ .gap-27{gap:27px}
+ .gap-28{gap:28px}
+ .gap-29{gap:29px}
+ .gap-30{gap:30px}
+ .gap-40{gap:40px}
+ .gap-50{gap:50px}
+ .gap-60{gap:60px}
+ .gap-70{gap:70px}
+ .gap-80{gap:80px}
+ .gap-90{gap:90px}
+ .width-100{width:100%}
+ .max-width{width:max-content}
+ .over-hidden{overflow: scroll}
+
+ .margint-tb-10{margin:10px 0}
+ .margint-tb-11{margin:11px 0}
+ .margint-tb-12{margin:12px 0}
+ .margint-tb-13{margin:13px 0}
+ .margint-tb-14{margin:14px 0}
+ .margint-tb-15{margin:15px 0}
+ .margint-tb-16{margin:16px 0}
+ .margint-tb-17{margin:17px 0}
+ .margint-tb-18{margin:18px 0}
+ .margint-tb-19{margin:19px 0}
+ .margint-tb-20{margin:10px 0}
+
+ .margin-b-10{margin-bottom:10px}
+ .margin-b-11{margin-bottom:11px}
+ .margin-b-12{margin-bottom:12px}
+ .margin-b-13{margin-bottom:13px}
+ .margin-b-14{margin-bottom:14px}
+ .margin-b-15{margin-bottom:15px}
+ .margin-b-16{margin-bottom:16px}
+ .margin-b-17{margin-bottom:17px}
+ .margin-b-18{margin-bottom:18px}
+ .margin-b-19{margin-bottom:19px}
+ .margin-b-20{margin-bottom:20px}
+
+ .padding-lr-10{padding:0 10px}
+ .padding-lr-11{padding:0 11px}
+ .padding-lr-12{padding:0 12px}
+ .padding-lr-13{padding:0 13px}
+ .padding-lr-14{padding:0 14px}
+ .padding-lr-15{padding:0 15px}
+ .padding-lr-16{padding:0 16px}
+ .padding-lr-17{padding:0 17px}
+ .padding-lr-18{padding:0 18px}
+ .padding-lr-19{padding:0 19px}
+ .padding-lr-20{padding:0 20px}
+
+ .bottom-0{bottom:0}
+
+`
+
+export default MainStyles | TypeScript | ์ด๋ ๊ฒ ์ฐ๊ณ ์ถ๋ค๋ฉด, ๊ด๋ จ `styles/mixin.ts`์ mixin ํจ์๋ฅผ ๋ง๋ค ์ ์์ ๊ฒ ๊ฐ์ต๋๋ค.
// flex๊ด๋ จ mixin
```suggestion
interface FlexMixin={
justifyContent?:'center' | 'flex-end' | 'flex-start' | 'space-evenly'
alignItems? :'center' | 'flex-end'
}
export const MixinFlex({ alignItems,justifyContent } : FlexMixin) {
return css`
display:flex;
${justifyContent && css` justify-content : ${justifyContent}`}
${alignItems && css`align-Items : ${alignItems}`}
`
}
```
์ด๋ฐ์์ผ๋ก ํ์ฅ์ฑ์๊ฒ ๊ฐ๋ฐ์ด ๊ฐ๋ฅํฉ๋๋ค!
cc. @eunbae11 |
@@ -0,0 +1,35 @@
+package db;
+
+import db.HttpSessions;
+import model.User;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import webserver.domain.Session;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class HttpSessionsTest {
+
+ @Test
+ @DisplayName("์ธ์
์ผ์น ํ
์คํธ")
+ void matchTest() {
+ User user = new User("dino", "dino", "dino", "dino.bin@kakaocorp.com");
+ String id = HttpSessions.getId();
+ Session session = new Session();
+ session.addAttribute("user", user);
+ HttpSessions.addSession(id, session);
+ assertThat(HttpSessions.getSession(id).getAttribute("user")).isEqualTo(user);
+ }
+
+ @Test
+ @DisplayName("์ธ์
๋ถ์ผ์น ํ
์คํธ")
+ void unMatchTest() {
+ User user = new User("dino", "dino", "dino", "dino.bin@kakaocorp.com");
+ String id = HttpSessions.getId();
+ Session session = new Session();
+ session.addAttribute("user", user);
+ HttpSessions.addSession(id, session);
+ String id2 = HttpSessions.getId();
+ assertThat(HttpSessions.getSession(id2)).isNotEqualTo(HttpSessions.getSession(id));
+ }
+} | Java | ํ
์คํธ๋ Session ์ถ๊ฐ์์ ๊ฐ์ด ํด์ฃผ์
จ๋ค์. ๐ |
@@ -0,0 +1,35 @@
+package db;
+
+import db.HttpSessions;
+import model.User;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import webserver.domain.Session;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class HttpSessionsTest {
+
+ @Test
+ @DisplayName("์ธ์
์ผ์น ํ
์คํธ")
+ void matchTest() {
+ User user = new User("dino", "dino", "dino", "dino.bin@kakaocorp.com");
+ String id = HttpSessions.getId();
+ Session session = new Session();
+ session.addAttribute("user", user);
+ HttpSessions.addSession(id, session);
+ assertThat(HttpSessions.getSession(id).getAttribute("user")).isEqualTo(user);
+ }
+
+ @Test
+ @DisplayName("์ธ์
๋ถ์ผ์น ํ
์คํธ")
+ void unMatchTest() {
+ User user = new User("dino", "dino", "dino", "dino.bin@kakaocorp.com");
+ String id = HttpSessions.getId();
+ Session session = new Session();
+ session.addAttribute("user", user);
+ HttpSessions.addSession(id, session);
+ String id2 = HttpSessions.getId();
+ assertThat(HttpSessions.getSession(id2)).isNotEqualTo(HttpSessions.getSession(id));
+ }
+} | Java | ๋ถ์ผ์น๊น์ง ๐ |
@@ -0,0 +1,35 @@
+package db;
+
+import db.HttpSessions;
+import model.User;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import webserver.domain.Session;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class HttpSessionsTest {
+
+ @Test
+ @DisplayName("์ธ์
์ผ์น ํ
์คํธ")
+ void matchTest() {
+ User user = new User("dino", "dino", "dino", "dino.bin@kakaocorp.com");
+ String id = HttpSessions.getId();
+ Session session = new Session();
+ session.addAttribute("user", user);
+ HttpSessions.addSession(id, session);
+ assertThat(HttpSessions.getSession(id).getAttribute("user")).isEqualTo(user);
+ }
+
+ @Test
+ @DisplayName("์ธ์
๋ถ์ผ์น ํ
์คํธ")
+ void unMatchTest() {
+ User user = new User("dino", "dino", "dino", "dino.bin@kakaocorp.com");
+ String id = HttpSessions.getId();
+ Session session = new Session();
+ session.addAttribute("user", user);
+ HttpSessions.addSession(id, session);
+ String id2 = HttpSessions.getId();
+ assertThat(HttpSessions.getSession(id2)).isNotEqualTo(HttpSessions.getSession(id));
+ }
+} | Java | ์ฌ์ฉํ์ง ์๋ import๋ ์ ๊ฑฐํ์ฃ ๐ |
@@ -16,10 +16,10 @@ public class HttpResponse {
private HttpStatusCode httpStatusCode;
private Map<String, String> headers;
- private List<Cookie> cookies;
+ private Cookies cookies;
private byte[] body;
- public HttpResponse(HttpStatusCode httpStatusCode, Map<String, String> headers, List<Cookie> cookies, byte[] body) {
+ public HttpResponse(HttpStatusCode httpStatusCode, Map<String, String> headers, Cookies cookies, byte[] body) {
this.httpStatusCode = httpStatusCode;
this.headers = headers;
this.cookies = cookies;
@@ -43,18 +43,15 @@ private String headersList() {
.append(": ")
.append(headers.get(key))
.append("\r\n"));
+ sb.append(cookies.toString());
- cookies.forEach(cookie -> sb.append(HttpHeader.SET_COOKIE)
- .append(": ")
- .append(cookie.toString())
- .append("\r\n"));
return sb.toString();
}
public static class Builder {
private HttpStatusCode httpStatusCode;
private Map<String, String> headers = new HashMap<>();
- private List<Cookie> cookies = new ArrayList<>();
+ private Cookies cookies = new Cookies();
private byte[] body;
public Builder status(HttpStatusCode httpStatusCode) {
@@ -71,13 +68,12 @@ public Builder body(String path) throws IOException, URISyntaxException {
public Builder body(String path, Map<String, Object> parameter) throws IOException {
this.body = TemplateUtils.getTemplatePage(path, parameter);
- logger.debug(new String(body));
headers.put(HttpHeader.CONTENT_LENGTH, String.valueOf(this.body.length));
return this;
}
public Builder cookie(Cookie cookie) {
- this.cookies.add(cookie);
+ this.cookies.addCookie(cookie);
return this;
}
| Java | ์ง๊ธ์ ์ ๊ฑฐํ์
จ์ง๋ง ๋๋ฒ๊น
๋ชฉ์ ์ผ๋ก System.out.println์ด ์๋๋ผ logger.debug๋ฅผ ์ฌ์ฉํด์ฃผ์
จ์๋ค์. ๐ฏ |
@@ -105,9 +105,15 @@ public String getBody() {
}
public boolean containsCookie(String cookie) {
- return this.headers
- .get(HttpHeader.COOKIE)
- .contains(cookie);
+ String requestCookie = this.headers.get(HttpHeader.COOKIE);
+ if (requestCookie != null) {
+ return requestCookie.contains(cookie);
+ }
+ return false;
+ }
+
+ public Cookies getCookies() {
+ return new Cookies(headers.get(HttpHeader.COOKIE));
}
public boolean isTemplate() { | Java | ์ฝ๊ฐ์ ๊ฐ์ธ์ ์ธ ์ ํธ์ธ๋ฐ ์ง๊ธ์ ๋ณต์กํ์ง ์์์ ์ฐจ์ด๊ฐ ํฌ์ง ์์ง๋ง ์ฌ๋์ ๋ถ์ ๋ณด๋ค๋ ๊ธ์ ์ ๋ ์์ฐ์ค๋ฝ๊ฒ ์ฝ๋ ๊ฒฝํฅ์ด ์์ด์ ๊ฐ๋ฅํ๋ค๋ฉด ๊ธ์ ์ ์กฐ๊ฑด์ ์ ํํ๋ ํธ์
๋๋ค.
```java
if (StringUtils.hasText(requestCookie)) {
return requestCookie.contains(cookie);
}
return false;
```
๋น ๋ฌธ์์ด์ผ ๋๋ ์ด๋ป๊ฒ ํด์ผํ ์ง๋ ์ด์ง ๊ณ ๋ฏผ๋๋ค์. |
@@ -0,0 +1,31 @@
+package db;
+
+import webserver.domain.Session;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+
+public class HttpSessions {
+ private static final Map<String, Session> sessions = new HashMap<>();
+
+ public static String getId() {
+ return UUID.randomUUID().toString();
+ }
+
+ public static void addSession(String name, Session session) {
+ sessions.put(name, session);
+ }
+
+ public static Session getSession(String name) {
+ return sessions.get(name);
+ }
+
+ public static void removeSession(String name) {
+ sessions.remove(name);
+ }
+
+ public static void invalidate() {
+ sessions.clear();
+ }
+} | Java | ์ ํ๋ฆฌ์ผ์ด์
๊ณตํต์ ์ผ๋ก ์ฌ์ฉ๋ ์ ์๊ฒ DB๋ก ์ฌ์ฉํด ์ฃผ์
จ๋ค์ ๐ |
@@ -0,0 +1,31 @@
+package db;
+
+import webserver.domain.Session;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+
+public class HttpSessions {
+ private static final Map<String, Session> sessions = new HashMap<>();
+
+ public static String getId() {
+ return UUID.randomUUID().toString();
+ }
+
+ public static void addSession(String name, Session session) {
+ sessions.put(name, session);
+ }
+
+ public static Session getSession(String name) {
+ return sessions.get(name);
+ }
+
+ public static void removeSession(String name) {
+ sessions.remove(name);
+ }
+
+ public static void invalidate() {
+ sessions.clear();
+ }
+} | Java | ํค ์์ฑ์ ์ด๋ป๊ฒ ํ ๊น ๊ณ ๋ฏผํ๋ค๊ฐ DB๊ฐ ํค์์ฑ์ ํ๋๊ฑธ ๊ณ ๋ คํ์ฌ ์ฌ๊ธฐ ๋ฃ์ด ์ฃผ์ ๊ฒ ๊ฐ๋ค์.
DB์์ ๋ณดํต ์ด์ ๊ฐ์ ๋์๋ก ํค๋ฅผ ๋ง๋ค์ง๋ ์๊ณ , HttpSessions๊ฐ ์๋ ๋ค๋ฅธ DB, ์๋ฅผ ๋ค๋ฉด Redis๋ฅผ ์ฌ์ฉํ๋ฉด ๋จ์ํ DB๋ฅผ ๋ฐ๊พธ๋ ๊ฑธ๋ก ์์
์ด ๋๋์ง ์๊ณ ๋์ ์์ฑ์ ๋ํ ๊ณ ๋ฏผ์ ํ์
์ผ ํ ํ
๋ฐ ์ด์ ๋ํ ์ญํ ์ DB๊ฐ ์๋ ๊ณณ์ผ๋ก ๋๊ฒจ๋ณด์ฃ .
์ด๊ฑด ์๋ Request๊ด๋ จ ๋ด์ฉ์ ๋จ๊ธธ๊ฒ์! |
@@ -1,24 +1,43 @@
package webserver.controller;
import db.DataBase;
+import db.HttpSessions;
import model.User;
+import org.checkerframework.checker.units.qual.C;
import webserver.domain.*;
+import java.util.UUID;
+
public class LoginController extends AbstractController {
@Override
public HttpResponse doPost(HttpRequest httpRequest) throws Exception {
User findUser = DataBase.findUserById(httpRequest.getParameter("userId"));
- if (findUser == null || !findUser.isValidPassword(httpRequest.getParameter("password"))) {
+ if (wrongUser(httpRequest, findUser)) {
+ Cookie cookie = new Cookie("logined=false");
+ cookie.setPath("/");
return new HttpResponse.Builder()
.status(HttpStatusCode.FOUND)
.redirect("/user/login_failed.html")
- .cookie(new Cookie("logined", "false", "Path", "/"))
+ .cookie(cookie)
.build();
}
+ Cookie cookie = new Cookie("logined=true");
+ cookie.setPath("/");
+ Session session = new Session();
+ session.addAttribute("user", findUser);
+ String uuid = HttpSessions.getId();
+ HttpSessions.addSession(uuid, session);
+ Cookie sessionCookie = new Cookie("Session=" + uuid);
+ sessionCookie.setPath("/");
return new HttpResponse.Builder()
.status(HttpStatusCode.FOUND)
.redirect("/index.html")
- .cookie(new Cookie("logined", "true", "Path", "/"))
+ .cookie(cookie)
+ .cookie(sessionCookie)
.build();
}
+
+ private boolean wrongUser(HttpRequest httpRequest, User findUser) {
+ return findUser == null || !findUser.isValidPassword(httpRequest.getParameter("password"));
+ }
} | Java | Session์ ๋ํ ์ถ๊ฐ๋ก ์๋นํ ๋ณต์กํด์ก๋ค์.
Controller์ ๋๋ถ๋ถ์ ์ฝ๋๊ฐ Http์ ๋ํ ์์
์ธ๋ฐ Session๋ ๊ฒฐ๊ตญ Http์ ์คํ์ธ๊ฑธ ๊ณ ๋ คํด์ Request, Response๋ฅผ ํตํด ๊ด๋ฆฌํ ์ ์์ง ์์๊น์? (์์ ๋ง์๋๋ฆฐ session id์ ์ถ๊ฐ ๋ํ ๋ง์ด์ฃ .)
๊ทธ๋ฌ๋ฉด Controller๋ Session์ ๊ฐ์ ธ์ค๊ณ , ์ถ๊ฐ ์์ฒญ๋ง ํ๋ ๋ฐฉ๋ฒ์ผ๋ก ์ฌ์ฉํ๊ธฐ๋ง ํ ์ ์์ ๊ฒ ๊ฐ์์. |
@@ -1,21 +1,27 @@
package webserver.domain;
+
+import java.util.Objects;
+
public class Cookie {
+ public static final String PATH = "Path";
private String name;
private String value;
- private String pathName;
- private String pathValue;
+ private String path;
public Cookie(String name, String value) {
this.name = name;
this.value = value;
}
- public Cookie(String name, String value, String pathName, String pathValue) {
- this.name = name;
- this.value = value;
- this.pathName = pathName;
- this.pathValue = pathValue;
+ public Cookie(String cookieString) {
+ String[] splitData = cookieString.split("=");
+ this.name = splitData[0];
+ this.value = splitData[1];
+ }
+
+ public void setPath(String path) {
+ this.path = path;
}
public String getName() {
@@ -26,16 +32,33 @@ public String getValue() {
return value;
}
- public String getPathName() {
- return pathName;
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Cookie cookie = (Cookie) o;
+ return Objects.equals(name, cookie.name) && Objects.equals(value, cookie.value);
}
- public String getPathValue() {
- return pathValue;
+ @Override
+ public int hashCode() {
+ return Objects.hash(name, value);
}
@Override
public String toString() {
- return name + "=" + value + "; " + pathName + "=" + pathValue;
+ StringBuilder sb = new StringBuilder();
+ sb.append(HttpHeader.SET_COOKIE)
+ .append(": ")
+ .append(name)
+ .append("=")
+ .append(value)
+ .append("; ");
+ if (path != null) {
+ sb.append(PATH)
+ .append("=")
+ .append(path);
+ }
+ return sb.toString();
}
} | Java | `cookieString` ํ์
์ ๋ณ์๋ช
์ ์จ์ค ํ์๋ ์์ต๋๋ค! |
@@ -0,0 +1,42 @@
+package webserver.domain;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.util.StringUtils;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+
+public class Cookies {
+ private static final Logger logger = LoggerFactory.getLogger(Cookies.class);
+
+ private Map<String, Cookie> cookies;
+
+ public Cookies() {
+ cookies = new HashMap<>();
+ }
+
+ public Cookies(String cookiesString) {
+ cookies = new HashMap<>();
+ Arrays.stream(cookiesString.trim().split(";")).forEach(str -> {
+ String[] keyValue = str.split("=");
+ cookies.put(keyValue[0].trim(), new Cookie(keyValue[0].trim(), keyValue[1].trim()));
+ });
+ }
+
+ public Cookie getCookie(String name) {
+ return cookies.get(name);
+ }
+
+ public void addCookie(Cookie cookie) {
+ cookies.put(cookie.getName(), cookie);
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ cookies.forEach((key, value) -> sb.append(cookies.get(key)).append("\r\n"));
+ return sb.toString();
+ }
+} | Java | [Java8 Stream์ loop๊ฐ ์๋๋ค.](https://www.popit.kr/java8-stream%EC%9D%80-loop%EA%B0%80-%EC%95%84%EB%8B%88%EB%8B%A4/)
```java
for (String str : cookiesString.trim().split(";")) {
String[] keyValue = str.split("=");
cookies.put(keyValue[0].trim(), new Cookie(keyValue[0].trim(), keyValue[1].trim()));
}
```
๋ฐ๋ณต๋ฌธ๋ ํฐ ์ฐจ์ด๊ฐ ์๊ธดํ์ง๋ง stream.forEach๋ง ํ ๊ฑฐ๋ผ๋ฉด ๋ง๊ทธ๋๋ก ๋ฐ๋ณต๋ฌธ๊ณผ ํฌ๊ฒ ๋ค๋ฅผ๊ฒ ์๋ต๋๋ค.
๊ทธ๋ ๋ค๋ฉด ์ผ๋ฐ์ ์ผ๋ก ๋ ์น์ํ ๋ฐ๋ณต๋ฌธ์ด ๋ ์ข๋ค๊ณ ์๊ฐ๋ค์ด์.
๊ฐ์ธ์ ์ผ๋ก๋ ํน์ ์ฐ์ฐ์ ์ฐ๊ฒฐํด์ ์ฌ์ฉํ ํ์๊ฐ ์๊ฑฐ๋, ๊ฐ๋
์ฑ ์ธก๋ฉด์์ ์ด์ ์ด ์์ ๋ ์์ฃผ๋ก ์คํธ๋ฆผ์ ์ฌ์ฉํฉ๋๋ค. |
@@ -0,0 +1,29 @@
+package webserver.domain;
+
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class Session {
+ private Map<String, Object> attribute;
+
+ public Session() {
+ this.attribute = new HashMap<>();
+ }
+
+ public Object getAttribute(String name) {
+ return attribute.get(name);
+ }
+
+ public void addAttribute(String name, Object value) {
+ attribute.put(name, value);
+ }
+
+ public void removeAttribute(String name) {
+ attribute.remove(name);
+ }
+
+ public void invalidate() {
+ attribute.clear();
+ }
+} | Java | ๊ตฐ๋๋๊ธฐ ์์ด ์ ๊ตฌํํ๋ค์. ๐ |
@@ -0,0 +1,48 @@
+import { SERVER } from '@/constants/url';
+import axios from 'axios';
+
+interface CreateReviewParams {
+ userId: string;
+ travelId: string;
+ reviewImgs: File[];
+ travelScore: number;
+ content: string;
+ title: string;
+ guideScore?: number;
+}
+
+export const createReview = async ({
+ userId,
+ travelId,
+ reviewImgs,
+ travelScore,
+ content,
+ title,
+ guideScore,
+}: CreateReviewParams) => {
+ try {
+ const formData = new FormData();
+ formData.append('userId', userId);
+ formData.append('travelId', travelId);
+ formData.append('travelScore', travelScore.toString());
+ formData.append('content', content);
+ formData.append('title', title);
+ if (guideScore !== undefined && guideScore !== null && guideScore !== 0) {
+ formData.append('guideScore', guideScore.toString());
+ }
+
+ reviewImgs.forEach((img) => {
+ formData.append('reviewImg', img);
+ });
+
+ const response = await axios.post(`${SERVER}/api/v1/reviews`, formData, {
+ headers: {
+ 'Content-Type': 'multipart/form-data',
+ },
+ });
+
+ return response.data;
+ } catch (err) {
+ throw new Error(err instanceof Error ? err.message : '๋ฆฌ๋ทฐ ์์ฑ ์คํจ');
+ }
+}; | TypeScript | _:warning: Potential issue_
**ํผ ๋ฐ์ดํฐ ๊ตฌ์ฑ ์ 0์ ์ฒ๋ฆฌ ์ฃผ์**
`guideScore`๊ฐ 0์ ์ด๋ฉด `if (guideScore)` ์กฐ๊ฑด์์๋ ๋๋ฝ๋ฉ๋๋ค. ์ ์ ๊ฐ ์๋์ ์ผ๋ก 0์ ์ ์
๋ ฅํ ๊ฐ๋ฅ์ฑ์ด ์๋ค๋ฉด, ์กฐ๊ฑด๋ฌธ์ `guideScore !== undefined` ๋ฑ์ ๋ฐฉ์์ผ๋ก ์์ ํด๋ณด์ธ์.
```diff
- if (guideScore) {
+ if (guideScore !== undefined && guideScore !== null) {
formData.append('guideScore', guideScore.toString());
- }
+ }
```
<!-- suggestion_start -->
<details>
<summary>๐ Committable suggestion</summary>
> โผ๏ธ **IMPORTANT**
> Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
`````suggestion
const formData = new FormData();
formData.append('userId', userId);
formData.append('travelId', travelId);
formData.append('travelScore', travelScore.toString());
formData.append('content', content);
formData.append('title', title);
if (guideScore !== undefined && guideScore !== null) {
formData.append('guideScore', guideScore.toString());
}
`````
</details>
<!-- suggestion_end -->
<!-- This is an auto-generated comment by CodeRabbit --> |
@@ -11,6 +11,10 @@ import GuideProfile from '@/components/GuideProfile';
import StarRating from '@/components/StarRating';
import FileUploadBtn from '@/components/FileUploadBtn';
+import useCreateReview from '@/hooks/query/useCreateReview';
+import { ShowToast } from '@/components/Toast';
+import { REVIEW_CONSTANTS } from '@/constants/reviewConstant';
+
export interface ReviewWriteModalProps {
reviewTitle: string;
userName: string;
@@ -22,6 +26,8 @@ export interface ReviewWriteModalProps {
userRating: number; // ์ถ๊ฐ
};
travelThumbnail?: string;
+ travelId: string;
+ userId: string;
}
const isValidFile = (file: File) => {
@@ -33,12 +39,15 @@ const ReviewWriteModal = ({
reviewTitle,
guideInfo,
travelThumbnail: imgURL,
+ travelId,
+ userId,
}: ReviewWriteModalProps) => {
const [open, setOpen] = useState(false);
- const [travelRating, setTravelRating] = useState(0);
- const [userRating, setUserRating] = useState(0);
+ const [travelRating, setTravelRating] = useState<number>(0);
+ const [userRating, setUserRating] = useState<number>(0);
const [files, setFiles] = useState<File[]>([]);
-
+ const [reviewContent, setReviewContent] = useState('');
+ const { mutate, isPending: isLoading } = useCreateReview();
const handleFileUpload = (event: ChangeEvent<HTMLInputElement>) => {
if (event.target.files) {
if (!isValidFile(event.target.files[0])) {
@@ -58,17 +67,60 @@ const ReviewWriteModal = ({
setOpen(false);
};
+ const resetForm = () => {
+ setFiles([]);
+ setTravelRating(0);
+ setUserRating(0);
+ setReviewContent('');
+ };
+
const onSubmitReview = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
- setFiles([]);
- setOpen(false);
+
+ if (reviewContent.trim().length === 0) {
+ ShowToast('๋ฆฌ๋ทฐ ๋ด์ฉ์ ์
๋ ฅํด์ฃผ์ธ์.', 'failed');
+ return;
+ }
+
+ if (reviewContent.length > REVIEW_CONSTANTS.MAX_CONTENT_LENGTH) {
+ ShowToast(
+ `๋ฆฌ๋ทฐ ๋ด์ฉ์ ${REVIEW_CONSTANTS.MAX_CONTENT_LENGTH}๊ธ์๋ฅผ ์ด๊ณผํ ์ ์์ต๋๋ค..`,
+ 'failed',
+ );
+ return;
+ }
+
+ if (travelRating < 1 || travelRating > 5) {
+ ShowToast('์ฌํ ํ์ ์ 1-5์ ์ฌ์ด์ฌ์ผ ํฉ๋๋ค.', 'failed');
+ return;
+ }
+
+ if (!travelRating || travelRating === 0) {
+ ShowToast('์ฌํ ํ์ ์ ์
๋ ฅํด์ฃผ์ธ์.', 'failed');
+ return;
+ }
+ mutate(
+ {
+ userId,
+ travelId,
+ reviewImgs: files,
+ travelScore: travelRating,
+ content: reviewContent,
+ title: reviewTitle,
+ ...(userRating > 0 && { guideScore: userRating }),
+ },
+ {
+ onSuccess: () => {
+ setOpen(false);
+ resetForm();
+ },
+ },
+ );
};
useEffect(() => {
if (!open) {
- setFiles([]);
- setTravelRating(0);
- setUserRating(0);
+ resetForm();
}
}, [open]);
@@ -106,7 +158,11 @@ const ReviewWriteModal = ({
<form onSubmit={(e) => onSubmitReview(e)}>
<div css={textAreaContainer}>
- <textarea placeholder="๋ฆฌ๋ทฐ๋ฅผ ์์ฑํด์ฃผ์ธ์" />
+ <textarea
+ placeholder="๋ฆฌ๋ทฐ๋ฅผ ์์ฑํด์ฃผ์ธ์"
+ value={reviewContent}
+ onChange={(e) => setReviewContent(e.target.value)}
+ />
</div>
<FileUploadBtn
@@ -140,13 +196,19 @@ const ReviewWriteModal = ({
</div>
<div css={buttonContainer}>
<FiledBtn
- children="์์ฑ"
color={theme.colors.primary}
customStyle={css`
width: 120px;
+ ${isLoading
+ ? `cursor: not-allowed;
+ opacity: 0.5;
+ `
+ : ``}
`}
type="submit"
- />
+ >
+ {isLoading ? '๋ฑ๋ก ์ค...' : '์์ฑ'}
+ </FiledBtn>
<BorderBtn
children="๋ซ๊ธฐ"
color="#b8bbbe" | Unknown | _:warning: Potential issue_
**์ ์ถ ๋ฒํผ ๋ก๋ฉ ์ํ ๊ตฌํ ์์ ํ์**
ํ์ฌ ๊ตฌํ์ ๋ฌธ๋ฒ์ ์ค๋ฅ๊ฐ ์์ต๋๋ค. ํ
ํ๋ฆฟ ๋ฆฌํฐ๋ด๊ณผ ์กฐ๊ฑด๋ถ ๋ ๋๋ง์ด ์๋ชป ์ฌ์ฉ๋์์ต๋๋ค.
```diff
- ${isLoading &&
- `cursor: not-allowed;
- opacity: 0.5;
- `}
+ ${isLoading ? `
+ cursor: not-allowed;
+ opacity: 0.5;
+ ` : ''}
`}
type="submit"
>
- isLoading ? '๋ฑ๋ก ์ค...' : '์์ฑ'
+ {isLoading ? '๋ฑ๋ก ์ค...' : '์์ฑ'}
</FiledBtn>
```
<!-- suggestion_start -->
<details>
<summary>๐ Committable suggestion</summary>
> โผ๏ธ **IMPORTANT**
> Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
`````suggestion
${isLoading ? `
cursor: not-allowed;
opacity: 0.5;
` : ''}
`}
type="submit"
>
{isLoading ? '๋ฑ๋ก ์ค...' : '์์ฑ'}
</FiledBtn>
`````
</details>
<!-- suggestion_end -->
<!-- This is an auto-generated comment by CodeRabbit --> |
@@ -11,6 +11,10 @@ import GuideProfile from '@/components/GuideProfile';
import StarRating from '@/components/StarRating';
import FileUploadBtn from '@/components/FileUploadBtn';
+import useCreateReview from '@/hooks/query/useCreateReview';
+import { ShowToast } from '@/components/Toast';
+import { REVIEW_CONSTANTS } from '@/constants/reviewConstant';
+
export interface ReviewWriteModalProps {
reviewTitle: string;
userName: string;
@@ -22,6 +26,8 @@ export interface ReviewWriteModalProps {
userRating: number; // ์ถ๊ฐ
};
travelThumbnail?: string;
+ travelId: string;
+ userId: string;
}
const isValidFile = (file: File) => {
@@ -33,12 +39,15 @@ const ReviewWriteModal = ({
reviewTitle,
guideInfo,
travelThumbnail: imgURL,
+ travelId,
+ userId,
}: ReviewWriteModalProps) => {
const [open, setOpen] = useState(false);
- const [travelRating, setTravelRating] = useState(0);
- const [userRating, setUserRating] = useState(0);
+ const [travelRating, setTravelRating] = useState<number>(0);
+ const [userRating, setUserRating] = useState<number>(0);
const [files, setFiles] = useState<File[]>([]);
-
+ const [reviewContent, setReviewContent] = useState('');
+ const { mutate, isPending: isLoading } = useCreateReview();
const handleFileUpload = (event: ChangeEvent<HTMLInputElement>) => {
if (event.target.files) {
if (!isValidFile(event.target.files[0])) {
@@ -58,17 +67,60 @@ const ReviewWriteModal = ({
setOpen(false);
};
+ const resetForm = () => {
+ setFiles([]);
+ setTravelRating(0);
+ setUserRating(0);
+ setReviewContent('');
+ };
+
const onSubmitReview = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
- setFiles([]);
- setOpen(false);
+
+ if (reviewContent.trim().length === 0) {
+ ShowToast('๋ฆฌ๋ทฐ ๋ด์ฉ์ ์
๋ ฅํด์ฃผ์ธ์.', 'failed');
+ return;
+ }
+
+ if (reviewContent.length > REVIEW_CONSTANTS.MAX_CONTENT_LENGTH) {
+ ShowToast(
+ `๋ฆฌ๋ทฐ ๋ด์ฉ์ ${REVIEW_CONSTANTS.MAX_CONTENT_LENGTH}๊ธ์๋ฅผ ์ด๊ณผํ ์ ์์ต๋๋ค..`,
+ 'failed',
+ );
+ return;
+ }
+
+ if (travelRating < 1 || travelRating > 5) {
+ ShowToast('์ฌํ ํ์ ์ 1-5์ ์ฌ์ด์ฌ์ผ ํฉ๋๋ค.', 'failed');
+ return;
+ }
+
+ if (!travelRating || travelRating === 0) {
+ ShowToast('์ฌํ ํ์ ์ ์
๋ ฅํด์ฃผ์ธ์.', 'failed');
+ return;
+ }
+ mutate(
+ {
+ userId,
+ travelId,
+ reviewImgs: files,
+ travelScore: travelRating,
+ content: reviewContent,
+ title: reviewTitle,
+ ...(userRating > 0 && { guideScore: userRating }),
+ },
+ {
+ onSuccess: () => {
+ setOpen(false);
+ resetForm();
+ },
+ },
+ );
};
useEffect(() => {
if (!open) {
- setFiles([]);
- setTravelRating(0);
- setUserRating(0);
+ resetForm();
}
}, [open]);
@@ -106,7 +158,11 @@ const ReviewWriteModal = ({
<form onSubmit={(e) => onSubmitReview(e)}>
<div css={textAreaContainer}>
- <textarea placeholder="๋ฆฌ๋ทฐ๋ฅผ ์์ฑํด์ฃผ์ธ์" />
+ <textarea
+ placeholder="๋ฆฌ๋ทฐ๋ฅผ ์์ฑํด์ฃผ์ธ์"
+ value={reviewContent}
+ onChange={(e) => setReviewContent(e.target.value)}
+ />
</div>
<FileUploadBtn
@@ -140,13 +196,19 @@ const ReviewWriteModal = ({
</div>
<div css={buttonContainer}>
<FiledBtn
- children="์์ฑ"
color={theme.colors.primary}
customStyle={css`
width: 120px;
+ ${isLoading
+ ? `cursor: not-allowed;
+ opacity: 0.5;
+ `
+ : ``}
`}
type="submit"
- />
+ >
+ {isLoading ? '๋ฑ๋ก ์ค...' : '์์ฑ'}
+ </FiledBtn>
<BorderBtn
children="๋ซ๊ธฐ"
color="#b8bbbe" | Unknown | _:hammer_and_wrench: Refactor suggestion_
**๋ฎคํ
์ด์
์๋ฌ ์ฒ๋ฆฌ ์ถ๊ฐ ํ์**
์ฑ๊ณต ์ ์ฒ๋ฆฌ๋ ์ ๋์ด์์ง๋ง, ์คํจ ์ ์ฒ๋ฆฌ๊ฐ ๋๋ฝ๋์ด ์์ต๋๋ค.
```diff
mutate(
{
userId,
travelId,
reviewImgs: files,
travelScore: travelRating,
content: reviewContent,
title: reviewTitle,
...(userRating > 0 && { guideScore: userRating }),
},
{
onSuccess: () => {
setOpen(false);
resetForm();
+ ShowToast('๋ฆฌ๋ทฐ๊ฐ ์ฑ๊ณต์ ์ผ๋ก ๋ฑ๋ก๋์์ต๋๋ค.', 'success');
},
+ onError: (error) => {
+ ShowToast(
+ error instanceof Error ? error.message : '๋ฆฌ๋ทฐ ๋ฑ๋ก์ ์คํจํ์ต๋๋ค.',
+ 'failed'
+ );
+ },
},
);
```
<!-- suggestion_start -->
<details>
<summary>๐ Committable suggestion</summary>
> โผ๏ธ **IMPORTANT**
> Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
`````suggestion
mutate(
{
userId,
travelId,
reviewImgs: files,
travelScore: travelRating,
content: reviewContent,
title: reviewTitle,
...(userRating > 0 && { guideScore: userRating }),
},
{
onSuccess: () => {
setOpen(false);
resetForm();
ShowToast('๋ฆฌ๋ทฐ๊ฐ ์ฑ๊ณต์ ์ผ๋ก ๋ฑ๋ก๋์์ต๋๋ค.', 'success');
},
onError: (error) => {
ShowToast(
error instanceof Error ? error.message : '๋ฆฌ๋ทฐ ๋ฑ๋ก์ ์คํจํ์ต๋๋ค.',
'failed'
);
},
},
);
`````
</details>
<!-- suggestion_end -->
<!-- This is an auto-generated comment by CodeRabbit --> |
@@ -11,6 +11,10 @@ import GuideProfile from '@/components/GuideProfile';
import StarRating from '@/components/StarRating';
import FileUploadBtn from '@/components/FileUploadBtn';
+import useCreateReview from '@/hooks/query/useCreateReview';
+import { ShowToast } from '@/components/Toast';
+import { REVIEW_CONSTANTS } from '@/constants/reviewConstant';
+
export interface ReviewWriteModalProps {
reviewTitle: string;
userName: string;
@@ -22,6 +26,8 @@ export interface ReviewWriteModalProps {
userRating: number; // ์ถ๊ฐ
};
travelThumbnail?: string;
+ travelId: string;
+ userId: string;
}
const isValidFile = (file: File) => {
@@ -33,12 +39,15 @@ const ReviewWriteModal = ({
reviewTitle,
guideInfo,
travelThumbnail: imgURL,
+ travelId,
+ userId,
}: ReviewWriteModalProps) => {
const [open, setOpen] = useState(false);
- const [travelRating, setTravelRating] = useState(0);
- const [userRating, setUserRating] = useState(0);
+ const [travelRating, setTravelRating] = useState<number>(0);
+ const [userRating, setUserRating] = useState<number>(0);
const [files, setFiles] = useState<File[]>([]);
-
+ const [reviewContent, setReviewContent] = useState('');
+ const { mutate, isPending: isLoading } = useCreateReview();
const handleFileUpload = (event: ChangeEvent<HTMLInputElement>) => {
if (event.target.files) {
if (!isValidFile(event.target.files[0])) {
@@ -58,17 +67,60 @@ const ReviewWriteModal = ({
setOpen(false);
};
+ const resetForm = () => {
+ setFiles([]);
+ setTravelRating(0);
+ setUserRating(0);
+ setReviewContent('');
+ };
+
const onSubmitReview = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
- setFiles([]);
- setOpen(false);
+
+ if (reviewContent.trim().length === 0) {
+ ShowToast('๋ฆฌ๋ทฐ ๋ด์ฉ์ ์
๋ ฅํด์ฃผ์ธ์.', 'failed');
+ return;
+ }
+
+ if (reviewContent.length > REVIEW_CONSTANTS.MAX_CONTENT_LENGTH) {
+ ShowToast(
+ `๋ฆฌ๋ทฐ ๋ด์ฉ์ ${REVIEW_CONSTANTS.MAX_CONTENT_LENGTH}๊ธ์๋ฅผ ์ด๊ณผํ ์ ์์ต๋๋ค..`,
+ 'failed',
+ );
+ return;
+ }
+
+ if (travelRating < 1 || travelRating > 5) {
+ ShowToast('์ฌํ ํ์ ์ 1-5์ ์ฌ์ด์ฌ์ผ ํฉ๋๋ค.', 'failed');
+ return;
+ }
+
+ if (!travelRating || travelRating === 0) {
+ ShowToast('์ฌํ ํ์ ์ ์
๋ ฅํด์ฃผ์ธ์.', 'failed');
+ return;
+ }
+ mutate(
+ {
+ userId,
+ travelId,
+ reviewImgs: files,
+ travelScore: travelRating,
+ content: reviewContent,
+ title: reviewTitle,
+ ...(userRating > 0 && { guideScore: userRating }),
+ },
+ {
+ onSuccess: () => {
+ setOpen(false);
+ resetForm();
+ },
+ },
+ );
};
useEffect(() => {
if (!open) {
- setFiles([]);
- setTravelRating(0);
- setUserRating(0);
+ resetForm();
}
}, [open]);
@@ -106,7 +158,11 @@ const ReviewWriteModal = ({
<form onSubmit={(e) => onSubmitReview(e)}>
<div css={textAreaContainer}>
- <textarea placeholder="๋ฆฌ๋ทฐ๋ฅผ ์์ฑํด์ฃผ์ธ์" />
+ <textarea
+ placeholder="๋ฆฌ๋ทฐ๋ฅผ ์์ฑํด์ฃผ์ธ์"
+ value={reviewContent}
+ onChange={(e) => setReviewContent(e.target.value)}
+ />
</div>
<FileUploadBtn
@@ -140,13 +196,19 @@ const ReviewWriteModal = ({
</div>
<div css={buttonContainer}>
<FiledBtn
- children="์์ฑ"
color={theme.colors.primary}
customStyle={css`
width: 120px;
+ ${isLoading
+ ? `cursor: not-allowed;
+ opacity: 0.5;
+ `
+ : ``}
`}
type="submit"
- />
+ >
+ {isLoading ? '๋ฑ๋ก ์ค...' : '์์ฑ'}
+ </FiledBtn>
<BorderBtn
children="๋ซ๊ธฐ"
color="#b8bbbe" | Unknown | _:hammer_and_wrench: Refactor suggestion_
**ํผ ์ ํจ์ฑ ๊ฒ์ฌ ๋ณด์ ํ์**
ํ์ฌ๋ ๊ธฐ๋ณธ์ ์ธ ๊ฒ์ฌ๋ง ์ํํ๊ณ ์์ต๋๋ค. ์ถ๊ฐ์ ์ธ ์ ํจ์ฑ ๊ฒ์ฌ๊ฐ ํ์ํฉ๋๋ค.
```diff
+ const MAX_CONTENT_LENGTH = 1000;
+
+ if (reviewContent.length > MAX_CONTENT_LENGTH) {
+ ShowToast(`๋ฆฌ๋ทฐ ๋ด์ฉ์ ${MAX_CONTENT_LENGTH}์๋ฅผ ์ด๊ณผํ ์ ์์ต๋๋ค.`, 'failed');
+ return;
+ }
+
if (reviewContent.trim().length === 0) {
ShowToast('๋ฆฌ๋ทฐ ๋ด์ฉ์ ์
๋ ฅํด์ฃผ์ธ์.', 'failed');
return;
}
+ if (travelRating < 1 || travelRating > 5) {
+ ShowToast('์ฌํ ํ์ ์ 1-5์ ์ฌ์ด์ฌ์ผ ํฉ๋๋ค.', 'failed');
+ return;
+ }
+
if (!travelRating || travelRating === 0) {
ShowToast('์ฌํ ํ์ ์ ์
๋ ฅํด์ฃผ์ธ์.', 'failed');
return;
}
```
<!-- suggestion_start -->
<details>
<summary>๐ Committable suggestion</summary>
> โผ๏ธ **IMPORTANT**
> Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
`````suggestion
const MAX_CONTENT_LENGTH = 1000;
if (reviewContent.length > MAX_CONTENT_LENGTH) {
ShowToast(`๋ฆฌ๋ทฐ ๋ด์ฉ์ ${MAX_CONTENT_LENGTH}์๋ฅผ ์ด๊ณผํ ์ ์์ต๋๋ค.`, 'failed');
return;
}
if (reviewContent.trim().length === 0) {
ShowToast('๋ฆฌ๋ทฐ ๋ด์ฉ์ ์
๋ ฅํด์ฃผ์ธ์.', 'failed');
return;
}
if (travelRating < 1 || travelRating > 5) {
ShowToast('์ฌํ ํ์ ์ 1-5์ ์ฌ์ด์ฌ์ผ ํฉ๋๋ค.', 'failed');
return;
}
if (!travelRating || travelRating === 0) {
ShowToast('์ฌํ ํ์ ์ ์
๋ ฅํด์ฃผ์ธ์.', 'failed');
return;
}
`````
</details>
<!-- suggestion_end -->
<!-- This is an auto-generated comment by CodeRabbit --> |
@@ -1,11 +1,11 @@
import DeleteIcon from '@/components/DeleteIcon';
import { textEllipsis } from '@/styles/GlobalStyles';
import { Review } from '@/types/reviewType';
-import { dateToString } from '@/utils/dataToString';
import { css } from '@emotion/react';
import Rating from '@/components/Rating';
import Profile from '../Profile';
+import { formatDate } from '@/utils/format';
interface ReviewCardProps {
review: Review;
@@ -24,41 +24,51 @@ const ReviewCard = ({
showDate,
showDelete,
}: ReviewCardProps) => {
+ // console.log(review.imgSrc.map((src, index) => src);
return (
<div css={reviewStyle}>
<div className="titleStyle">
<div className="titleText">
{showUser && review.user && (
<div css={userProfileStyles}>
<div className="profile-container">
- {review.imgSrc && <Profile url={review.imgSrc} size="40px" />}
+ <Profile url={review.user.userProfileImage} size="30px" />
<div className="user-info">
<div className="name-rating">
<div className="name">{review.user.socialName}</div>
</div>
<p className="createAt">
- {review?.createdAt instanceof Date ? dateToString(review.createdAt) : ''}
+ {review?.createdAt ? formatDate(review.createdAt) : ''}
</p>
</div>
</div>
</div>
)}
{showTitle && review?.title && <h2>{review.title}</h2>}
{showDate && (
- <p className="createAt">
- {review?.createdAt instanceof Date ? dateToString(review.createdAt) : ''}
- </p>
+ <p className="createAt">{review?.createdAt ? formatDate(review.createdAt) : ''}</p>
)}
<div className="ratingContainer">
<Rating rating={Number(review.rating)} />
</div>
</div>
{showDelete && <DeleteIcon onDelete={onDelete || (() => {})} />}
</div>
- <div className="imgContainer">
- <img src={review.imgSrc} alt="review" />
+ <div
+ css={css`
+ display: flex;
+ gap: 10px;
+ `}
+ >
+ {Array.isArray(review.imgSrc) &&
+ review.imgSrc.length > 0 &&
+ review.imgSrc.map((src, index) => (
+ <div key={index + src} className="imgContainer">
+ <img src={src} alt="๋ฆฌ๋ทฐ ์ด๋ฏธ์ง" />
+ </div>
+ ))}
</div>
- <p css={textEllipsis(3)}>{review.content}</p>
+ <p css={textEllipsis(4)}>{review.content}</p>
</div>
);
};
@@ -98,6 +108,7 @@ const userProfileStyles = css`
const reviewStyle = css`
border-radius: 10px;
width: 100%;
+ min-width: 530px;
background-color: #f8f8f8;
padding: 10px 15px 15px 15px;
margin-bottom: 20px;
@@ -129,12 +140,13 @@ const reviewStyle = css`
border-radius: 5px;
overflow: hidden;
}
+
img {
width: 100%;
}
.ratingContainer {
- transform: translateY(-0.8px);
+ transform: translateY(-0.36vh);
}
.createAt { | Unknown | _:hammer_and_wrench: Refactor suggestion_
**๋ชจ๋ฐ์ผ ํ๊ฒฝ์ ๊ณ ๋ คํ ๋ฐ์ํ ๋์์ธ์ด ํ์ํฉ๋๋ค.**
`min-width: 530px`๋ ๋ชจ๋ฐ์ผ ๊ธฐ๊ธฐ์์ ๊ฐ๋ก ์คํฌ๋กค์ ๋ฐ์์ํฌ ์ ์์ต๋๋ค. ๋ฏธ๋์ด ์ฟผ๋ฆฌ๋ฅผ ์ฌ์ฉํ์ฌ ๋ชจ๋ฐ์ผ ํ๊ฒฝ์์๋ ๋ค๋ฅธ ๊ฐ์ ์ ์ฉํ๋ ๊ฒ์ด ์ข๊ฒ ์ต๋๋ค.
```diff
const reviewStyle = css`
- min-width: 530px;
+ width: 100%;
+ @media (min-width: 530px) {
+ min-width: 530px;
+ }
```
<!-- suggestion_start -->
<details>
<summary>๐ Committable suggestion</summary>
> โผ๏ธ **IMPORTANT**
> Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
`````suggestion
width: 100%;
@media (min-width: 530px) {
min-width: 530px;
}
`````
</details>
<!-- suggestion_end -->
<!-- This is an auto-generated comment by CodeRabbit --> |
@@ -1,11 +1,11 @@
import DeleteIcon from '@/components/DeleteIcon';
import { textEllipsis } from '@/styles/GlobalStyles';
import { Review } from '@/types/reviewType';
-import { dateToString } from '@/utils/dataToString';
import { css } from '@emotion/react';
import Rating from '@/components/Rating';
import Profile from '../Profile';
+import { formatDate } from '@/utils/format';
interface ReviewCardProps {
review: Review;
@@ -24,41 +24,51 @@ const ReviewCard = ({
showDate,
showDelete,
}: ReviewCardProps) => {
+ // console.log(review.imgSrc.map((src, index) => src);
return (
<div css={reviewStyle}>
<div className="titleStyle">
<div className="titleText">
{showUser && review.user && (
<div css={userProfileStyles}>
<div className="profile-container">
- {review.imgSrc && <Profile url={review.imgSrc} size="40px" />}
+ <Profile url={review.user.userProfileImage} size="30px" />
<div className="user-info">
<div className="name-rating">
<div className="name">{review.user.socialName}</div>
</div>
<p className="createAt">
- {review?.createdAt instanceof Date ? dateToString(review.createdAt) : ''}
+ {review?.createdAt ? formatDate(review.createdAt) : ''}
</p>
</div>
</div>
</div>
)}
{showTitle && review?.title && <h2>{review.title}</h2>}
{showDate && (
- <p className="createAt">
- {review?.createdAt instanceof Date ? dateToString(review.createdAt) : ''}
- </p>
+ <p className="createAt">{review?.createdAt ? formatDate(review.createdAt) : ''}</p>
)}
<div className="ratingContainer">
<Rating rating={Number(review.rating)} />
</div>
</div>
{showDelete && <DeleteIcon onDelete={onDelete || (() => {})} />}
</div>
- <div className="imgContainer">
- <img src={review.imgSrc} alt="review" />
+ <div
+ css={css`
+ display: flex;
+ gap: 10px;
+ `}
+ >
+ {Array.isArray(review.imgSrc) &&
+ review.imgSrc.length > 0 &&
+ review.imgSrc.map((src, index) => (
+ <div key={index + src} className="imgContainer">
+ <img src={src} alt="๋ฆฌ๋ทฐ ์ด๋ฏธ์ง" />
+ </div>
+ ))}
</div>
- <p css={textEllipsis(3)}>{review.content}</p>
+ <p css={textEllipsis(4)}>{review.content}</p>
</div>
);
};
@@ -98,6 +108,7 @@ const userProfileStyles = css`
const reviewStyle = css`
border-radius: 10px;
width: 100%;
+ min-width: 530px;
background-color: #f8f8f8;
padding: 10px 15px 15px 15px;
margin-bottom: 20px;
@@ -129,12 +140,13 @@ const reviewStyle = css`
border-radius: 5px;
overflow: hidden;
}
+
img {
width: 100%;
}
.ratingContainer {
- transform: translateY(-0.8px);
+ transform: translateY(-0.36vh);
}
.createAt { | Unknown | _:warning: Potential issue_
**์ด๋ฏธ์ง ๋ ๋๋ง ์ key prop์ด ์๋ชป๋ ์์น์ ์์ต๋๋ค.**
ํ์ฌ `key` prop์ด `img` ํ๊ทธ์ ์์ง๋ง, map ํจ์์ ์ต์์ ์์์ธ `div`๋ก ์ด๋ํด์ผ ํฉ๋๋ค. ๋ํ, ์ด๋ฏธ์ง URL์ key๋ก ์ฌ์ฉํ๋ ๊ฒ์ด index๋ณด๋ค ๋ ์์ ์ ์
๋๋ค.
```diff
{Array.isArray(review.imgSrc) &&
review.imgSrc.length > 0 &&
review.imgSrc.map((src, index) => (
- <div className="imgContainer">
- <img key={index} src={src} alt="๋ฆฌ๋ทฐ ์ด๋ฏธ์ง" />
+ <div key={src} className="imgContainer">
+ <img src={src} alt="๋ฆฌ๋ทฐ ์ด๋ฏธ์ง" />
</div>
))}
```
<!-- suggestion_start -->
<details>
<summary>๐ Committable suggestion</summary>
> โผ๏ธ **IMPORTANT**
> Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
`````suggestion
{Array.isArray(review.imgSrc) &&
review.imgSrc.length > 0 &&
review.imgSrc.map((src, index) => (
<div key={src} className="imgContainer">
<img src={src} alt="๋ฆฌ๋ทฐ ์ด๋ฏธ์ง" />
</div>
))}
`````
</details>
<!-- suggestion_end -->
<details>
<summary>๐งฐ Tools</summary>
<details>
<summary>๐ช Biome (1.9.4)</summary>
[error] 66-66: Missing key property for this element in iterable.
The order of the items may change, and having a key can help React identify which item was moved.
Check the React documentation.
(lint/correctness/useJsxKeyInIterable)
</details>
</details>
<!-- This is an auto-generated comment by CodeRabbit --> |
@@ -1,58 +1,52 @@
-import reviewImage from '@/assets/reviewImg.png';
import ReviewCard from '@/components/myReview/ReviewCard';
-import { Review } from '@/types/reviewType';
-// import ReviewWriteModal from '@/components/myReview/ReviewWriteModal';
-
-const data: { reviews: Review[] } = {
- reviews: [
- {
- reviewId: 1,
- title: '๋ํ ๊ณ ๊ถ ํฌ์ด',
- content:
- '๊ฒฝ๋ณต๊ถ์ ํ๊ตญ์ ์ญ์ฌ์ ์ ํต์ ์จ์ ํ ๋๋ ์ ์๋ ๊ณณ์ด์์ด์. ์ ๋ฌธ์ธ ๊ดํ๋ฌธ์ ์ง๋ ๋ค์ด์๋ฉด ์
์ฅํ ๊ทผ์ ์ ๊ณผ ๊ฒฝํ๋ฃจ๊ฐ ์์ ์ ์ฌ๋ก์ก๊ณ , ์กฐ์ฉํ ์ฐ๋ชป๊ณผ ์ ์์ ๋ง์น ์ ์๋๋ก ๋์๊ฐ ๋ฏํ ๊ธฐ๋ถ์ ์ฃผ์๋ต๋๋ค. ์ฃผ๋ณ์ ํ๋ณต ๋์ฌ์ ์์ ํ๋ณต์ ์
๊ณ ๋ฐฉ๋ฌธํ๋ ๋์ฑ ํน๋ณํ ์ถ์ต์ผ๋ก ๋จ์์ด์. ๊ณ ์ฆ๋ํ ๋ถ์๊ธฐ ์์์ ์๊ฐ์ ๋ณด๋ด๋ฉฐ ํ๊ตญ์ ๋ฉ๊ณผ ์๋ฆ๋ค์์ ์์ผ ๋๋ ์ ์์๋ ์๊ฐ์ด์์ด์.',
- imgSrc: reviewImage,
- createdAt: new Date('2024-10-25'),
- reviewCount: 10,
- rating: 4.5,
- },
- {
- reviewId: 2,
- title: '๋ํ ๊ณ ๊ถ ํฌ์ด',
- content:
- '๊ฒฝ๋ณต๊ถ์ ํ๊ตญ์ ์ญ์ฌ์ ์ ํต์ ์จ์ ํ ๋๋ ์ ์๋ ๊ณณ์ด์์ด์. ์ ๋ฌธ์ธ ๊ดํ๋ฌธ์ ์ง๋ ๋ค์ด์๋ฉด ์
์ฅํ ๊ทผ์ ์ ๊ณผ ๊ฒฝํ๋ฃจ๊ฐ ์์ ์ ์ฌ๋ก์ก๊ณ , ์กฐ์ฉํ ์ฐ๋ชป๊ณผ ์ ์์ ๋ง์น ์ ์๋๋ก ๋์๊ฐ ๋ฏํ ๊ธฐ๋ถ์ ์ฃผ์๋ต๋๋ค. ์ฃผ๋ณ์ ํ๋ณต ๋์ฌ์ ์์ ํ๋ณต์ ์
๊ณ ๋ฐฉ๋ฌธํ๋ ๋์ฑ ํน๋ณํ ์ถ์ต์ผ๋ก ๋จ์์ด์. ๊ณ ์ฆ๋ํ ๋ถ์๊ธฐ ์์์ ์๊ฐ์ ๋ณด๋ด๋ฉฐ ํ๊ตญ์ ๋ฉ๊ณผ ์๋ฆ๋ค์์ ์์ผ ๋๋ ์ ์์๋ ์๊ฐ์ด์์ด์.',
- imgSrc: reviewImage,
- createdAt: new Date('2024-10-25'),
- reviewCount: 10,
- rating: 5.0,
- },
- {
- reviewId: 3,
- title: '๋ํ ๊ณ ๊ถ ํฌ์ด',
- content:
- '๊ฒฝ๋ณต๊ถ์ ํ๊ตญ์ ์ญ์ฌ์ ์ ํต์ ์จ์ ํ ๋๋ ์ ์๋ ๊ณณ์ด์์ด์. ์ ๋ฌธ์ธ ๊ดํ๋ฌธ์ ์ง๋ ๋ค์ด์๋ฉด ์
์ฅํ ๊ทผ์ ์ ๊ณผ ๊ฒฝํ๋ฃจ๊ฐ ์์ ์ ์ฌ๋ก์ก๊ณ , ์กฐ์ฉํ ์ฐ๋ชป๊ณผ ์ ์์ ๋ง์น ์ ์๋๋ก ๋์๊ฐ ๋ฏํ ๊ธฐ๋ถ์ ์ฃผ์๋ต๋๋ค. ์ฃผ๋ณ์ ํ๋ณต ๋์ฌ์ ์์ ํ๋ณต์ ์
๊ณ ๋ฐฉ๋ฌธํ๋ ๋์ฑ ํน๋ณํ ์ถ์ต์ผ๋ก ๋จ์์ด์. ๊ณ ์ฆ๋ํ ๋ถ์๊ธฐ ์์์ ์๊ฐ์ ๋ณด๋ด๋ฉฐ ํ๊ตญ์ ๋ฉ๊ณผ ์๋ฆ๋ค์์ ์์ผ ๋๋ ์ ์์๋ ์๊ฐ์ด์์ด์.',
- imgSrc: reviewImage,
- createdAt: new Date('2024-10-25'),
- reviewCount: 10,
- rating: 4.7,
- },
- ],
-};
+import { REVIEW_LIST } from '@/constants/queryKey';
+import useGetReviews from '@/hooks/query/useGetReviews';
+import useUserStore from '@/stores/useUserStore';
+import { useQueryClient } from '@tanstack/react-query';
+import { useCallback, useEffect } from 'react';
+import { useInView } from 'react-intersection-observer';
const MyReviews = () => {
+ const user = useUserStore((state) => state.user);
+
+ const { data, fetchNextPage, isFetchingNextPage, hasNextPage } = useGetReviews({
+ userId: user?.userId ?? '',
+ });
+
+ const queryClient = useQueryClient();
+
+ const { ref } = useInView({
+ threshold: 1,
+ skip: !hasNextPage,
+ onChange: useCallback(
+ (inView: boolean) => {
+ if (inView && hasNextPage && !isFetchingNextPage) {
+ fetchNextPage();
+ }
+ },
+ [hasNextPage, isFetchingNextPage, fetchNextPage],
+ ),
+ });
+
+ const reviews = data?.pages.flatMap((group) => group.data.data.reviews) || [];
+
+ useEffect(() => {
+ queryClient.resetQueries({ queryKey: [REVIEW_LIST, user?.userId] });
+ }, [user?.userId, queryClient]);
+
return (
<div>
- <div>
- {data.reviews.map((review: Review) => (
- <ReviewCard
- key={review.reviewId}
- review={review}
- showTitle={true}
- showUser={false}
- showDate={true}
- showDelete={true}
- />
- ))}
- </div>
+ {reviews.map((review) => (
+ <ReviewCard
+ key={review.reviewId}
+ review={review}
+ showTitle={true}
+ showUser={false}
+ showDate={true}
+ showDelete={true}
+ />
+ ))}
+ {hasNextPage && <div ref={ref}>{isFetchingNextPage ? 'Loading more...' : ''}</div>}
</div>
);
}; | Unknown | _:hammer_and_wrench: Refactor suggestion_
**์ฌ์ฉ์ ID ํ์
์บ์คํ
๊ฐ์ ํ์**
์ฌ์ฉ์ ID๋ฅผ ๋ฌธ์์ด๋ก ๊ฐ์ ์บ์คํ
ํ๋ ๋ถ๋ถ์ด ์์ต๋๋ค. ํ์
์์ ์ฑ์ ๋์ด๊ธฐ ์ํด ๊ฐ์ ์ด ํ์ํฉ๋๋ค.
๋ค์๊ณผ ๊ฐ์ด ์์ ์ ์ ์ํฉ๋๋ค:
```diff
- userId: (user?.userId as string) || '',
+ userId: user?.userId ?? '',
```
<!-- suggestion_start -->
<details>
<summary>๐ Committable suggestion</summary>
> โผ๏ธ **IMPORTANT**
> Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
`````suggestion
const user = useUserStore((state) => state.user);
const { data, fetchNextPage, isFetchingNextPage, hasNextPage } = useGetReviews({
userId: user?.userId ?? '',
});
`````
</details>
<!-- suggestion_end -->
<!-- This is an auto-generated comment by CodeRabbit --> |
@@ -0,0 +1,79 @@
+@import url('https://fonts.googleapis.com/css2?family=Lobster&display=swap');
+
+* {
+ box-sizing: border-box;
+}
+body{
+ background-color:#fafafa;
+}
+
+.login-wrap{
+ width:30%;
+ height:550px;
+ background-color:#fff;
+ border:3px solid rgba(221, 221, 221, 0.3);
+ margin:130px auto 0 auto;
+
+ h1{
+ width:80%;
+ height:50px;
+ font-size:55px;
+ font-family: 'Lobster', cursive;
+ padding-top:50px;
+ margin:0 auto 120px auto;
+ text-align: center;
+ }
+
+ .inner-wrap {
+ width:80%;
+ margin:auto;
+ height:300px;
+
+ input {
+ width:100%;
+ height:60px;
+ border-radius: 5px;
+ border:2px solid rgba(221, 221, 221, 0.2);
+ margin-bottom:10px;
+ padding:30px 10px;
+ font-size:18px;
+ color:#000;
+ cursor: pointer;
+ outline:none;
+ line-height: 30px;
+ }
+
+ .on {
+ background-color:#0094f6;
+ }
+
+ .off {
+ background-color:#0094f64b;
+ }
+
+ button {
+ width:100%;
+ height:50px;
+ margin-top:15px;
+ border:none;
+ background-color:#0094f64b;
+ border-radius: 8px;
+ color:#fff;
+ font-size:20px;
+ font-weight:600;
+ outline:none;
+ cursor:pointer;
+ }
+
+ p{
+ text-align:center;
+ margin-top:110px;
+
+ a{
+ color:#00376b;
+ font-size:16px;
+ text-decoration: none;
+ }
+ }
+ }
+} | Unknown | CSS ์์ฑ ์์๋๋ก ๋ณ๊ฒฝํ๋ฉด ๋ ์ข์๊ฒ ๊ฐ์์
margin, padding ๋ค์ font-size ์์ด๋ค์ ;) |
@@ -0,0 +1,32 @@
+import React from "react";
+import "./Footer.scss";
+
+class Footer extends React.Component {
+ render() {
+ return (
+ <footer>
+ <ul>
+ {RIGHT_FOOTER.map((element, index) => {
+ return <li key={index}>{element}</li>;
+ })}
+ </ul>
+ <p className="made">ยฉ 2021 INSTAGRAM FROM doheekim</p>
+ </footer>
+ );
+ }
+}
+
+export default Footer;
+
+const RIGHT_FOOTER = [
+ "์๊ฐ",
+ "๋์๋ง",
+ "ํ๋ณด ์ผํฐ",
+ "API",
+ "์ฑ์ฉ์ ๋ณด",
+ "๊ฐ์ธ์ ๋ณด์ฒ๋ผ๋ฐฉ์นจ",
+ "์ฝ๊ด",
+ "์์น",
+ "์ธ๊ธฐ ๊ณ์ ",
+ "ํด์ฌํ๊ทธ",
+]; | JavaScript | footer ๋ด์ฉ ์ ๋ง๋์
จ๋ค์ bb |
@@ -0,0 +1,79 @@
+@import url('https://fonts.googleapis.com/css2?family=Lobster&display=swap');
+
+* {
+ box-sizing: border-box;
+}
+body{
+ background-color:#fafafa;
+}
+
+.login-wrap{
+ width:30%;
+ height:550px;
+ background-color:#fff;
+ border:3px solid rgba(221, 221, 221, 0.3);
+ margin:130px auto 0 auto;
+
+ h1{
+ width:80%;
+ height:50px;
+ font-size:55px;
+ font-family: 'Lobster', cursive;
+ padding-top:50px;
+ margin:0 auto 120px auto;
+ text-align: center;
+ }
+
+ .inner-wrap {
+ width:80%;
+ margin:auto;
+ height:300px;
+
+ input {
+ width:100%;
+ height:60px;
+ border-radius: 5px;
+ border:2px solid rgba(221, 221, 221, 0.2);
+ margin-bottom:10px;
+ padding:30px 10px;
+ font-size:18px;
+ color:#000;
+ cursor: pointer;
+ outline:none;
+ line-height: 30px;
+ }
+
+ .on {
+ background-color:#0094f6;
+ }
+
+ .off {
+ background-color:#0094f64b;
+ }
+
+ button {
+ width:100%;
+ height:50px;
+ margin-top:15px;
+ border:none;
+ background-color:#0094f64b;
+ border-radius: 8px;
+ color:#fff;
+ font-size:20px;
+ font-weight:600;
+ outline:none;
+ cursor:pointer;
+ }
+
+ p{
+ text-align:center;
+ margin-top:110px;
+
+ a{
+ color:#00376b;
+ font-size:16px;
+ text-decoration: none;
+ }
+ }
+ }
+} | Unknown | ๋ต ์์ ํ๊ฒ ์ต๋๋ค! |
@@ -0,0 +1,98 @@
+import { Component } from "react";
+import { Link, withRouter } from "react-router-dom";
+import "./Login.scss";
+
+class Login extends Component {
+ constructor() {
+ super();
+ this.state = {
+ id: "",
+ pw: "",
+ };
+ }
+
+ // localStorage.clear();
+ // localStorage.removeItem('key');
+ // localStorage.getItem('key');
+
+ //์ ์ฅ
+
+ //์กฐํ
+ // let getValue = localStorage.getItem('Token');
+ // console.log(getValue);
+ // localStorage
+
+ goToMain = () => {
+ fetch("http://10.58.2.229:8000/users/login", {
+ method: "POST",
+ body: JSON.stringify({
+ account: this.state.id,
+ password: this.state.pw,
+ // phone_number: "01034358181",
+ // name: "๊น๋ํ",
+ }),
+ })
+ .then((res) => res.json())
+ .then((result) => {
+ console.log(result);
+ if (result.MESSAGE === "SUCCESS") {
+ localStorage.setItem("Token", result.Token);
+ alert("๋ก๊ทธ์ธ์ฑ๊ณต!");
+ this.props.history.push("/maindh");
+ } else {
+ alert("๐คฌIT'S YOUR FAULT!๐คฌ");
+ }
+ });
+ };
+
+ handleInput = (event) => {
+ const { name, value } = event.target;
+ this.setState({
+ [name]: value,
+ });
+ };
+
+ render() {
+ const { id, pw } = this.state;
+ return (
+ <>
+ <div className="login-wrap">
+ <h1 className="title">Westagram</h1>
+ <div className="inner-wrap">
+ <input
+ className="id"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={this.handleInput}
+ value={id}
+ name="id"
+ />
+ <input
+ className="password"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={this.handleInput}
+ value={pw}
+ name="pw"
+ />
+ <button
+ className={id.includes("@") && pw.length >= 5 ? "on" : "off"}
+ onClick={this.goToMain}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <p>
+ <Link to="/Main">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</Link>
+ </p>
+ </div>
+ </div>
+ </>
+ );
+ }
+}
+
+export default withRouter(Login);
+
+//๊ฐ์ฒด ๊ตฌ์กฐ ๋ถํด ํ ๋น
+
+//const { fontState} = this.state | JavaScript | this.state ๋ ๊ตฌ์กฐ๋ถํดํ ๋น์ ์ฌ์ฉํด์ ์ ๋ฆฌํด์ฃผ์๋ฉด ๋ ๊น๋ํ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,98 @@
+import { Component } from "react";
+import { Link, withRouter } from "react-router-dom";
+import "./Login.scss";
+
+class Login extends Component {
+ constructor() {
+ super();
+ this.state = {
+ id: "",
+ pw: "",
+ };
+ }
+
+ // localStorage.clear();
+ // localStorage.removeItem('key');
+ // localStorage.getItem('key');
+
+ //์ ์ฅ
+
+ //์กฐํ
+ // let getValue = localStorage.getItem('Token');
+ // console.log(getValue);
+ // localStorage
+
+ goToMain = () => {
+ fetch("http://10.58.2.229:8000/users/login", {
+ method: "POST",
+ body: JSON.stringify({
+ account: this.state.id,
+ password: this.state.pw,
+ // phone_number: "01034358181",
+ // name: "๊น๋ํ",
+ }),
+ })
+ .then((res) => res.json())
+ .then((result) => {
+ console.log(result);
+ if (result.MESSAGE === "SUCCESS") {
+ localStorage.setItem("Token", result.Token);
+ alert("๋ก๊ทธ์ธ์ฑ๊ณต!");
+ this.props.history.push("/maindh");
+ } else {
+ alert("๐คฌIT'S YOUR FAULT!๐คฌ");
+ }
+ });
+ };
+
+ handleInput = (event) => {
+ const { name, value } = event.target;
+ this.setState({
+ [name]: value,
+ });
+ };
+
+ render() {
+ const { id, pw } = this.state;
+ return (
+ <>
+ <div className="login-wrap">
+ <h1 className="title">Westagram</h1>
+ <div className="inner-wrap">
+ <input
+ className="id"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={this.handleInput}
+ value={id}
+ name="id"
+ />
+ <input
+ className="password"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={this.handleInput}
+ value={pw}
+ name="pw"
+ />
+ <button
+ className={id.includes("@") && pw.length >= 5 ? "on" : "off"}
+ onClick={this.goToMain}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <p>
+ <Link to="/Main">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</Link>
+ </p>
+ </div>
+ </div>
+ </>
+ );
+ }
+}
+
+export default withRouter(Login);
+
+//๊ฐ์ฒด ๊ตฌ์กฐ ๋ถํด ํ ๋น
+
+//const { fontState} = this.state | JavaScript | ์ ๋ถ๋ถ ๋
ธ์
์์ ๋ดค๋๋ฐ handleId๋ handlePw๊ฐ์ด ๋๊ฐ์ ํ์์ event handler๋ผ์ ํฉ์น ์ ์๋๋ผ๊ตฌ์! ์ ๋ ์์ง์ํ์ง๋ง...^^ ๊ฐ์ด ํด๋ณด์์ ใ
ใ
ใ
|
@@ -0,0 +1,79 @@
+@import url('https://fonts.googleapis.com/css2?family=Lobster&display=swap');
+
+* {
+ box-sizing: border-box;
+}
+body{
+ background-color:#fafafa;
+}
+
+.login-wrap{
+ width:30%;
+ height:550px;
+ background-color:#fff;
+ border:3px solid rgba(221, 221, 221, 0.3);
+ margin:130px auto 0 auto;
+
+ h1{
+ width:80%;
+ height:50px;
+ font-size:55px;
+ font-family: 'Lobster', cursive;
+ padding-top:50px;
+ margin:0 auto 120px auto;
+ text-align: center;
+ }
+
+ .inner-wrap {
+ width:80%;
+ margin:auto;
+ height:300px;
+
+ input {
+ width:100%;
+ height:60px;
+ border-radius: 5px;
+ border:2px solid rgba(221, 221, 221, 0.2);
+ margin-bottom:10px;
+ padding:30px 10px;
+ font-size:18px;
+ color:#000;
+ cursor: pointer;
+ outline:none;
+ line-height: 30px;
+ }
+
+ .on {
+ background-color:#0094f6;
+ }
+
+ .off {
+ background-color:#0094f64b;
+ }
+
+ button {
+ width:100%;
+ height:50px;
+ margin-top:15px;
+ border:none;
+ background-color:#0094f64b;
+ border-radius: 8px;
+ color:#fff;
+ font-size:20px;
+ font-weight:600;
+ outline:none;
+ cursor:pointer;
+ }
+
+ p{
+ text-align:center;
+ margin-top:110px;
+
+ a{
+ color:#00376b;
+ font-size:16px;
+ text-decoration: none;
+ }
+ }
+ }
+} | Unknown | ์์ฃผ์ฐ๋ border variable ์๋ค๊ฐ ์ ์ฅํด๋๊ณ ์ฐ๋๊น ํธํ๊ณ ์ข๋๋ผ๊ตฌ์! |
@@ -0,0 +1,21 @@
+import React from "react";
+import "./MainRight.scss";
+import RecommendHeader from "./MainRight/RecommendHeader";
+import RecommendTitle from "./MainRight/RecommendTitle";
+import RecommendFriends from "./MainRight/RecommendFriends";
+import Footer from "./MainRight/Footer";
+
+class MainRight extends React.Component {
+ render() {
+ return (
+ <div className="main-right">
+ <RecommendHeader></RecommendHeader>
+ <RecommendTitle></RecommendTitle>
+ <RecommendFriends></RecommendFriends>
+ <Footer></Footer>
+ </div>
+ );
+ }
+}
+
+export default MainRight; | JavaScript | ์ค ๋ฒ์จ ๋ค ๋๋์
จ๋ค๋ ๐ |
@@ -0,0 +1,21 @@
+import React from "react";
+import "./MainRight.scss";
+import RecommendHeader from "./MainRight/RecommendHeader";
+import RecommendTitle from "./MainRight/RecommendTitle";
+import RecommendFriends from "./MainRight/RecommendFriends";
+import Footer from "./MainRight/Footer";
+
+class MainRight extends React.Component {
+ render() {
+ return (
+ <div className="main-right">
+ <RecommendHeader></RecommendHeader>
+ <RecommendTitle></RecommendTitle>
+ <RecommendFriends></RecommendFriends>
+ <Footer></Footer>
+ </div>
+ );
+ }
+}
+
+export default MainRight; | JavaScript | ๊น๋....๐คญ |
@@ -0,0 +1,98 @@
+import { Component } from "react";
+import { Link, withRouter } from "react-router-dom";
+import "./Login.scss";
+
+class Login extends Component {
+ constructor() {
+ super();
+ this.state = {
+ id: "",
+ pw: "",
+ };
+ }
+
+ // localStorage.clear();
+ // localStorage.removeItem('key');
+ // localStorage.getItem('key');
+
+ //์ ์ฅ
+
+ //์กฐํ
+ // let getValue = localStorage.getItem('Token');
+ // console.log(getValue);
+ // localStorage
+
+ goToMain = () => {
+ fetch("http://10.58.2.229:8000/users/login", {
+ method: "POST",
+ body: JSON.stringify({
+ account: this.state.id,
+ password: this.state.pw,
+ // phone_number: "01034358181",
+ // name: "๊น๋ํ",
+ }),
+ })
+ .then((res) => res.json())
+ .then((result) => {
+ console.log(result);
+ if (result.MESSAGE === "SUCCESS") {
+ localStorage.setItem("Token", result.Token);
+ alert("๋ก๊ทธ์ธ์ฑ๊ณต!");
+ this.props.history.push("/maindh");
+ } else {
+ alert("๐คฌIT'S YOUR FAULT!๐คฌ");
+ }
+ });
+ };
+
+ handleInput = (event) => {
+ const { name, value } = event.target;
+ this.setState({
+ [name]: value,
+ });
+ };
+
+ render() {
+ const { id, pw } = this.state;
+ return (
+ <>
+ <div className="login-wrap">
+ <h1 className="title">Westagram</h1>
+ <div className="inner-wrap">
+ <input
+ className="id"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={this.handleInput}
+ value={id}
+ name="id"
+ />
+ <input
+ className="password"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={this.handleInput}
+ value={pw}
+ name="pw"
+ />
+ <button
+ className={id.includes("@") && pw.length >= 5 ? "on" : "off"}
+ onClick={this.goToMain}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <p>
+ <Link to="/Main">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</Link>
+ </p>
+ </div>
+ </div>
+ </>
+ );
+ }
+}
+
+export default withRouter(Login);
+
+//๊ฐ์ฒด ๊ตฌ์กฐ ๋ถํด ํ ๋น
+
+//const { fontState} = this.state | JavaScript | ์ค์ท ํ๋ฒ ์๋ํด๋ด์ผ๊ฒ ์ด์! |
@@ -0,0 +1,21 @@
+import React from "react";
+import "./MainRight.scss";
+import RecommendHeader from "./MainRight/RecommendHeader";
+import RecommendTitle from "./MainRight/RecommendTitle";
+import RecommendFriends from "./MainRight/RecommendFriends";
+import Footer from "./MainRight/Footer";
+
+class MainRight extends React.Component {
+ render() {
+ return (
+ <div className="main-right">
+ <RecommendHeader></RecommendHeader>
+ <RecommendTitle></RecommendTitle>
+ <RecommendFriends></RecommendFriends>
+ <Footer></Footer>
+ </div>
+ );
+ }
+}
+
+export default MainRight; | JavaScript | ๊ฐ์ฌํฉ๋๋ฏ๐คญ |
@@ -0,0 +1,79 @@
+@import url('https://fonts.googleapis.com/css2?family=Lobster&display=swap');
+
+* {
+ box-sizing: border-box;
+}
+body{
+ background-color:#fafafa;
+}
+
+.login-wrap{
+ width:30%;
+ height:550px;
+ background-color:#fff;
+ border:3px solid rgba(221, 221, 221, 0.3);
+ margin:130px auto 0 auto;
+
+ h1{
+ width:80%;
+ height:50px;
+ font-size:55px;
+ font-family: 'Lobster', cursive;
+ padding-top:50px;
+ margin:0 auto 120px auto;
+ text-align: center;
+ }
+
+ .inner-wrap {
+ width:80%;
+ margin:auto;
+ height:300px;
+
+ input {
+ width:100%;
+ height:60px;
+ border-radius: 5px;
+ border:2px solid rgba(221, 221, 221, 0.2);
+ margin-bottom:10px;
+ padding:30px 10px;
+ font-size:18px;
+ color:#000;
+ cursor: pointer;
+ outline:none;
+ line-height: 30px;
+ }
+
+ .on {
+ background-color:#0094f6;
+ }
+
+ .off {
+ background-color:#0094f64b;
+ }
+
+ button {
+ width:100%;
+ height:50px;
+ margin-top:15px;
+ border:none;
+ background-color:#0094f64b;
+ border-radius: 8px;
+ color:#fff;
+ font-size:20px;
+ font-weight:600;
+ outline:none;
+ cursor:pointer;
+ }
+
+ p{
+ text-align:center;
+ margin-top:110px;
+
+ a{
+ color:#00376b;
+ font-size:16px;
+ text-decoration: none;
+ }
+ }
+ }
+} | Unknown | ๊ณตํต scss๋ฅผ ์ ํ์ฉํด๋ด์ผ๊ฒ ์ต๋๋ค! |
@@ -0,0 +1,18 @@
+.recommend-title {
+ width:100%;
+ height:40px;
+ margin-bottom:5px;
+
+ .recommend-title-left {
+ float:left;
+ font-size:14px;
+ color:#888;
+ font-weight:700;
+ }
+
+ .recommend-title-right {
+ float:right;
+ font-size:12px;
+ font-weight:600;
+ }
+}
\ No newline at end of file | Unknown | ์ ๋ชฉ ๊น๋ํ๊ณ ์์๋ฃ๊ธฐ ์ฌ์์ ์ข์๊ฑฐ๊ฐ์์! |
@@ -0,0 +1,98 @@
+import { Component } from "react";
+import { Link, withRouter } from "react-router-dom";
+import "./Login.scss";
+
+class Login extends Component {
+ constructor() {
+ super();
+ this.state = {
+ id: "",
+ pw: "",
+ };
+ }
+
+ // localStorage.clear();
+ // localStorage.removeItem('key');
+ // localStorage.getItem('key');
+
+ //์ ์ฅ
+
+ //์กฐํ
+ // let getValue = localStorage.getItem('Token');
+ // console.log(getValue);
+ // localStorage
+
+ goToMain = () => {
+ fetch("http://10.58.2.229:8000/users/login", {
+ method: "POST",
+ body: JSON.stringify({
+ account: this.state.id,
+ password: this.state.pw,
+ // phone_number: "01034358181",
+ // name: "๊น๋ํ",
+ }),
+ })
+ .then((res) => res.json())
+ .then((result) => {
+ console.log(result);
+ if (result.MESSAGE === "SUCCESS") {
+ localStorage.setItem("Token", result.Token);
+ alert("๋ก๊ทธ์ธ์ฑ๊ณต!");
+ this.props.history.push("/maindh");
+ } else {
+ alert("๐คฌIT'S YOUR FAULT!๐คฌ");
+ }
+ });
+ };
+
+ handleInput = (event) => {
+ const { name, value } = event.target;
+ this.setState({
+ [name]: value,
+ });
+ };
+
+ render() {
+ const { id, pw } = this.state;
+ return (
+ <>
+ <div className="login-wrap">
+ <h1 className="title">Westagram</h1>
+ <div className="inner-wrap">
+ <input
+ className="id"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={this.handleInput}
+ value={id}
+ name="id"
+ />
+ <input
+ className="password"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={this.handleInput}
+ value={pw}
+ name="pw"
+ />
+ <button
+ className={id.includes("@") && pw.length >= 5 ? "on" : "off"}
+ onClick={this.goToMain}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <p>
+ <Link to="/Main">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</Link>
+ </p>
+ </div>
+ </div>
+ </>
+ );
+ }
+}
+
+export default withRouter(Login);
+
+//๊ฐ์ฒด ๊ตฌ์กฐ ๋ถํด ํ ๋น
+
+//const { fontState} = this.state | JavaScript | import { Link, withRouter } from "react-router-dom"; ํ์ค๋ก ๋ง๋ค์ด๋ ์ข์๊ฑฐ๊ฐ์์! |
@@ -0,0 +1,98 @@
+import { Component } from "react";
+import { Link, withRouter } from "react-router-dom";
+import "./Login.scss";
+
+class Login extends Component {
+ constructor() {
+ super();
+ this.state = {
+ id: "",
+ pw: "",
+ };
+ }
+
+ // localStorage.clear();
+ // localStorage.removeItem('key');
+ // localStorage.getItem('key');
+
+ //์ ์ฅ
+
+ //์กฐํ
+ // let getValue = localStorage.getItem('Token');
+ // console.log(getValue);
+ // localStorage
+
+ goToMain = () => {
+ fetch("http://10.58.2.229:8000/users/login", {
+ method: "POST",
+ body: JSON.stringify({
+ account: this.state.id,
+ password: this.state.pw,
+ // phone_number: "01034358181",
+ // name: "๊น๋ํ",
+ }),
+ })
+ .then((res) => res.json())
+ .then((result) => {
+ console.log(result);
+ if (result.MESSAGE === "SUCCESS") {
+ localStorage.setItem("Token", result.Token);
+ alert("๋ก๊ทธ์ธ์ฑ๊ณต!");
+ this.props.history.push("/maindh");
+ } else {
+ alert("๐คฌIT'S YOUR FAULT!๐คฌ");
+ }
+ });
+ };
+
+ handleInput = (event) => {
+ const { name, value } = event.target;
+ this.setState({
+ [name]: value,
+ });
+ };
+
+ render() {
+ const { id, pw } = this.state;
+ return (
+ <>
+ <div className="login-wrap">
+ <h1 className="title">Westagram</h1>
+ <div className="inner-wrap">
+ <input
+ className="id"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={this.handleInput}
+ value={id}
+ name="id"
+ />
+ <input
+ className="password"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={this.handleInput}
+ value={pw}
+ name="pw"
+ />
+ <button
+ className={id.includes("@") && pw.length >= 5 ? "on" : "off"}
+ onClick={this.goToMain}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <p>
+ <Link to="/Main">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</Link>
+ </p>
+ </div>
+ </div>
+ </>
+ );
+ }
+}
+
+export default withRouter(Login);
+
+//๊ฐ์ฒด ๊ตฌ์กฐ ๋ถํด ํ ๋น
+
+//const { fontState} = this.state | JavaScript | ๋ต! ๋ฆฌํฉํ ๋ง ํด๋ณด๊ฒ ์ต๋๋ค๐ |
@@ -0,0 +1,63 @@
+import React from "react";
+import Story from "./Mainleft/Story";
+import Feed from "./Mainleft/Feed";
+import "./MainLeft.scss";
+// import { FaRedditAlien } from "react-icons/fa";
+
+class MainLeft extends React.Component {
+ state = {
+ feedList: [],
+ };
+
+ componentDidMount() {
+ fetch("/data/FeedData.json", {
+ method: "GET",
+ })
+ .then((res) => res.json())
+ .then((data) => {
+ this.setState({
+ feedList: data,
+ });
+ });
+ }
+
+ aaa = () => {
+ // console.log("aaa ํจ์ํธ์ถ");
+ fetch("http://10.58.2.229:8000/posts/post", {
+ method: "GET",
+ headers: {
+ Authorization: localStorage.getItem("Token"),
+ },
+ })
+ .then((res) => res.json())
+ .then((res) => {
+ this.setState({
+ feedList: res.RESULT,
+ });
+ console.log(res.RESULT);
+ });
+ };
+
+ render() {
+ const { feedList } = this.state;
+ return (
+ <div className="main-left">
+ {/* <button onClick={this.aaa}>click</button> */}
+ <Story />
+ {feedList.map((element) => {
+ return (
+ <Feed
+ id={element.id}
+ name={element.userId}
+ count={element.count}
+ img={element.img}
+ title={element.title}
+ />
+ );
+ })}
+ </div>
+ );
+ }
+}
+
+export default MainLeft; | JavaScript | ํ๊ทธ๋ช
์ด ํ๋์ ๋ค์ด์์๐ |
@@ -0,0 +1,50 @@
+@import "../../common.scss";
+
+.recommend-header {
+ width:100%;
+ height:100px;
+ @extend %flexbetween;
+ margin-top:5px;
+
+ li {
+ position:relative;
+ &:first-child {
+ &:after {
+ width:64px;
+ height:64px;
+ border:1px solid #ddd;
+ border-radius: 50%;
+ content:"";
+ position:absolute;
+ top:-3px; left:-3px;
+ }
+ }
+
+ .recommend-header-flex {
+ display:flex;
+ justify-content: flex-start;
+ align-items: center;
+
+ li {
+
+ img {
+ width:100%;
+ width:60px;
+ height:60px;
+ border-radius:50%;
+ margin-bottom:5px;
+ }
+
+ .recommend-header-id {
+ font-weight:700;
+ margin-left:10px;
+ }
+ }
+ }
+ }
+
+ .log-out {
+ float:right;
+ }
+}
+ | Unknown | tirm ํจ์? ์ด์ฉํด์ ๋น์นธ enter๋ฐฉ์งํ๋ ๋ฐฉ๋ฒ์ด์๋๋ผ๊ตฌ์ ๊ฐ์ด ์ฌ์ฉํด๋ด์๐ |
@@ -0,0 +1,181 @@
+import React from "react";
+import Comments from "./Comments";
+import COMMENT from "./CommentData";
+import "./Feed.scss";
+import { FaEllipsisH } from "react-icons/fa";
+import { FaRegHeart } from "react-icons/fa";
+import { FaRegComment } from "react-icons/fa";
+import { FaRegShareSquare } from "react-icons/fa";
+import { FaRegBookmark } from "react-icons/fa";
+import { FaRegSmile } from "react-icons/fa";
+
+class Feed extends React.Component {
+ constructor() {
+ super();
+ this.state = {
+ color: "#0094f64b",
+ newComment: "",
+ comments: [[{ id: 0, userId: "", comment: "" }]],
+ };
+ }
+
+ commentValue = (e) => {
+ this.setState({
+ newComment: e.target.value,
+ });
+ };
+
+ addComment = () => {
+ console.log("ํจ์๋ฅผ ์คํ๋๊ฑฐ์");
+ const { comments, newComment } = this.state;
+ const token = localStorage.getItem("Token");
+ fetch("http://10.58.2.229:8000/comment", {
+ method: "POST",
+ headers: {
+ Authorization: token, //Authorization : ์ธ์ฆํ ํฐ์ ์๋ฒ๋ก ๋ณด๋ผ๋
+ },
+ body: JSON.stringify({
+ newComment: newComment,
+ //๊ฒฝ์ฌ๋์ด ๋งํด์ค ์ด๋ฆ
+ }),
+ })
+ .then((res) => res.json())
+ .then((res) => {
+ this.setState({ comments: res.message });
+ this.setState({ newComment: "" });
+ });
+
+ this.setState({
+ comments: [
+ ...comments,
+ {
+ userId: "_ggul_dodo",
+ comment: newComment,
+ key: comments.length,
+ },
+ ],
+ newComment: "",
+ });
+ };
+
+ componentDidMount() {
+ this.setState({
+ comments: COMMENT,
+ });
+ }
+
+ pressEnter = (e) => {
+ if (e.key === "Enter" && this.state.newComment) {
+ this.addComment();
+ e.target.value = "";
+ }
+ };
+
+ render() {
+ console.log(this.props); //๋ฐ์ดํฐ ํ๋กญ์ค ๋ฐ์์ค๋์ง
+ return (
+ <div className="feeds">
+ <article>
+ <ul className="feeds-header">
+ <li className="feeds-idwrap">
+ <ul>
+ <li className="mini-profile">
+ <img
+ src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/154058443_217688870078059_3669752827847367841_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=ceRMdT1axXoAX_Lpuxn&edm=AABBvjUAAAAA&ccb=7-4&oh=92252211fe0704195cbc8ded03d8a95b&oe=608AF997&_nc_sid=83d603"
+ alt="๋ํฌ๋ฏธ๋ํ๋กํ"
+ />
+ </li>
+ <li className="mini-id">{this.props.name}</li>
+ </ul>
+ </li>
+ <li className="more">
+ <FaEllipsisH />
+ </li>
+ </ul>
+ <img src={this.props.img} alt="ํผ๋์ฌ์ง" />
+ <div className="feeds-bottom">
+ <ul className="feeds-bottom-flex">
+ <li className="feeds-icon">
+ <ul className="feeds-iconbox">
+ <li className="heart-btn">
+ <button>
+ <FaRegHeart />
+ </button>
+ </li>
+ <li className="comment-btn">
+ <button>
+ <FaRegComment />
+ </button>
+ </li>
+ <li className="share-btn">
+ <button>
+ <FaRegShareSquare />
+ </button>
+ </li>
+ </ul>
+ </li>
+ <li className="bookmark">
+ <button>
+ <FaRegBookmark />
+ </button>
+ </li>
+ </ul>
+ <div className="heart-count">
+ <img
+ src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/155180730_424134145319091_2244618473151617561_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=jkEKojtr85AAX-RveBi&edm=AOG-cTkAAAAA&ccb=7-4&oh=7f7b1c626d17579c1586680935296ee6&oe=608C1C0B&_nc_sid=282b66"
+ alt="์ข์์๋๋ฅธ์ฌ๋์ฌ์ง"
+ />
+ <p>
+ <span className="bold">j_vely_s2</span>๋{" "}
+ <span>์ธ {this.props.count}๋ช
</span>์ด ์ข์ํฉ๋๋ค
+ </p>
+ </div>
+ <ul className="content-write">
+ <li>
+ <span className="chat-id">{this.props.name}</span>
+ <span className="chat-content">{this.props.title}</span>
+ </li>
+ {this.state.comments.map((item) => (
+ <Comments
+ key={item.length}
+ userId={item.userId}
+ comment={item.comment}
+ ></Comments>
+ ))}
+ </ul>
+ <p className="time">7์๊ฐ ์ </p>
+ </div>
+ <ul className="comment-write">
+ <li>{FaRegSmile}</li>
+ <li>
+ <input
+ className="comment-inner"
+ onChange={this.commentValue}
+ onKeyPress={this.pressEnter}
+ value={this.state.newComment}
+ type="text"
+ placeholder="๋๊ธ ๋ฌ๊ธฐ..."
+ />
+ </li>
+ <li>
+ <button
+ className="submit"
+ onClick={this.addComment}
+ style={{
+ color:
+ this.state.newComment.length > 0
+ ? "#0094f6"
+ : this.state.color,
+ }}
+ >
+ ๊ฒ์
+ </button>
+ </li>
+ </ul>
+ </article>
+ </div>
+ );
+ }
+}
+
+export default Feed; | JavaScript | ๋์์ ์ด๋ฒคํธ๊ฐ ์คํ๋ ์์๊ฒ ์ ๋ ์ฐ์ฐ์๋ก ์ฌ์ฉํด๋ด์ผ๊ฒ ์ด์!! |
@@ -0,0 +1,88 @@
+@import "../../../../styles/common.scss";
+
+
+%flexbetween {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+}
+
+nav {
+ width:100%;
+ height:55px;
+ background-color:#fff;
+ border-bottom :1px solid #ddd;
+ position:fixed;
+ top:0;
+ z-index:10;
+
+ ul{
+ margin:auto;
+ height:inherit;
+ width:60%;
+ display:flex;
+ justify-content:space-between;
+ align-items: center;
+
+ li{
+ .logo {
+ font-family: 'Lobster', cursive;
+ font-size:25px;
+ margin-top:-5px;
+ }
+ }
+
+ .search-wrap {
+ position:relative;
+
+ input {
+ width:200px;
+ height:30px;
+ border:1px solid #ddd;
+ background-color:#fafafa;
+ outline:none;
+ border-radius: 5px;
+ &::placeholder {
+ text-align:center;
+ }
+ }
+
+ svg {
+ color:#888;
+ font-size:12px;
+ position:absolute;
+ left:60px; top:9px;
+ }
+ }
+ }
+}
+
+.icon {
+ @extend %flexbetween;
+ margin-left:-30px;
+
+ li {
+ position:relative;
+ margin-left:15px;
+ &:nth-child(2):after {
+ width:4px;
+ height:4px;
+ border-radius:50%;
+ content:"";
+ background-color:red;
+ position:absolute;
+ top:30px;
+ right:10px;
+ }
+ &:last-child {
+ img {
+ border-radius: 50%;
+ }
+ }
+ img {
+ border-radius: 50%;
+ width:25px;
+ height:25px;
+ }
+ }
+}
\ No newline at end of file | Unknown | placeholder ์คํ์ผ ๊ฐ์ฃผ๋ ๋ฒ ์ ๋ ์จ๋ด์ผ๊ฒ ์ด์! |
@@ -0,0 +1,46 @@
+footer {
+ width:100%;
+ height:70px;
+
+ ul {
+ width:90%;
+ margin-top:20px;
+
+ li {
+ font-size:12px;
+ color:#888;
+ margin-bottom:10px;
+ position:relative;
+ padding-left:5px;
+ padding-right:10px;
+ display:inline-block;
+
+ &::after {
+ width:3px;
+ height:3px;
+ border-radius: 50%;
+ position:absolute;
+ top:25%; left:95%;
+ content:"";
+ background-color:#888;
+ }
+
+ &:nth-child(6) {
+ &::after {
+ display:none;
+ }
+ }
+
+ &:last-child {
+ &::after {
+ display:none;
+ }
+ }
+ }
+ }
+
+ .made {
+ font-size:12px;
+ color:#888;
+ }
+}
\ No newline at end of file | Unknown | css์ ํ์์ ๊ฐ์์์์ ํ์๋ฅผ ์ ์ด์ฉํ์
จ๋ค์..! ์ ํํ ์ด์ฉ๋ฒ์ ๋ชฐ๋๋๋ฐ ๋ฐฐ์๊ฐ๋๋ค ๐ฅ๐๐ป |
@@ -0,0 +1,50 @@
+@import "../../common.scss";
+
+.recommend-header {
+ width:100%;
+ height:100px;
+ @extend %flexbetween;
+ margin-top:5px;
+
+ li {
+ position:relative;
+ &:first-child {
+ &:after {
+ width:64px;
+ height:64px;
+ border:1px solid #ddd;
+ border-radius: 50%;
+ content:"";
+ position:absolute;
+ top:-3px; left:-3px;
+ }
+ }
+
+ .recommend-header-flex {
+ display:flex;
+ justify-content: flex-start;
+ align-items: center;
+
+ li {
+
+ img {
+ width:100%;
+ width:60px;
+ height:60px;
+ border-radius:50%;
+ margin-bottom:5px;
+ }
+
+ .recommend-header-id {
+ font-weight:700;
+ margin-left:10px;
+ }
+ }
+ }
+ }
+
+ .log-out {
+ float:right;
+ }
+}
+ | Unknown | afterํ์ฉ ๐๐ป |
@@ -0,0 +1,98 @@
+import { Component } from "react";
+import { Link, withRouter } from "react-router-dom";
+import "./Login.scss";
+
+class Login extends Component {
+ constructor() {
+ super();
+ this.state = {
+ id: "",
+ pw: "",
+ };
+ }
+
+ // localStorage.clear();
+ // localStorage.removeItem('key');
+ // localStorage.getItem('key');
+
+ //์ ์ฅ
+
+ //์กฐํ
+ // let getValue = localStorage.getItem('Token');
+ // console.log(getValue);
+ // localStorage
+
+ goToMain = () => {
+ fetch("http://10.58.2.229:8000/users/login", {
+ method: "POST",
+ body: JSON.stringify({
+ account: this.state.id,
+ password: this.state.pw,
+ // phone_number: "01034358181",
+ // name: "๊น๋ํ",
+ }),
+ })
+ .then((res) => res.json())
+ .then((result) => {
+ console.log(result);
+ if (result.MESSAGE === "SUCCESS") {
+ localStorage.setItem("Token", result.Token);
+ alert("๋ก๊ทธ์ธ์ฑ๊ณต!");
+ this.props.history.push("/maindh");
+ } else {
+ alert("๐คฌIT'S YOUR FAULT!๐คฌ");
+ }
+ });
+ };
+
+ handleInput = (event) => {
+ const { name, value } = event.target;
+ this.setState({
+ [name]: value,
+ });
+ };
+
+ render() {
+ const { id, pw } = this.state;
+ return (
+ <>
+ <div className="login-wrap">
+ <h1 className="title">Westagram</h1>
+ <div className="inner-wrap">
+ <input
+ className="id"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={this.handleInput}
+ value={id}
+ name="id"
+ />
+ <input
+ className="password"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={this.handleInput}
+ value={pw}
+ name="pw"
+ />
+ <button
+ className={id.includes("@") && pw.length >= 5 ? "on" : "off"}
+ onClick={this.goToMain}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <p>
+ <Link to="/Main">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</Link>
+ </p>
+ </div>
+ </div>
+ </>
+ );
+ }
+}
+
+export default withRouter(Login);
+
+//๊ฐ์ฒด ๊ตฌ์กฐ ๋ถํด ํ ๋น
+
+//const { fontState} = this.state | JavaScript | ํ๋์ ํจ์๋ก ํฉ์ณ์ฃผ์ค์ ์๊ฒ ๋ค์-! ๐ |
@@ -0,0 +1,79 @@
+@import url('https://fonts.googleapis.com/css2?family=Lobster&display=swap');
+
+* {
+ box-sizing: border-box;
+}
+body{
+ background-color:#fafafa;
+}
+
+.login-wrap{
+ width:30%;
+ height:550px;
+ background-color:#fff;
+ border:3px solid rgba(221, 221, 221, 0.3);
+ margin:130px auto 0 auto;
+
+ h1{
+ width:80%;
+ height:50px;
+ font-size:55px;
+ font-family: 'Lobster', cursive;
+ padding-top:50px;
+ margin:0 auto 120px auto;
+ text-align: center;
+ }
+
+ .inner-wrap {
+ width:80%;
+ margin:auto;
+ height:300px;
+
+ input {
+ width:100%;
+ height:60px;
+ border-radius: 5px;
+ border:2px solid rgba(221, 221, 221, 0.2);
+ margin-bottom:10px;
+ padding:30px 10px;
+ font-size:18px;
+ color:#000;
+ cursor: pointer;
+ outline:none;
+ line-height: 30px;
+ }
+
+ .on {
+ background-color:#0094f6;
+ }
+
+ .off {
+ background-color:#0094f64b;
+ }
+
+ button {
+ width:100%;
+ height:50px;
+ margin-top:15px;
+ border:none;
+ background-color:#0094f64b;
+ border-radius: 8px;
+ color:#fff;
+ font-size:20px;
+ font-weight:600;
+ outline:none;
+ cursor:pointer;
+ }
+
+ p{
+ text-align:center;
+ margin-top:110px;
+
+ a{
+ color:#00376b;
+ font-size:16px;
+ text-decoration: none;
+ }
+ }
+ }
+} | Unknown | ํ์ค margin ์์ฑ์ผ๋ก ์ค์ฌ๋ณผ ์ ์๊ฒ ๋ค์-! ๐ |
@@ -0,0 +1,98 @@
+import { Component } from "react";
+import { Link, withRouter } from "react-router-dom";
+import "./Login.scss";
+
+class Login extends Component {
+ constructor() {
+ super();
+ this.state = {
+ id: "",
+ pw: "",
+ };
+ }
+
+ // localStorage.clear();
+ // localStorage.removeItem('key');
+ // localStorage.getItem('key');
+
+ //์ ์ฅ
+
+ //์กฐํ
+ // let getValue = localStorage.getItem('Token');
+ // console.log(getValue);
+ // localStorage
+
+ goToMain = () => {
+ fetch("http://10.58.2.229:8000/users/login", {
+ method: "POST",
+ body: JSON.stringify({
+ account: this.state.id,
+ password: this.state.pw,
+ // phone_number: "01034358181",
+ // name: "๊น๋ํ",
+ }),
+ })
+ .then((res) => res.json())
+ .then((result) => {
+ console.log(result);
+ if (result.MESSAGE === "SUCCESS") {
+ localStorage.setItem("Token", result.Token);
+ alert("๋ก๊ทธ์ธ์ฑ๊ณต!");
+ this.props.history.push("/maindh");
+ } else {
+ alert("๐คฌIT'S YOUR FAULT!๐คฌ");
+ }
+ });
+ };
+
+ handleInput = (event) => {
+ const { name, value } = event.target;
+ this.setState({
+ [name]: value,
+ });
+ };
+
+ render() {
+ const { id, pw } = this.state;
+ return (
+ <>
+ <div className="login-wrap">
+ <h1 className="title">Westagram</h1>
+ <div className="inner-wrap">
+ <input
+ className="id"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={this.handleInput}
+ value={id}
+ name="id"
+ />
+ <input
+ className="password"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={this.handleInput}
+ value={pw}
+ name="pw"
+ />
+ <button
+ className={id.includes("@") && pw.length >= 5 ? "on" : "off"}
+ onClick={this.goToMain}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <p>
+ <Link to="/Main">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</Link>
+ </p>
+ </div>
+ </div>
+ </>
+ );
+ }
+}
+
+export default withRouter(Login);
+
+//๊ฐ์ฒด ๊ตฌ์กฐ ๋ถํด ํ ๋น
+
+//const { fontState} = this.state | JavaScript | ๋ฐ๋ก ํจ์๋ฅผ ๋ง๋ค์ด์ฃผ์์ง ์์๋ ๋ ๊ฒ ๊ฐ์ต๋๋ค-!
```js
const { id, pw } = this.state;
<button className={id.includes('@') && pw.length >= 5 ? 'on' : 'off'} onClick={this.goToMain}>
``` |
@@ -0,0 +1,79 @@
+@import url('https://fonts.googleapis.com/css2?family=Lobster&display=swap');
+
+* {
+ box-sizing: border-box;
+}
+body{
+ background-color:#fafafa;
+}
+
+.login-wrap{
+ width:30%;
+ height:550px;
+ background-color:#fff;
+ border:3px solid rgba(221, 221, 221, 0.3);
+ margin:130px auto 0 auto;
+
+ h1{
+ width:80%;
+ height:50px;
+ font-size:55px;
+ font-family: 'Lobster', cursive;
+ padding-top:50px;
+ margin:0 auto 120px auto;
+ text-align: center;
+ }
+
+ .inner-wrap {
+ width:80%;
+ margin:auto;
+ height:300px;
+
+ input {
+ width:100%;
+ height:60px;
+ border-radius: 5px;
+ border:2px solid rgba(221, 221, 221, 0.2);
+ margin-bottom:10px;
+ padding:30px 10px;
+ font-size:18px;
+ color:#000;
+ cursor: pointer;
+ outline:none;
+ line-height: 30px;
+ }
+
+ .on {
+ background-color:#0094f6;
+ }
+
+ .off {
+ background-color:#0094f64b;
+ }
+
+ button {
+ width:100%;
+ height:50px;
+ margin-top:15px;
+ border:none;
+ background-color:#0094f64b;
+ border-radius: 8px;
+ color:#fff;
+ font-size:20px;
+ font-weight:600;
+ outline:none;
+ cursor:pointer;
+ }
+
+ p{
+ text-align:center;
+ margin-top:110px;
+
+ a{
+ color:#00376b;
+ font-size:16px;
+ text-decoration: none;
+ }
+ }
+ }
+} | Unknown | ์์ฃผ ์ฌ์ฉ๋๋ ์คํ์ผ ๊ฐ์๋ฐ, scss ๋ณ์๋ก ์ ์ธํด์ ์ฌ์ฉํด์ฃผ์๋ฉด ์ข์ ๋ฏ ํ๋ค์-! ๐ |
@@ -0,0 +1,63 @@
+import React from "react";
+import Story from "./Mainleft/Story";
+import Feed from "./Mainleft/Feed";
+import "./MainLeft.scss";
+// import { FaRedditAlien } from "react-icons/fa";
+
+class MainLeft extends React.Component {
+ state = {
+ feedList: [],
+ };
+
+ componentDidMount() {
+ fetch("/data/FeedData.json", {
+ method: "GET",
+ })
+ .then((res) => res.json())
+ .then((data) => {
+ this.setState({
+ feedList: data,
+ });
+ });
+ }
+
+ aaa = () => {
+ // console.log("aaa ํจ์ํธ์ถ");
+ fetch("http://10.58.2.229:8000/posts/post", {
+ method: "GET",
+ headers: {
+ Authorization: localStorage.getItem("Token"),
+ },
+ })
+ .then((res) => res.json())
+ .then((res) => {
+ this.setState({
+ feedList: res.RESULT,
+ });
+ console.log(res.RESULT);
+ });
+ };
+
+ render() {
+ const { feedList } = this.state;
+ return (
+ <div className="main-left">
+ {/* <button onClick={this.aaa}>click</button> */}
+ <Story />
+ {feedList.map((element) => {
+ return (
+ <Feed
+ id={element.id}
+ name={element.userId}
+ count={element.count}
+ img={element.img}
+ title={element.title}
+ />
+ );
+ })}
+ </div>
+ );
+ }
+}
+
+export default MainLeft; | JavaScript | import ์์ ์์ ํด์ฃผ์ธ์ ๐ ์ผ๋ฐ์ ์ธ convention์ ๋ฐ๋ฅด๋ ์ด์ ๋ ์์ง๋ง ์์๋ง ์ ์ง์ผ์ฃผ์
๋ ๊ฐ๋
์ฑ์ด ์ข์์ง๋๋ค. ์๋ ์์ ์ฐธ๊ณ ํด์ฃผ์ธ์.
- React โ Library(Package) โ Component โ ๋ณ์ / ์ด๋ฏธ์ง โ css ํ์ผ(scss ํ์ผ) |
@@ -0,0 +1,63 @@
+import React from "react";
+import Story from "./Mainleft/Story";
+import Feed from "./Mainleft/Feed";
+import "./MainLeft.scss";
+// import { FaRedditAlien } from "react-icons/fa";
+
+class MainLeft extends React.Component {
+ state = {
+ feedList: [],
+ };
+
+ componentDidMount() {
+ fetch("/data/FeedData.json", {
+ method: "GET",
+ })
+ .then((res) => res.json())
+ .then((data) => {
+ this.setState({
+ feedList: data,
+ });
+ });
+ }
+
+ aaa = () => {
+ // console.log("aaa ํจ์ํธ์ถ");
+ fetch("http://10.58.2.229:8000/posts/post", {
+ method: "GET",
+ headers: {
+ Authorization: localStorage.getItem("Token"),
+ },
+ })
+ .then((res) => res.json())
+ .then((res) => {
+ this.setState({
+ feedList: res.RESULT,
+ });
+ console.log(res.RESULT);
+ });
+ };
+
+ render() {
+ const { feedList } = this.state;
+ return (
+ <div className="main-left">
+ {/* <button onClick={this.aaa}>click</button> */}
+ <Story />
+ {feedList.map((element) => {
+ return (
+ <Feed
+ id={element.id}
+ name={element.userId}
+ count={element.count}
+ img={element.img}
+ title={element.title}
+ />
+ );
+ })}
+ </div>
+ );
+ }
+}
+
+export default MainLeft; | JavaScript | 1. ๋ก์ปฌ ํธ์คํธ์ ๊ฒฝ์ฐ ๋ฐ๋ก ์
๋ ฅ์ ํด์ฃผ์ง ์์ผ์
๋ ์๋์ผ๋ก ๋ค์ด๊ฐ๊ฒ ๋ฉ๋๋ค. ์ด๋ ๊ฒ ์๋ตํด์ ์์ฑ์ ํด์ฃผ์๋ ๊ฒ ๋ ์ข์ต๋๋ค. ์๋ํ๋ฉด, ํฌํธ ๋ฒํธ๊ฐ ๋ณ๊ฒฝ๋๋ ๋๊ฐ ์๊ฐ๋ณด๋ค ๋ง์๋ฐ, ์ด๋ ๊ฒ ์ง์ ์์ฑ์ ํด์ฃผ์ ๊ฒฝ์ฐ ํฌํธ ๋ฒํธ๋ฅผ ์ผ์ผ์ด ์์ ํด์ฃผ์์ผ ํฉ๋๋ค. ์๋ต์ ํด์ ์๋์ ๊ฐ์ด ์์ฑํ ๊ฒฝ์ฐ, ์๋์ผ๋ก ๋ณ๊ฒฝ๋ ํฌํธ๋ฒํธ๊ฐ ๋ค์ด๊ฐ๋๋ค ๐
```js
fetch(`/data/Story.json`)
.then(res => res.json())
.then( ... )
```
2. fetch ์ ๊ธฐ๋ณธ ๋ฉ์๋๋ GET ์
๋๋ค. ๋ฐ๋ผ์ { method: 'GET' } ๋ถ๋ถ๋ ์๋ตํด ์ฃผ์ค ์ ์์ต๋๋ค. |
@@ -1,17 +1,38 @@
import { AccessTokenGuard } from '#guards/access-token.guard.js';
import { IReviewController } from '#reviews/interfaces/review.controller.interface.js';
-import { Body, Controller, Delete, Get, Param, Post, UseGuards } from '@nestjs/common';
+import { Body, Controller, Delete, Get, Param, Post, Query, UseGuards } from '@nestjs/common';
import { ApiOperation } from '@nestjs/swagger';
import { ReviewService } from './review.service.js';
import { ReviewInputDTO } from './review.types.js';
+import { GetQueries } from '#types/queries.type.js';
+import { SortOrder } from '#types/options.type.js';
@Controller('reviews')
export class ReviewController implements IReviewController {
constructor(private readonly reviewService: ReviewService) {}
+ @Get('my')
+ @UseGuards(AccessTokenGuard)
+ @ApiOperation({ summary: '๋ด๊ฐ ์์ฑํ ๋ฆฌ๋ทฐ ์กฐํ' })
+ async getMyReviews(@Query() query: GetQueries) {
+ const { page = 1, pageSize = 10, orderBy = SortOrder.Recent, keyword = '' } = query;
+ const options = { page, pageSize, orderBy, keyword };
+
+ const { totalCount, list } = await this.reviewService.getMyReviews(options);
+
+ return { totalCount, list };
+ }
+
@Get(':driverId')
@ApiOperation({ summary: '๊ธฐ์ฌ ๋ฆฌ๋ทฐ ์กฐํ' })
- async getReviews() {}
+ async getDriverReviews(@Param('driverId') driverId: string, @Query() query: GetQueries) {
+ const { page = 1, pageSize = 10, orderBy = SortOrder.Recent, keyword = '' } = query;
+ const options = { page, pageSize, orderBy, keyword };
+
+ const { totalCount, list } = await this.reviewService.getDriverReviews(driverId, options);
+
+ return { totalCount, list };
+ }
@Post(':driverId')
@UseGuards(AccessTokenGuard)
@@ -22,11 +43,21 @@ export class ReviewController implements IReviewController {
return review;
}
- @Post(':reviewId')
+ @Post('patch/:reviewId')
+ @UseGuards(AccessTokenGuard)
@ApiOperation({ summary: '๋ฆฌ๋ทฐ ์์ ' })
- async patchReview() {}
+ async patchReview(@Param('reviewId') reviewId: string, @Body() body: Partial<ReviewInputDTO>) {
+ const review = await this.reviewService.patchReview(reviewId, body);
+
+ return review;
+ }
@Delete(':reviewId')
+ @UseGuards(AccessTokenGuard)
@ApiOperation({ summary: '๋ฆฌ๋ทฐ ์ญ์ ' })
- async deleteReview() {}
+ async deleteReview(@Param('reviewId') reviewId: string) {
+ const review = await this.reviewService.deleteReview(reviewId);
+
+ return review;
+ }
} | TypeScript | userId๋ ์ก์ธ์ค ํ ํฐ์์ ๊ฐ์ ธ์ฌ ์ ์์ผ๋ ํ๋ผ๋ฏธํฐ์์ ๊ฐ์ ธ์ฌ ํ์๋ ์์ด๋ณด์ฌ์! |
@@ -1,17 +1,38 @@
import { AccessTokenGuard } from '#guards/access-token.guard.js';
import { IReviewController } from '#reviews/interfaces/review.controller.interface.js';
-import { Body, Controller, Delete, Get, Param, Post, UseGuards } from '@nestjs/common';
+import { Body, Controller, Delete, Get, Param, Post, Query, UseGuards } from '@nestjs/common';
import { ApiOperation } from '@nestjs/swagger';
import { ReviewService } from './review.service.js';
import { ReviewInputDTO } from './review.types.js';
+import { GetQueries } from '#types/queries.type.js';
+import { SortOrder } from '#types/options.type.js';
@Controller('reviews')
export class ReviewController implements IReviewController {
constructor(private readonly reviewService: ReviewService) {}
+ @Get('my')
+ @UseGuards(AccessTokenGuard)
+ @ApiOperation({ summary: '๋ด๊ฐ ์์ฑํ ๋ฆฌ๋ทฐ ์กฐํ' })
+ async getMyReviews(@Query() query: GetQueries) {
+ const { page = 1, pageSize = 10, orderBy = SortOrder.Recent, keyword = '' } = query;
+ const options = { page, pageSize, orderBy, keyword };
+
+ const { totalCount, list } = await this.reviewService.getMyReviews(options);
+
+ return { totalCount, list };
+ }
+
@Get(':driverId')
@ApiOperation({ summary: '๊ธฐ์ฌ ๋ฆฌ๋ทฐ ์กฐํ' })
- async getReviews() {}
+ async getDriverReviews(@Param('driverId') driverId: string, @Query() query: GetQueries) {
+ const { page = 1, pageSize = 10, orderBy = SortOrder.Recent, keyword = '' } = query;
+ const options = { page, pageSize, orderBy, keyword };
+
+ const { totalCount, list } = await this.reviewService.getDriverReviews(driverId, options);
+
+ return { totalCount, list };
+ }
@Post(':driverId')
@UseGuards(AccessTokenGuard)
@@ -22,11 +43,21 @@ export class ReviewController implements IReviewController {
return review;
}
- @Post(':reviewId')
+ @Post('patch/:reviewId')
+ @UseGuards(AccessTokenGuard)
@ApiOperation({ summary: '๋ฆฌ๋ทฐ ์์ ' })
- async patchReview() {}
+ async patchReview(@Param('reviewId') reviewId: string, @Body() body: Partial<ReviewInputDTO>) {
+ const review = await this.reviewService.patchReview(reviewId, body);
+
+ return review;
+ }
@Delete(':reviewId')
+ @UseGuards(AccessTokenGuard)
@ApiOperation({ summary: '๋ฆฌ๋ทฐ ์ญ์ ' })
- async deleteReview() {}
+ async deleteReview(@Param('reviewId') reviewId: string) {
+ const review = await this.reviewService.deleteReview(reviewId);
+
+ return review;
+ }
} | TypeScript | ๊ธฐ์ฌ ๋ฆฌ๋ทฐ ์กฐํ๋ ๊ธฐ์ฌ ์์ธ ์กฐํ์์ ํ๊ฒ ๋ ๊ฒ์ผ๋ก ๋ณด์ด๋๋ฐ
๊ธฐ์ฌ ์์ธ ์กฐํ๋ ๋นํ์๋ ์ด๋ ๊ฐ๋ฅํ ํ์ด์ง์
๋๋ค! |
@@ -1,7 +1,7 @@
import { PrismaService } from '#global/prisma.service.js';
import { IReviewRepository } from '#reviews/interfaces/review.repository.interface.js';
import { ReviewInputDTO } from '#reviews/review.types.js';
-import { FindOptions } from '#types/options.type.js';
+import { FindOptions, SortOrder } from '#types/options.type.js';
import { Injectable } from '@nestjs/common';
@Injectable()
@@ -11,7 +11,67 @@ export class ReviewRepository implements IReviewRepository {
this.review = prisma.review;
}
- async findMany(options: FindOptions) {}
+ async totalCount(id: string, type: 'user' | 'driver') {
+ const whereCondition = type === 'user' ? { ownerId: id } : type === 'driver' ? { driverId: id } : {};
+ const totalCount = await this.review.count({ where: whereCondition });
+
+ return totalCount;
+ }
+
+ async findManyMyReviews(userId: string, options: FindOptions) {
+ console.log('findManyMyReviews called with:', userId, options);
+ const { page, pageSize, orderBy } = options;
+
+ const sort = orderBy === SortOrder.Recent ? { createdAt: 'desc' } : { createdAt: 'asc' };
+
+ const list = await this.review.findMany({
+ where: { ownerId: userId },
+ orderBy: sort,
+ skip: (page - 1) * pageSize,
+ take: pageSize,
+ include: {
+ driver: { select: { name: true, image: true } },
+ owner: {
+ select: {
+ moveInfos: {
+ where: { progress: 'COMPLETE' },
+ select: {
+ type: true,
+ date: true,
+ confirmedEstimation: {
+ select: {
+ price: true,
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ });
+
+ return list;
+ }
+
+ async findManyDriverReviews(driverId: string, options: FindOptions) {
+ const { page, pageSize, orderBy } = options;
+
+ const sort = orderBy === SortOrder.Recent ? { createdAt: 'desc' } : { createdAt: 'asc' };
+
+ const list = await this.review.findMany({
+ where: { driverId },
+ orderBy: sort,
+ skip: (page - 1) * pageSize,
+ take: pageSize,
+ include: {
+ owner: {
+ select: { name: true },
+ },
+ },
+ });
+
+ return list;
+ }
async findById(id: string) {}
@@ -21,7 +81,15 @@ export class ReviewRepository implements IReviewRepository {
return review;
}
- async update(id: string, data: Partial<ReviewInputDTO>) {}
+ async update(id: string, data: Partial<ReviewInputDTO>) {
+ const review = await this.review.update({ where: { id }, data });
- async delete(id: string) {}
+ return review;
+ }
+
+ async delete(id: string) {
+ const review = await this.review.delete({ where: { id } });
+
+ return review;
+ }
} | TypeScript | repository์ ํ ๋ฉ์๋๋ ํ๋์ ๊ฒฐ๊ณผ๋ง์ ๋ด๋ณด๋ด๋ ๊ฒ์ด ์ข์ต๋๋ค.
count ๋ฉ์๋๋ findMany์ ๋ฐ๋ก ์์ฑํ๊ณ , service์์ ๊ฒฐ๊ณผ๋ฅผ ํฉ์ณ์ ๋ด๋ณด๋ด๋ ๊ฒ์ด ๋ ๋ฐ๋์งํ ๊ฒ ๊ฐ์์! |
@@ -1,7 +1,7 @@
import { PrismaService } from '#global/prisma.service.js';
import { IReviewRepository } from '#reviews/interfaces/review.repository.interface.js';
import { ReviewInputDTO } from '#reviews/review.types.js';
-import { FindOptions } from '#types/options.type.js';
+import { FindOptions, SortOrder } from '#types/options.type.js';
import { Injectable } from '@nestjs/common';
@Injectable()
@@ -11,7 +11,67 @@ export class ReviewRepository implements IReviewRepository {
this.review = prisma.review;
}
- async findMany(options: FindOptions) {}
+ async totalCount(id: string, type: 'user' | 'driver') {
+ const whereCondition = type === 'user' ? { ownerId: id } : type === 'driver' ? { driverId: id } : {};
+ const totalCount = await this.review.count({ where: whereCondition });
+
+ return totalCount;
+ }
+
+ async findManyMyReviews(userId: string, options: FindOptions) {
+ console.log('findManyMyReviews called with:', userId, options);
+ const { page, pageSize, orderBy } = options;
+
+ const sort = orderBy === SortOrder.Recent ? { createdAt: 'desc' } : { createdAt: 'asc' };
+
+ const list = await this.review.findMany({
+ where: { ownerId: userId },
+ orderBy: sort,
+ skip: (page - 1) * pageSize,
+ take: pageSize,
+ include: {
+ driver: { select: { name: true, image: true } },
+ owner: {
+ select: {
+ moveInfos: {
+ where: { progress: 'COMPLETE' },
+ select: {
+ type: true,
+ date: true,
+ confirmedEstimation: {
+ select: {
+ price: true,
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ });
+
+ return list;
+ }
+
+ async findManyDriverReviews(driverId: string, options: FindOptions) {
+ const { page, pageSize, orderBy } = options;
+
+ const sort = orderBy === SortOrder.Recent ? { createdAt: 'desc' } : { createdAt: 'asc' };
+
+ const list = await this.review.findMany({
+ where: { driverId },
+ orderBy: sort,
+ skip: (page - 1) * pageSize,
+ take: pageSize,
+ include: {
+ owner: {
+ select: { name: true },
+ },
+ },
+ });
+
+ return list;
+ }
async findById(id: string) {}
@@ -21,7 +81,15 @@ export class ReviewRepository implements IReviewRepository {
return review;
}
- async update(id: string, data: Partial<ReviewInputDTO>) {}
+ async update(id: string, data: Partial<ReviewInputDTO>) {
+ const review = await this.review.update({ where: { id }, data });
- async delete(id: string) {}
+ return review;
+ }
+
+ async delete(id: string) {
+ const review = await this.review.delete({ where: { id } });
+
+ return review;
+ }
} | TypeScript | ์์ ๋ง์ฐฌ๊ฐ์ง |
@@ -0,0 +1,23 @@
+public class Calculator {
+
+ public int add(int fir, int sec) {
+ return fir + sec;
+ }
+
+ public int subtract(int fir, int sec) {
+ return fir - sec;
+ }
+
+ public int multiply(int fir, int sec) {
+ return fir * sec;
+ }
+
+ public int divide(int fir, int sec) {
+ if (sec == 0) {
+ throw new ArithmeticException("Divide by zero");
+ }
+ return fir / sec;
+ }
+
+
+} | Java | ์์ธ์ฒ๋ฆฌ ๐ |
@@ -0,0 +1,40 @@
+public class StringCalculator {
+
+ public int add(String string) {
+ if (string.isEmpty()) {
+ return 0;
+ }
+
+
+ String[] numbers = string.split(",|:");
+ return sum(numbers);
+ }
+
+ private int sum(String[] numbers) {
+ int total = 0;
+
+ for (String number : numbers) {
+ int num = checkNumber(number);
+ total += num;
+ }
+
+ return total;
+ }
+
+ private int checkNumber(String number) {
+ if (number.isEmpty()) {
+ return 0;
+ }
+
+ // ์ซ์๊ฐ ์๋ ๊ฒฝ์ฐ RuntimeException ๋ฐ์
+ try {
+ int num = Integer.parseInt(number);
+ if (num < 0) {
+ throw new RuntimeException("์์๊ฐ ํฌํจ๋์ด ์์ต๋๋ค.");
+ }
+ return num;
+ } catch (NumberFormatException e) {
+ throw new RuntimeException("์๋ชป๋ ์
๋ ฅ์
๋๋ค.");
+ }
+ }
+}
\ No newline at end of file | Java | ๋ณ์๋ช
์ string์ผ๋ก ํ๊ธฐ๋ณด๋ค๋ ์ข ๋ ๋์ ๋ณ์๋ช
์ผ๋ก ์ง๋ ๊ฒ์ด ๊ฐ๋
์ฑ ์ธก๋ฉด์์ ์ข์๋ณด์ฌ์! |
@@ -0,0 +1,40 @@
+public class StringCalculator {
+
+ public int add(String string) {
+ if (string.isEmpty()) {
+ return 0;
+ }
+
+
+ String[] numbers = string.split(",|:");
+ return sum(numbers);
+ }
+
+ private int sum(String[] numbers) {
+ int total = 0;
+
+ for (String number : numbers) {
+ int num = checkNumber(number);
+ total += num;
+ }
+
+ return total;
+ }
+
+ private int checkNumber(String number) {
+ if (number.isEmpty()) {
+ return 0;
+ }
+
+ // ์ซ์๊ฐ ์๋ ๊ฒฝ์ฐ RuntimeException ๋ฐ์
+ try {
+ int num = Integer.parseInt(number);
+ if (num < 0) {
+ throw new RuntimeException("์์๊ฐ ํฌํจ๋์ด ์์ต๋๋ค.");
+ }
+ return num;
+ } catch (NumberFormatException e) {
+ throw new RuntimeException("์๋ชป๋ ์
๋ ฅ์
๋๋ค.");
+ }
+ }
+}
\ No newline at end of file | Java | 4๋ฒ์งธ ์ค์ ์ฝ๋์ ์ค๋ณต๋๋ ๋ถ๋ถ์ผ๋ก ๋ณด์ด๋ค์.
๋ฐ๋ก ๋ชจ๋ํํด์ ํจ์๋ก ๋ง๋ค์ด์ฃผ๋ฉด ๊ฐ๋
์ฑ๋ ์ข์์ง๊ณ ์ฌ์ฌ์ฉ์ฑ๋ ๋์์ ธ์. |
@@ -0,0 +1,15 @@
+public class CalculatorTest {
+
+ public static void main(String[] args) {
+
+ Calculator calc = new Calculator();
+
+ System.out.println(calc.add(10, 20));
+ System.out.println(calc.add(10, -5));
+ System.out.println(calc.subtract(10, 20));
+ System.out.println(calc.multiply(10, 20));
+ System.out.println(calc.divide(10, 5));
+
+
+ }
+} | Java | ํ
์คํธ์ฝ๋๋ก ์์ฑ๋ ๋ถ๋ถ์ด ์๋ ๊ฒ ๊ฐ์์. |
@@ -0,0 +1,46 @@
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.*;
+
+public class StringCalculatorTest {
+
+ private final StringCalculator calculator = new StringCalculator();
+
+ @Test
+ public void testEmptyString() {
+ assertEquals(0, calculator.add(""));
+ }
+
+
+ @Test
+ public void testNumbers() {
+ assertEquals(3, calculator.add("1,2"));
+ assertEquals(7, calculator.add("3:4"));
+ assertEquals(6, calculator.add("1,2,3"));
+ assertEquals(10, calculator.add("4:2:4"));
+ assertEquals(15, calculator.add("1,2:3,4,5"));
+ }
+
+ @Test
+ public void testNegativeNumber() {
+ RuntimeException exception = assertThrows(RuntimeException.class, () -> {
+ calculator.add("1,-2");
+ });
+ assertEquals("์์๊ฐ ํฌํจ๋์ด ์์ต๋๋ค.", exception.getMessage());
+ }
+
+ @Test
+ public void testInvalidString() {
+ RuntimeException exception = assertThrows(RuntimeException.class, () -> {
+ calculator.add("1,a");
+ });
+ assertEquals("์๋ชป๋ ์
๋ ฅ์
๋๋ค.", exception.getMessage());
+ }
+
+ @Test
+ public void testMixedDelimiters() {
+ assertEquals(10, calculator.add("1,2:3,4"));
+ assertEquals(15, calculator.add("1,2:3,4,5"));
+ }
+}
+
+ | Java | ํ๋์ ํ
์คํธ๋ ํ๋์ ๋ํด์๋ง ํ
์คํธํ๋ฉด ๋ ์ข์ ๊ฒ ๊ฐ์์. |
@@ -0,0 +1,65 @@
+import History from "@models/History";
+import {
+ getHistoryItemTemplate,
+ NO_HISTORY_TEMPLATE,
+} from "@templates/history";
+
+export default class HistoryController {
+ constructor(historyContainer) {
+ this.historyContainer = historyContainer;
+ this.numberOfHistory = 0;
+ this._init();
+ }
+ _init() {
+ this._initEvent();
+ this._initHistory();
+ }
+ _initEvent() {
+ this.historyContainer.addEventListener("click", (event) => {
+ if (event.target.classList.contains("button__delete")) {
+ const toDeleteEl = event.target.parentElement;
+ this.deleteHistory(toDeleteEl);
+ }
+ });
+ }
+ _initHistory() {
+ const history = History.getAll();
+ this.numberOfHistory = history.length;
+
+ if (this.numberOfHistory === 0) {
+ this.historyContainer.innerHTML = NO_HISTORY_TEMPLATE;
+ return;
+ }
+
+ const historyTemplates = history
+ .map(({ value, id }) => getHistoryItemTemplate(value, id))
+ .join("");
+ this.historyContainer.innerHTML = historyTemplates;
+ }
+ addHistory(searchValue) {
+ const historyId = History.add(searchValue);
+ if (!historyId) {
+ return;
+ }
+
+ const listItemEl = getHistoryItemTemplate(searchValue, historyId);
+
+ this.numberOfHistory++;
+ if (this.numberOfHistory === 1) {
+ this.historyContainer.innerHTML = listItemEl;
+ return;
+ }
+
+ this.historyContainer.insertAdjacentHTML("beforeend", listItemEl);
+ }
+ deleteHistory(historyEl) {
+ const id = historyEl.id;
+ this.historyContainer.removeChild(historyEl);
+ History.delete(id);
+ this.numberOfHistory--;
+
+ if (this.numberOfHistory === 0) {
+ this.historyContainer.innerHTML = NO_HISTORY_TEMPLATE;
+ }
+ }
+} | JavaScript | ๐ ๐ ๋ฆฌ๋ทฐ๋๋ฆฐ ๋ถ๋ถ ๋ฐ์ํด์ฃผ์
จ๋ค์~! ํ์คํ ํ
ํ๋ฆฟ์ ์์๋ก ๋ถ๋ฆฌํ๋๊น ๊ฐ๋
์ฑ์ด ์ข์์ก๋ค์ :) |
@@ -19,41 +19,56 @@ export default class Repo {
}) {
this.id = id;
this.name = name;
- this.full_name = full_name;
+ this.fullName = full_name;
this.owner = owner;
- this.html_url = html_url;
+ this.htmlUrl = html_url;
this.description = description;
- this.stargazers_count = stargazers_count;
- this.watchers_count = watchers_count;
- this.forks_count = forks_count;
+ this.stargazersCount = stargazers_count;
+ this.watchersCount = watchers_count;
+ this.forksCount = forks_count;
this.forks = forks;
- this.created_at = created_at;
- this.updated_at = updated_at;
- this.clone_url = clone_url;
+ this.createdAt = created_at;
+ this.updatedAt = updated_at;
+ this.cloneUrl = clone_url;
this.language = language;
this.watchers = watchers;
this.visibility = visibility;
}
render() {
return `
- <div class="col-12 col-sm-6 mb-4" id="repo-${this.id}">
+ <div class="col-12 col-sm-6 mb-4 px-2" id="repo-${this.id}">
<div class="card border-secondary h-100" >
- <div class="card-body">
- <div class="d-flex align-items-center flex-wrap">
- <h5 class="mb-2 mr-2">
- ${this.name}
- </h5>
- <span class="mb-2 badge bg-light">
+ <div class="card-body d-flex flex-column justify-content-between">
+ <div class="d-flex align-items-center flex-wrap" >
+ <a class="text-info d-flex align-items-center flex-wrap mb-2 mr-2" href="${
+ this.htmlUrl
+ }" target="_blank">
+ <h5>
+ ${this.name}
+ </h5>
+ </a>
+ <span class="mb-2 badge bg-light mr-2">
${this.visibility}
</span>
+ <span class="mb-2 d-flex align-items-center">
+ <img alt="๋ ํฌ์งํ ๋ฆฌ ์คํ ์์ด์ฝ" src="${
+ this.stargazersCount > 0 ? "star_filled.svg" : "star.svg"
+ }" height="16"/>
+ ${this.stargazersCount}
+ </span>
</div>
<p class="card-text">${this.description ?? ""}</p>
<div>
- <span class="text-secondary">
+ <span class="text-secondary mr-2">
${this.language ?? ""}
</span>
+ <span class="text-secondary mr-2">
+ <img src="fork.svg" alt="ํฌํฌ ์์ด์ฝ" height="18"/>
+ ${this.forks}
+ </span>
<span class="text-secondary">
- ${this.forks > 0 ? this.forks : ""}
+ <img src="watch.svg" alt="์์น ์์ด์ฝ" height="18"/>
+ ${this.watchersCount}
</span>
</div>
</div> | JavaScript | `models/User.js` ์์ ์ฌ์ฉ๋๋ ์ด๋ฏธ์ง์๋ alt๊ฐ ํ๊ธ๋ก ๋์ด์๋๋ฐ ์ด๋ถ๋ถ์ ์์ด๋ก ๋์ด์๋ค์! ํต์ผ์์ผ์ฃผ๋ ๊ฒ๋ ์ข์ ๊ฒ ๊ฐ์์~ |
@@ -1,83 +1,112 @@
import GithubApiController from "@controllers/githubController";
import User from "@models/User";
+import {
+ NO_SEARCH_RESULT_TEMPLATE,
+ SEARCH_LOADING_TEMPLATE,
+ getReposTemplate,
+ NO_REPOS_TEMPLATE,
+} from "@templates/search";
+import { SPINNER_TEMPLATE } from "@templates/spinner";
+import { NUMBER_OF_REPOS } from "@constants/search";
const searchResultContainer = document.body.querySelector(".search-result");
export default class SearchController {
- constructor(inputEl, submitEl) {
+ constructor(inputEl, submitEl, historyController) {
this.inputEl = inputEl;
this.submitEl = submitEl;
this.fetcher = new GithubApiController();
+ this.historyController = historyController;
this.init();
}
init() {
this.inputEl.addEventListener("keypress", (event) => {
- if (event.code === 'Enter') {
+ if (event.code === "Enter") {
this.search(this.inputEl.value);
}
});
this.submitEl.addEventListener("click", () => {
this.search(this.inputEl.value);
});
+
+ this.historyController.historyContainer.addEventListener(
+ "click",
+ (event) => {
+ if (
+ event.target.classList.contains("list-group-item") &&
+ !event.target.classList.contains("button__delete")
+ ) {
+ const [searchValue] = event.target.textContent.trim().split("\n");
+ this.search(searchValue);
+ }
+ }
+ );
}
async search(searchValue) {
const renderUser = (user) => {
const userResult = searchResultContainer.querySelector("#user-result");
userResult.id = user.id;
- userResult.innerHTML = user.render();
+ user.render(userResult);
};
-
- const renderRepos = (repos) => {
+ const renderNoUserInfo = () => {
+ const userResult = searchResultContainer.querySelector("#user-result");
+ userResult.innerHTML = NO_SEARCH_RESULT_TEMPLATE;
+ };
+ const createRepoResultContainerEl = () => {
const repoResult = document.createElement("div");
- repoResult.id = "#repos-result";
+ repoResult.id = "repo-result";
repoResult.className = "bs-component";
+ return repoResult;
+ };
+ const renderRepos = (repos, numberOfRepos) => {
+ const repoResult = createRepoResultContainerEl();
+ repoResult.innerHTML = getReposTemplate(repos, numberOfRepos);
- repoResult.innerHTML = `
- <div class="container">
- <div class="row">
- ${repos
- .slice(0, 5)
- .map((repo) => repo.render())
- .join("\n")}
- </div>
- </div>
- `;
searchResultContainer.appendChild(repoResult);
};
+ const renderNoRepos = () => {
+ const repoResult = createRepoResultContainerEl();
+ repoResult.innerHTML = NO_REPOS_TEMPLATE;
+
+ searchResultContainer.appendChild(repoResult);
+ };
+ const createLoadingElement = () => {
+ const element = document.createElement("div");
+ element.className = "card-body d-flex align-items-center";
+ element.innerHTML = SPINNER_TEMPLATE;
+ return element;
+ };
const trimmedValue = searchValue.trim();
if (!trimmedValue) {
alert("๊ฒ์์ด๋ฅผ ์
๋ ฅํด์ฃผ์ธ์");
return;
}
-
- searchResultContainer.innerHTML = `
- <div class="card my-3">
- <h4 class="card-header">๊ฒ์๊ฒฐ๊ณผ</h4>
- <div id="user-result" class="card-body d-flex align-items-center">
- <p class="text-center container-fluid">
- ๊ฒ์์ค
- </p>
- </div>
- </div>
- `;
+ this.historyController.addHistory(trimmedValue);
+ searchResultContainer.innerHTML = SEARCH_LOADING_TEMPLATE;
const userInfo = await this.fetcher.getUser(trimmedValue);
if (!userInfo) {
- const userResult = searchResultContainer.querySelector("#user-result");
- userResult.innerHTML = `
- <p class="text-center container-fluid">
- ๊ฒ์ ๊ฒฐ๊ณผ๊ฐ ์์ต๋๋ค.
- </p>
- `;
+ renderNoUserInfo();
return;
}
const user = new User(userInfo);
renderUser(user);
- user.setRepos(await this.fetcher.getRepos(user));
- renderRepos(user.repos);
+ const loadingEl = createLoadingElement();
+
+ searchResultContainer.appendChild(loadingEl);
+ const repos = await this.fetcher.getRepos(user);
+ searchResultContainer.removeChild(loadingEl);
+
+ if (repos.length === 0) {
+ renderNoRepos();
+ return;
+ }
+
+ user.setRepos(repos);
+ renderRepos(user.repos, NUMBER_OF_REPOS);
}
} | JavaScript | ๊ฐ์ธ์ ์ธ ์๊ฐ์ผ๋ก ํจ์๋ช
์ด `getXXXEl`๋ก ๋์ด์์ด์ ๊ธฐ์กด์ ์กด์ฌํ๋ ์๋ ๋จผํธ๋ฅผ ์ฟผ๋ฆฌ์
๋ ํธ๋ก ๊ฐ์ ธ์ค๋ ๊ฒ ๊ฐ์ ๋๋์ด ์๋๋ฐ์, ์๋ก์ด ์๋ ๋จผํธ๋ฅผ ๋ง๋ค์ด์ ๋ฐํํ๋ ์ญํ ์ ํด์ฃผ๊ณ ์์ผ๋ `get` ๋์ `create`๋ผ๋ ์ด๋ฆ์ผ๋ก ๋ค์ด๋ฐํด๋ ์ข์ ๊ฒ ๊ฐ๋ค์ :) |
@@ -1,83 +1,112 @@
import GithubApiController from "@controllers/githubController";
import User from "@models/User";
+import {
+ NO_SEARCH_RESULT_TEMPLATE,
+ SEARCH_LOADING_TEMPLATE,
+ getReposTemplate,
+ NO_REPOS_TEMPLATE,
+} from "@templates/search";
+import { SPINNER_TEMPLATE } from "@templates/spinner";
+import { NUMBER_OF_REPOS } from "@constants/search";
const searchResultContainer = document.body.querySelector(".search-result");
export default class SearchController {
- constructor(inputEl, submitEl) {
+ constructor(inputEl, submitEl, historyController) {
this.inputEl = inputEl;
this.submitEl = submitEl;
this.fetcher = new GithubApiController();
+ this.historyController = historyController;
this.init();
}
init() {
this.inputEl.addEventListener("keypress", (event) => {
- if (event.code === 'Enter') {
+ if (event.code === "Enter") {
this.search(this.inputEl.value);
}
});
this.submitEl.addEventListener("click", () => {
this.search(this.inputEl.value);
});
+
+ this.historyController.historyContainer.addEventListener(
+ "click",
+ (event) => {
+ if (
+ event.target.classList.contains("list-group-item") &&
+ !event.target.classList.contains("button__delete")
+ ) {
+ const [searchValue] = event.target.textContent.trim().split("\n");
+ this.search(searchValue);
+ }
+ }
+ );
}
async search(searchValue) {
const renderUser = (user) => {
const userResult = searchResultContainer.querySelector("#user-result");
userResult.id = user.id;
- userResult.innerHTML = user.render();
+ user.render(userResult);
};
-
- const renderRepos = (repos) => {
+ const renderNoUserInfo = () => {
+ const userResult = searchResultContainer.querySelector("#user-result");
+ userResult.innerHTML = NO_SEARCH_RESULT_TEMPLATE;
+ };
+ const createRepoResultContainerEl = () => {
const repoResult = document.createElement("div");
- repoResult.id = "#repos-result";
+ repoResult.id = "repo-result";
repoResult.className = "bs-component";
+ return repoResult;
+ };
+ const renderRepos = (repos, numberOfRepos) => {
+ const repoResult = createRepoResultContainerEl();
+ repoResult.innerHTML = getReposTemplate(repos, numberOfRepos);
- repoResult.innerHTML = `
- <div class="container">
- <div class="row">
- ${repos
- .slice(0, 5)
- .map((repo) => repo.render())
- .join("\n")}
- </div>
- </div>
- `;
searchResultContainer.appendChild(repoResult);
};
+ const renderNoRepos = () => {
+ const repoResult = createRepoResultContainerEl();
+ repoResult.innerHTML = NO_REPOS_TEMPLATE;
+
+ searchResultContainer.appendChild(repoResult);
+ };
+ const createLoadingElement = () => {
+ const element = document.createElement("div");
+ element.className = "card-body d-flex align-items-center";
+ element.innerHTML = SPINNER_TEMPLATE;
+ return element;
+ };
const trimmedValue = searchValue.trim();
if (!trimmedValue) {
alert("๊ฒ์์ด๋ฅผ ์
๋ ฅํด์ฃผ์ธ์");
return;
}
-
- searchResultContainer.innerHTML = `
- <div class="card my-3">
- <h4 class="card-header">๊ฒ์๊ฒฐ๊ณผ</h4>
- <div id="user-result" class="card-body d-flex align-items-center">
- <p class="text-center container-fluid">
- ๊ฒ์์ค
- </p>
- </div>
- </div>
- `;
+ this.historyController.addHistory(trimmedValue);
+ searchResultContainer.innerHTML = SEARCH_LOADING_TEMPLATE;
const userInfo = await this.fetcher.getUser(trimmedValue);
if (!userInfo) {
- const userResult = searchResultContainer.querySelector("#user-result");
- userResult.innerHTML = `
- <p class="text-center container-fluid">
- ๊ฒ์ ๊ฒฐ๊ณผ๊ฐ ์์ต๋๋ค.
- </p>
- `;
+ renderNoUserInfo();
return;
}
const user = new User(userInfo);
renderUser(user);
- user.setRepos(await this.fetcher.getRepos(user));
- renderRepos(user.repos);
+ const loadingEl = createLoadingElement();
+
+ searchResultContainer.appendChild(loadingEl);
+ const repos = await this.fetcher.getRepos(user);
+ searchResultContainer.removeChild(loadingEl);
+
+ if (repos.length === 0) {
+ renderNoRepos();
+ return;
+ }
+
+ user.setRepos(repos);
+ renderRepos(user.repos, NUMBER_OF_REPOS);
}
} | JavaScript | ์ง๋๋ฒ์ `keyCode`๋ก ์ฒ๋ฆฌํ์ ๋ ๋ณด๋ค ์ด๋ค ํค๋ฅผ ๋๋ ์ ๋ ๋์ํ๋ ๋ก์ง์ธ์ง ํ์
ํ๊ธฐ๊ฐ ์ฌ์์ก๋ค์ ๐ |
@@ -0,0 +1,65 @@
+import History from "@models/History";
+import {
+ getHistoryItemTemplate,
+ NO_HISTORY_TEMPLATE,
+} from "@templates/history";
+
+export default class HistoryController {
+ constructor(historyContainer) {
+ this.historyContainer = historyContainer;
+ this.numberOfHistory = 0;
+ this._init();
+ }
+ _init() {
+ this._initEvent();
+ this._initHistory();
+ }
+ _initEvent() {
+ this.historyContainer.addEventListener("click", (event) => {
+ if (event.target.classList.contains("button__delete")) {
+ const toDeleteEl = event.target.parentElement;
+ this.deleteHistory(toDeleteEl);
+ }
+ });
+ }
+ _initHistory() {
+ const history = History.getAll();
+ this.numberOfHistory = history.length;
+
+ if (this.numberOfHistory === 0) {
+ this.historyContainer.innerHTML = NO_HISTORY_TEMPLATE;
+ return;
+ }
+
+ const historyTemplates = history
+ .map(({ value, id }) => getHistoryItemTemplate(value, id))
+ .join("");
+ this.historyContainer.innerHTML = historyTemplates;
+ }
+ addHistory(searchValue) {
+ const historyId = History.add(searchValue);
+ if (!historyId) {
+ return;
+ }
+
+ const listItemEl = getHistoryItemTemplate(searchValue, historyId);
+
+ this.numberOfHistory++;
+ if (this.numberOfHistory === 1) {
+ this.historyContainer.innerHTML = listItemEl;
+ return;
+ }
+
+ this.historyContainer.insertAdjacentHTML("beforeend", listItemEl);
+ }
+ deleteHistory(historyEl) {
+ const id = historyEl.id;
+ this.historyContainer.removeChild(historyEl);
+ History.delete(id);
+ this.numberOfHistory--;
+
+ if (this.numberOfHistory === 0) {
+ this.historyContainer.innerHTML = NO_HISTORY_TEMPLATE;
+ }
+ }
+} | JavaScript | ์ง์ด์ฃผ์ ๋ณ์๋ช
๋ ์ถฉ๋ถํ ์๋ฏธํ์
์ด ์๋๋๋ฐ์! ํน์ ์ข๋ ๊ฐ๊ฒฐํ ๋ณ์๋ช
์ ์ํ์ ๋ค๋ฉด `historyCount` ๋ก ๋ค์ด๋ฐํ๋ ๋ฐฉ๋ฒ๋ ์์ ๊ฒ ๊ฐ์ต๋๋ค ใ
ใ
|
@@ -1,11 +1,13 @@
import Repo from "@models/Repo";
+import { getDateDiff } from "@utils/dateUtils";
export default class User {
constructor({
id,
avatar_url,
created_at,
email,
+ bio,
followers,
following,
login,
@@ -22,57 +24,114 @@ export default class User {
this.id = id;
this.avartar = avatar_url;
this.name = name;
+ this.bio = bio;
this.followers = followers;
this.following = following;
this.loginId = login;
this.email = email;
- this.public_repos = public_repos;
- this.public_gists = public_gists;
- this.created_at = created_at;
- this.html_url = html_url;
+ this.publicRepos = public_repos;
+ this.publicGists = public_gists;
+ this.createdAt = created_at;
+ this.htmlUrl = html_url;
this.organizations_url = organizations_url;
- this.starred_url = starred_url;
+ this.starredUrl = starred_url;
this.subscriptions_url = subscriptions_url;
- this.repos_url = repos_url;
- this.updated_at = updated_at;
+ this.reposUrl = repos_url;
+ this.updatedAt = updated_at;
this.repos = [];
}
- render() {
+ _getCreatedDateInfo() {
+ const today = new Date();
+ const createdDate = new Date(this.createdAt);
+ const monthDiff = getDateDiff(today, createdDate, "month");
+
+ if (monthDiff === 0) {
+ const dayDiff = getDateDiff(today, createdDate, "day");
+ return `${dayDiff}์ผ ์ `;
+ }
+
+ const year = Math.floor(monthDiff / 12);
+ const month = monthDiff % 12;
+ if (year === 0) {
+ return `${month}๊ฐ์ ์ `;
+ }
+ if (month === 0) {
+ return `${year}๋
์ `;
+ }
+
+ return `${year}๋
${month}๊ฐ์ ์ `;
+ }
+ setEvent() {
+ const activityChart = document.body.querySelector("#activity-chart");
+ activityChart.onerror = (event) => {
+ event.target.style.setProperty("display", "none");
+ event.target.parentElement.insertAdjacentHTML(
+ "beforeend",
+ '<div class="activity-error ml-4">No Activity Chart</div>'
+ );
+ };
+ }
+ template() {
return `
- <div>
- <img
- src="${this.avartar}"
- alt="${this.name} ํ๋กํ์ฌ์ง"
- width="90"
- class="mr-3 rounded-circle"
- />
+ <div class="w-100 flex-lg-row flex-column d-flex align-items-center justify-content-center">
+ <div class="d-flex align-items-center justify-content-center">
+ <img
+ src="${this.avartar}"
+ alt="${this.name} ํ๋กํ์ฌ์ง"
+ width="200"
+ class="mr-xl-3 mb-3 mb-xl-0 rounded-circle"
+ />
+ </div>
+ <div class="w-100 d-flex flex-column align-items-lg-start align-items-center">
+ <div class="px-4 text-lg-left text-center">
+ <a class="text-primary" href="${this.htmlUrl}" target="_blank">
+ <h5 class="card-title">${this.loginId} </h5>
+ </a>
+ <div class="d-flex align-items-end">
+ <h6 class="card-subtitle m-0">${this.name ?? ""}</h6>
+ <span class="card-text text-muted ml-2 font-size-xs">${this._getCreatedDateInfo()}</span>
</div>
- <div>
- <h5 class="card-title">${this.name} </h5>
- <h6 class="card-subtitle text-muted">${this.loginId}</h6>
- <div class="card-body p-0 mt-2">
- <a
- href="https://github.com/dmstmdrbs?tab=followers"
- target="_blank"
- class="card-link badge bg-success text-white"
- >Followers ${this.followers}๋ช
</a
- >
- <a
- href="https://github.com/dmstmdrbs?tab=following"
- target="_blank"
- class="card-link badge bg-success text-white ml-2"
- >Following ${this.following}๋ช
</a
- >
- <a
- href="https://github.com/dmstmdrbs?tab=repositories"
- target="_blank"
- class="card-link badge bg-info text-white ml-2"
- >Repos ${this.public_repos}๊ฐ</a
- >
- <span class="badge bg-secondary text-white ml-2">Gists ${this.public_gists}๊ฐ</span>
- </div>
- </div>
- `;
+ <p class="m-0 mt-2">${this.bio ?? ""}</p>
+ </div>
+ <div class="card-body py-1 ml-1 mb-2">
+ <a
+ href="https://github.com/${this.loginId}?tab=followers"
+ target="_blank"
+ class="card-link badge bg-success text-white"
+ >Followers ${this.followers}๋ช
</a
+ >
+ <a
+ href="https://github.com/${this.loginId}?tab=following"
+ target="_blank"
+ class="card-link badge bg-success text-white ml-2"
+ >Following ${this.following}๋ช
</a
+ >
+ <a
+ href="https://github.com/${this.loginId}?tab=repositories"
+ target="_blank"
+ class="card-link badge bg-info text-white ml-2"
+ >Repos ${this.publicRepos}๊ฐ
+ </a>
+ <span class="badge bg-secondary text-white ml-2">
+ Gists ${this.publicGists}๊ฐ
+ </span>
+ </div>
+ <div class="w-100">
+ <img
+ id="activity-chart"
+ class="w-100"
+ style="max-width: 663px;"
+ src="https://ghchart.rshah.org/${this.loginId}"
+ alt="๊นํ๋ธ ํ๋ ์ฐจํธ"
+ />
+ </div>
+ </div>
+ </div>
+ `;
+ }
+ render(container) {
+ container.innerHTML = this.template();
+ this.setEvent();
}
setRepos(repos) {
this.repos = repos | JavaScript | `loginId` ๋ง ์นด๋ฉ์ผ์ด์ค๋ก ์ ์ ๋์ด์๋ค์! ๋ณ์๋ช
ํ๊ธฐ๋ฒ์ ํต์ผ์ํค๋ฉด ์ข์ ๊ฒ ๊ฐ์์ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.