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` ๋งŒ ์นด๋ฉœ์ผ€์ด์Šค๋กœ ์ •์˜ ๋˜์–ด์žˆ๋„ค์š”! ๋ณ€์ˆ˜๋ช… ํ‘œ๊ธฐ๋ฒ•์„ ํ†ต์ผ์‹œํ‚ค๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”