code stringlengths 41 34.3k | lang stringclasses 8
values | review stringlengths 1 4.74k |
|---|---|---|
@@ -0,0 +1,36 @@
+package christmas.domain;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import java.math.BigDecimal;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+public class BillTest {
+ Order testOrder = new Order();
+
+ @Test
+ @DisplayName("์ ์ฒด_๊ฐ๊ฒฉ_๊ณ์ฐ_ํ
์คํธ")
+ public void testBillTotalPriceCalculation() {
+ testOrder.takeOrder("์์ก์ด์ํ-1,ํฐ๋ณธ์คํ
์ดํฌ-2,์ด์ฝ์ผ์ดํฌ-3");
+ Bill bill = new Bill(testOrder);
+
+ BigDecimal expectedTotalPrice = BigDecimal
+ .valueOf(1).multiply(Menu.APPETIZER_MUSHROOM_SOUP.getPrice())
+ .add(BigDecimal.valueOf(2).multiply(Menu.MAIN_T_BONE_STEAK.getPrice()))
+ .add(BigDecimal.valueOf(3).multiply(Menu.DESSERT_CHOCO_CAKE.getPrice()));
+
+ assertEquals(expectedTotalPrice, bill.getTotalPrice());
+ }
+
+ @Test
+ @DisplayName("๊ฐ๊ฒฉ_ํ ์ธ_์ ์ฉ_ํ
์คํธ")
+ public void testBillDiscountPrice() {
+ testOrder.takeOrder("์์ก์ด์ํ-5"); //30,000์
+ Bill bill = new Bill(testOrder);
+ bill.discountPrice(new BigDecimal(10000)); //30,000 - 10,000 ์
+
+ assertEquals(bill.getTotalPrice(), new BigDecimal(20000));
+ }
+} | Java | given when then ํจํด์ ์ฌ์ฉํด์ ํ
์คํธ์ฝ๋๋ฅผ ๋๋ ๋ณด๋ ๊ฑด ์ด๋จ๊น์?
https://brunch.co.kr/@springboot/292 |
@@ -0,0 +1,89 @@
+package christmas.domain;
+
+import christmas.utils.ErrorMessage;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class OrderTest {
+ String validInput = "ํฐ๋ณธ์คํ
์ดํฌ-2,์์ก์ด์ํ-2";
+
+ @Test
+ @DisplayName("์ฃผ๋ฌธ_์ ํจ๊ฐ_์
๋ ฅ_ํ
์คํธ")
+ void takeOrder_ValidInput_ShouldNotThrowException() {
+ Order order = new Order();
+ assertDoesNotThrow(() -> order.takeOrder(validInput));
+ }
+
+ @Test
+ @DisplayName("์ฃผ๋ฌธ_์ค๋ณต_์์ธ_ํ
์คํธ")
+ void takeOrder_DuplicateMenu_ShouldThrowException() {
+ Order order = new Order();
+ String duplicateMenuInput = "ํฐ๋ณธ์คํ
์ดํฌ-2,ํฐ๋ณธ์คํ
์ดํฌ-2";
+
+ IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, ()
+ -> order.takeOrder(duplicateMenuInput));
+ assertEquals(ErrorMessage.INPUT_ORDER_ERROR_MESSAGE.getMessage(), exception.getMessage());
+ }
+
+ @Test
+ @DisplayName("์ฃผ๋ฌธ_์
๋ ฅํ์_์์ธ_ํ
์คํธ")
+ void takeOrder_InvalidOrderFormat_ShouldThrowException() {
+ Order order = new Order();
+ String invalidFormatInput = "ํฐ๋ณธ์คํ
์ดํฌ+2";
+
+ IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, ()
+ -> order.takeOrder(invalidFormatInput));
+ assertEquals(ErrorMessage.INPUT_ORDER_ERROR_MESSAGE.getMessage(), exception.getMessage());
+ }
+
+ @Test
+ @DisplayName("์ฃผ๋ฌธ_๊ฐ์์ด๊ณผ_์์ธ_ํ
์คํธ")
+ void takeOrder_ExceedMaximumQuantity_ShouldThrowException() {
+ Order order = new Order();
+ String exceedQuantityInput = "ํฐ๋ณธ์คํ
์ดํฌ-20,์์ก์ด์ํ-10";
+
+ IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, ()
+ -> order.takeOrder(exceedQuantityInput));
+ assertEquals(ErrorMessage.INPUT_ORDER_ERROR_MESSAGE.getMessage(), exception.getMessage());
+ }
+
+ @Test
+ @DisplayName("์ฃผ๋ฌธ_์๋ฃ_์์ธ_ํ
์คํธ")
+ void takeOrder_OnlyBeverage_ValidInput_ShouldNotThrowException() {
+ Order order = new Order();
+ String onlyBeverageInput = "์ ๋ก์ฝ๋ผ-10";
+
+ IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, ()
+ -> order.takeOrder(onlyBeverageInput));
+ assertEquals(ErrorMessage.INPUT_ORDER_ERROR_MESSAGE.getMessage(), exception.getMessage());
+ }
+
+ @Test
+ @DisplayName("์ฃผ๋ฌธ_๊ณต๋ฐฑ_์์ธ_ํ
์คํธ")
+ void toString_OrderDetailsEmpty_ShouldReturnEmptyString() {
+ Order order = new Order();
+
+ IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, ()
+ -> order.takeOrder(""));
+ assertEquals(ErrorMessage.INPUT_ORDER_ERROR_MESSAGE.getMessage(), exception.getMessage());
+ assertEquals("", order.toString());
+ }
+
+ @Test
+ @DisplayName("์ฃผ๋ฌธ_๋ด์ญ_์ถ๋ ฅ_ํ
์คํธ")
+ void getOrderDetails_OrderDetailsNotEmpty_ShouldReturnOrderDetails() {
+ Order order = new Order();
+ order.takeOrder(validInput);
+
+ Map<Menu, Integer> expectedOrderDetails = new HashMap<>();
+ expectedOrderDetails.put(Menu.findMenu("ํฐ๋ณธ์คํ
์ดํฌ"), 2);
+ expectedOrderDetails.put(Menu.findMenu("์์ก์ด์ํ"), 2);
+
+ assertEquals(expectedOrderDetails, order.getOrderDetails());
+ }
+} | Java | ๋ฐ๋ณต๋๋ Order order = new Order(); ๋ @BeforeAll void setUp()์ ํ์ฉํ์ฌ์ ๋ฏธ๋ฆฌ ์์ฑํด ์ฃผ๋ ๊ฑด ์ด๋จ๊น์? |
@@ -0,0 +1,110 @@
+package christmas.controller;
+
+import christmas.domain.*;
+import christmas.utils.EventSettings;
+import christmas.parser.EventDetailsParser;
+import christmas.view.EventView;
+
+import java.math.BigDecimal;
+import java.util.Map;
+
+public class ChristmasEventController implements EventController {
+ private static final String WEEKDAY_DISCOUNT_TYPE = "dessert";
+ private static final String WEEKEND_DISCOUNT_TYPE = "main";
+ private static final DecemberCalendar decemberCalendar = new DecemberCalendar();
+
+ private boolean canPresent = false;
+ private BigDecimal totalBenefitAmount = new BigDecimal(0);
+ private Map<Menu, Integer> orderDetails;
+ private Badge badge;
+ private String eventResultDetails = "";
+ private BigDecimal beforeEventApplied;
+
+ public void applyEvent(ReservationDay reservationDay, Order order, Bill bill) {
+ beforeEventApplied = bill.getTotalPrice();
+ if (bill.getTotalPrice().compareTo(EventSettings.EVENT_APPLY_STAND.getAmount()) >= 0) {
+ this.orderDetails = order.getOrderDetails();
+ presentEvent(bill);
+ dDayDiscountEvent(reservationDay, bill);
+ weekdayDiscountEvent(reservationDay, bill);
+ weekendDiscountEvent(reservationDay, bill);
+ specialDayDiscountEvent(reservationDay, bill);
+ badgeEvent(totalBenefitAmount);
+ }
+ }
+
+ public void presentEvent(Bill bill) {
+ if (bill.getTotalPrice().compareTo(EventSettings.PRESENT_STANDARD_AMOUNT.getAmount()) == 1) {
+ canPresent = true;
+ BigDecimal benefitValue = EventSettings.PRESENT_VALUE.getAmount();
+
+ totalBenefitAmount = totalBenefitAmount.add(benefitValue);
+ eventResultDetails += EventDetailsParser.parsePresentEventDetail(benefitValue);
+ }
+ }
+
+ public void dDayDiscountEvent(ReservationDay reservationDay, Bill bill) {
+ if (reservationDay.dDayDiscountEventPeriod()) {
+ BigDecimal eventDay = new BigDecimal(reservationDay.getDay() - 1);
+ BigDecimal discountValue = EventSettings.D_DAY_DISCOUNT_START_VALUE.getAmount().
+ add((EventSettings.D_DAY_DISCOUNT_VALUE.getAmount().multiply(eventDay)));
+
+ bill.discountPrice(discountValue);
+ totalBenefitAmount = totalBenefitAmount.add(discountValue);
+ eventResultDetails += EventDetailsParser.parseDDayDiscountEventDetail(discountValue);
+ }
+ }
+
+ public void weekdayDiscountEvent(ReservationDay day, Bill bill) {
+ if (decemberCalendar.isWeekday(day.getDay())) {
+ long dessertCount = orderDetails.entrySet().stream()
+ .filter(entry -> WEEKDAY_DISCOUNT_TYPE.equals(entry.getKey().getMenuItem().getMenuType()))
+ .mapToLong(Map.Entry::getValue)
+ .sum();
+ BigDecimal discountValue = new BigDecimal(dessertCount)
+ .multiply(EventSettings.STANDARD_DISCOUNT_VALUE.getAmount());
+
+ bill.discountPrice(discountValue);
+ totalBenefitAmount = totalBenefitAmount.add(discountValue);
+ eventResultDetails += EventDetailsParser.parseWeekdayDiscountEventDetail(discountValue);
+ }
+ }
+
+ public void weekendDiscountEvent(ReservationDay day, Bill bill) {
+ if (decemberCalendar.isWeekend(day.getDay())) {
+ long mainDishCount = orderDetails.entrySet().stream()
+ .filter(entry -> WEEKEND_DISCOUNT_TYPE.equals(entry.getKey().getMenuItem().getMenuType()))
+ .mapToLong(Map.Entry::getValue)
+ .sum();
+ BigDecimal discountValue = new BigDecimal(mainDishCount)
+ .multiply(EventSettings.STANDARD_DISCOUNT_VALUE.getAmount());
+
+ bill.discountPrice(discountValue);
+ totalBenefitAmount = totalBenefitAmount.add(discountValue);
+ eventResultDetails += EventDetailsParser.parseWeekendDiscountEventDetail(discountValue);
+ }
+ }
+
+ public void specialDayDiscountEvent(ReservationDay day, Bill bill) {
+ if (decemberCalendar.isSpecialDay(day.getDay())) {
+ BigDecimal discountValue = EventSettings.SPECIAL_DAY_DISCOUNT_VALUE.getAmount();
+
+ bill.discountPrice(discountValue);
+ totalBenefitAmount = totalBenefitAmount.add(discountValue);
+ eventResultDetails += EventDetailsParser.paresSpecialDayDiscountEventDetail(discountValue);
+ }
+ }
+
+ public void badgeEvent(BigDecimal totalBenefitAmount) {
+ badge = Badge.getBadge(totalBenefitAmount);
+ }
+
+ public void showEventDiscountDetails(Bill bill) {
+ EventView.printPriceBeforeDiscount(beforeEventApplied);
+ EventView.printPresentDetails(canPresent);
+ EventView.printEventResultDetails(eventResultDetails);
+ EventView.printTotalBenefitAmount(totalBenefitAmount);
+ EventView.printPriceAfterDiscount(bill);
+ EventView.printBadge(badge);
+ }
+} | Java | ํน์ ๋ฉ์๋์์๋ง ์ฌ์ฉ๋๋ ํ๋๋ ๋ก์ปฌํํ๊ณ ๋๋จธ์ง ๊ฐ์ฒดํํ์ฌ ํ๋ ์๋ฅผ ์ค์ฌ๋ณด๋ ๊ฑด ์ด๋จ๊น์?
์ถ๊ฐ๋ก `final` ํค์๋๋ฅผ ์๋ตํ์ ์ด์ ๊ฐ ์์๊น์? |
@@ -0,0 +1,69 @@
+package christmas.controller;
+
+import christmas.domain.Bill;
+import christmas.domain.Order;
+import christmas.domain.ReservationDay;
+import christmas.view.InputView;
+import christmas.view.OutputView;
+
+public class PlannerController {
+ private final Order order;
+ private final ReservationDay reservationDay;
+ private final EventController eventController;
+
+ private Bill bill;
+
+ public PlannerController(EventController eventController) {
+ this.eventController = eventController;
+ this.reservationDay = new ReservationDay();
+ this.order = new Order();
+ }
+
+ public void run() {
+ OutputView.printStartMessage();
+
+ try {
+ inputDay();
+ inputOrder();
+ } catch (IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ return;
+ }
+
+ processEvent();
+ }
+
+ private void inputDay() {
+ while (true) {
+ try {
+ String dayInput = InputView.inputDate();
+ reservationDay.reserveDay(dayInput);
+ break;
+ } catch (IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+ }
+
+ private void inputOrder() {
+ while (true) {
+ try {
+ String orderInput = InputView.inputOrder();
+ order.takeOrder(orderInput.replace(" ", ""));
+ break;
+ } catch (IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+ }
+
+ private void processEvent() {
+ OutputView.printEventPreviewMessage(reservationDay.getDay());
+ OutputView.printOrderDetails(order);
+
+ bill = new Bill(order);
+
+ eventController.applyEvent(reservationDay, order, bill);
+ eventController.showEventDiscountDetails(bill);
+ }
+} | Java | ์์ธ ๋ฉ์์ง ์ถ๋ ฅ๋ `OutputView` ์์ ์ฒ๋ฆฌํ๋๊ฑด ์ด๋จ๊น์? |
@@ -0,0 +1,69 @@
+package christmas.controller;
+
+import christmas.domain.Bill;
+import christmas.domain.Order;
+import christmas.domain.ReservationDay;
+import christmas.view.InputView;
+import christmas.view.OutputView;
+
+public class PlannerController {
+ private final Order order;
+ private final ReservationDay reservationDay;
+ private final EventController eventController;
+
+ private Bill bill;
+
+ public PlannerController(EventController eventController) {
+ this.eventController = eventController;
+ this.reservationDay = new ReservationDay();
+ this.order = new Order();
+ }
+
+ public void run() {
+ OutputView.printStartMessage();
+
+ try {
+ inputDay();
+ inputOrder();
+ } catch (IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ return;
+ }
+
+ processEvent();
+ }
+
+ private void inputDay() {
+ while (true) {
+ try {
+ String dayInput = InputView.inputDate();
+ reservationDay.reserveDay(dayInput);
+ break;
+ } catch (IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+ }
+
+ private void inputOrder() {
+ while (true) {
+ try {
+ String orderInput = InputView.inputOrder();
+ order.takeOrder(orderInput.replace(" ", ""));
+ break;
+ } catch (IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+ }
+
+ private void processEvent() {
+ OutputView.printEventPreviewMessage(reservationDay.getDay());
+ OutputView.printOrderDetails(order);
+
+ bill = new Bill(order);
+
+ eventController.applyEvent(reservationDay, order, bill);
+ eventController.showEventDiscountDetails(bill);
+ }
+} | Java | ํ๋๊ฐ ์์ฑ์๊ฐ ์๋ ๋ค๋ฅธ ๋ฉ์๋์์ ์ด๊ธฐํ๋๋๊ฒ ์ด์ํ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,35 @@
+package christmas.domain;
+
+import java.math.BigDecimal;
+
+public enum Badge {
+ SANTA_BADGE("์ฐํ", new BigDecimal(20000)),
+ TREE_BADGE("ํธ๋ฆฌ", new BigDecimal(10000)),
+ STAR_BADGE("๋ณ", new BigDecimal(5000));
+
+ private final String name;
+ private final BigDecimal standardAmount;
+
+ Badge(String name, BigDecimal standardAmount) {
+ this.name = name;
+ this.standardAmount = standardAmount;
+ }
+
+ public String getName() {
+ if (this == null) return "";
+ return name;
+ }
+
+ public static Badge getBadge(BigDecimal totalBenefit) {
+ if (totalBenefit.compareTo(SANTA_BADGE.standardAmount) >= 0) {
+ return SANTA_BADGE;
+ }
+ if (totalBenefit.compareTo(TREE_BADGE.standardAmount) >= 0) {
+ return TREE_BADGE;
+ }
+ if (totalBenefit.compareTo(STAR_BADGE.standardAmount) >= 0) {
+ return STAR_BADGE;
+ }
+ return null;
+ }
+} | Java | ์ด๋ฆ์ด `null`์ด ๋๋ ๊ฒฝ์ฐ๊ฐ ์์๊น์? |
@@ -0,0 +1,110 @@
+package christmas.controller;
+
+import christmas.domain.*;
+import christmas.utils.EventSettings;
+import christmas.parser.EventDetailsParser;
+import christmas.view.EventView;
+
+import java.math.BigDecimal;
+import java.util.Map;
+
+public class ChristmasEventController implements EventController {
+ private static final String WEEKDAY_DISCOUNT_TYPE = "dessert";
+ private static final String WEEKEND_DISCOUNT_TYPE = "main";
+ private static final DecemberCalendar decemberCalendar = new DecemberCalendar();
+
+ private boolean canPresent = false;
+ private BigDecimal totalBenefitAmount = new BigDecimal(0);
+ private Map<Menu, Integer> orderDetails;
+ private Badge badge;
+ private String eventResultDetails = "";
+ private BigDecimal beforeEventApplied;
+
+ public void applyEvent(ReservationDay reservationDay, Order order, Bill bill) {
+ beforeEventApplied = bill.getTotalPrice();
+ if (bill.getTotalPrice().compareTo(EventSettings.EVENT_APPLY_STAND.getAmount()) >= 0) {
+ this.orderDetails = order.getOrderDetails();
+ presentEvent(bill);
+ dDayDiscountEvent(reservationDay, bill);
+ weekdayDiscountEvent(reservationDay, bill);
+ weekendDiscountEvent(reservationDay, bill);
+ specialDayDiscountEvent(reservationDay, bill);
+ badgeEvent(totalBenefitAmount);
+ }
+ }
+
+ public void presentEvent(Bill bill) {
+ if (bill.getTotalPrice().compareTo(EventSettings.PRESENT_STANDARD_AMOUNT.getAmount()) == 1) {
+ canPresent = true;
+ BigDecimal benefitValue = EventSettings.PRESENT_VALUE.getAmount();
+
+ totalBenefitAmount = totalBenefitAmount.add(benefitValue);
+ eventResultDetails += EventDetailsParser.parsePresentEventDetail(benefitValue);
+ }
+ }
+
+ public void dDayDiscountEvent(ReservationDay reservationDay, Bill bill) {
+ if (reservationDay.dDayDiscountEventPeriod()) {
+ BigDecimal eventDay = new BigDecimal(reservationDay.getDay() - 1);
+ BigDecimal discountValue = EventSettings.D_DAY_DISCOUNT_START_VALUE.getAmount().
+ add((EventSettings.D_DAY_DISCOUNT_VALUE.getAmount().multiply(eventDay)));
+
+ bill.discountPrice(discountValue);
+ totalBenefitAmount = totalBenefitAmount.add(discountValue);
+ eventResultDetails += EventDetailsParser.parseDDayDiscountEventDetail(discountValue);
+ }
+ }
+
+ public void weekdayDiscountEvent(ReservationDay day, Bill bill) {
+ if (decemberCalendar.isWeekday(day.getDay())) {
+ long dessertCount = orderDetails.entrySet().stream()
+ .filter(entry -> WEEKDAY_DISCOUNT_TYPE.equals(entry.getKey().getMenuItem().getMenuType()))
+ .mapToLong(Map.Entry::getValue)
+ .sum();
+ BigDecimal discountValue = new BigDecimal(dessertCount)
+ .multiply(EventSettings.STANDARD_DISCOUNT_VALUE.getAmount());
+
+ bill.discountPrice(discountValue);
+ totalBenefitAmount = totalBenefitAmount.add(discountValue);
+ eventResultDetails += EventDetailsParser.parseWeekdayDiscountEventDetail(discountValue);
+ }
+ }
+
+ public void weekendDiscountEvent(ReservationDay day, Bill bill) {
+ if (decemberCalendar.isWeekend(day.getDay())) {
+ long mainDishCount = orderDetails.entrySet().stream()
+ .filter(entry -> WEEKEND_DISCOUNT_TYPE.equals(entry.getKey().getMenuItem().getMenuType()))
+ .mapToLong(Map.Entry::getValue)
+ .sum();
+ BigDecimal discountValue = new BigDecimal(mainDishCount)
+ .multiply(EventSettings.STANDARD_DISCOUNT_VALUE.getAmount());
+
+ bill.discountPrice(discountValue);
+ totalBenefitAmount = totalBenefitAmount.add(discountValue);
+ eventResultDetails += EventDetailsParser.parseWeekendDiscountEventDetail(discountValue);
+ }
+ }
+
+ public void specialDayDiscountEvent(ReservationDay day, Bill bill) {
+ if (decemberCalendar.isSpecialDay(day.getDay())) {
+ BigDecimal discountValue = EventSettings.SPECIAL_DAY_DISCOUNT_VALUE.getAmount();
+
+ bill.discountPrice(discountValue);
+ totalBenefitAmount = totalBenefitAmount.add(discountValue);
+ eventResultDetails += EventDetailsParser.paresSpecialDayDiscountEventDetail(discountValue);
+ }
+ }
+
+ public void badgeEvent(BigDecimal totalBenefitAmount) {
+ badge = Badge.getBadge(totalBenefitAmount);
+ }
+
+ public void showEventDiscountDetails(Bill bill) {
+ EventView.printPriceBeforeDiscount(beforeEventApplied);
+ EventView.printPresentDetails(canPresent);
+ EventView.printEventResultDetails(eventResultDetails);
+ EventView.printTotalBenefitAmount(totalBenefitAmount);
+ EventView.printPriceAfterDiscount(bill);
+ EventView.printBadge(badge);
+ }
+} | Java | `BigDecimal` ์ ๊ฒฝ์ฐ ์ผ๋ถ ๊ฐ์ ์บ์ฑํ๊ณ ์์ด ์์ฑ์ ๋์ `valueOf()` ๋ฉ์๋๋ฅผ ํตํด ๊ฐ์ฒด๋ฅผ ์ป๋๊ฒ ๋ ํจ์จ์ ์
๋๋ค! |
@@ -0,0 +1,35 @@
+package christmas.domain;
+
+import java.math.BigDecimal;
+
+public enum Badge {
+ SANTA_BADGE("์ฐํ", new BigDecimal(20000)),
+ TREE_BADGE("ํธ๋ฆฌ", new BigDecimal(10000)),
+ STAR_BADGE("๋ณ", new BigDecimal(5000));
+
+ private final String name;
+ private final BigDecimal standardAmount;
+
+ Badge(String name, BigDecimal standardAmount) {
+ this.name = name;
+ this.standardAmount = standardAmount;
+ }
+
+ public String getName() {
+ if (this == null) return "";
+ return name;
+ }
+
+ public static Badge getBadge(BigDecimal totalBenefit) {
+ if (totalBenefit.compareTo(SANTA_BADGE.standardAmount) >= 0) {
+ return SANTA_BADGE;
+ }
+ if (totalBenefit.compareTo(TREE_BADGE.standardAmount) >= 0) {
+ return TREE_BADGE;
+ }
+ if (totalBenefit.compareTo(STAR_BADGE.standardAmount) >= 0) {
+ return STAR_BADGE;
+ }
+ return null;
+ }
+} | Java | `null` ๋ฐํ์ด ์ํํ ๊ฒ ๊ฐ์์! `NONE` ๊ณผ ๊ฐ์ ์ธ์คํด์ค๋ฅผ ์ถ๊ฐํ์ฌ ์ด๋ฅผ ๋ฐํํ๋๊ฑด ์ด๋จ๊น์? |
@@ -0,0 +1,32 @@
+package christmas.domain;
+
+import java.math.BigDecimal;
+import java.util.Map;
+
+public class Bill {
+ private final Map<Menu, Integer> orderDetails;
+
+ private BigDecimal totalPrice = new BigDecimal(0);
+
+ public Bill(Order order) {
+ this.orderDetails = order.getOrderDetails();
+ calculateTotalPrice();
+ }
+
+ private void calculateTotalPrice() {
+ for (Map.Entry<Menu, Integer> entry : orderDetails.entrySet()) {
+ Menu menu = entry.getKey();
+ int count = entry.getValue();
+ BigDecimal price = menu.getPrice().multiply(BigDecimal.valueOf(count));
+ totalPrice = totalPrice.add(price);
+ }
+ }
+
+ public void discountPrice(BigDecimal discountValue) {
+ totalPrice = totalPrice.subtract(discountValue);
+ }
+
+ public BigDecimal getTotalPrice() {
+ return totalPrice;
+ }
+} | Java | ๋ฉ๋ด ์
๋ ฅ ์ ์ด๋ฆ, ์๋ ์ธ์ ๋ค๋ฅธ ๊ฐ์ด ์ถ๊ฐ๋๋๊ฑธ ๊ฐ์ํ์ฌ `Map<K, V>` ๋์ ๋ณ๋์ ํด๋์ค ์ฌ์ฉ์ ์ด๋จ๊น์? |
@@ -0,0 +1,29 @@
+package christmas.domain;
+
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+public class DecemberCalendar {
+ private final List<Integer> weekdays = Stream.of(3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 17, 18, 19, 20, 21, 24, 25, 26, 27, 28, 31)
+ .collect(Collectors.toList());
+ private final List<Integer> weekends = Stream.of(1, 2, 8, 9, 15, 16, 22, 23, 29, 30)
+ .collect(Collectors.toList());
+ private final List<Integer> specialDays = Stream.of(3, 10, 17, 24, 25, 31)
+ .collect(Collectors.toList());
+
+ public boolean isWeekday(int day) {
+ if (weekdays.contains(day)) return true;
+ return false;
+ }
+
+ public boolean isWeekend(int day) {
+ if (weekends.contains(day)) return true;
+ return false;
+ }
+
+ public boolean isSpecialDay(int day) {
+ if (specialDays.contains(day)) return true;
+ return false;
+ }
+} | Java | `Arrays.asList()` ๋์ Stream์ ์ฌ์ฉํ์ ์ด์ ๊ฐ ์์๊น์? |
@@ -0,0 +1,62 @@
+package christmas.domain;
+
+import christmas.utils.ErrorMessage;
+import christmas.parser.Parser;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static christmas.domain.validator.OrderValidator.*;
+
+public class Order {
+ private final Map<Menu, Integer> orderDetails = new HashMap<>();
+ private int quantity = 0;
+
+ public void takeOrder(String input) {
+ List<String> eachOrderedMenu = Parser.inputToEachOrderedMenu(input);
+ try {
+ eachOrderedMenu.forEach(menuInformation -> processOrderedMenu(menuInformation));
+
+ calculateMenuQuantity();
+ validateOnlyBeverage(orderDetails);
+ validateMaximumQuantity(quantity);
+ } catch (Exception e) {
+ throw new IllegalArgumentException(ErrorMessage.INPUT_ORDER_ERROR_MESSAGE.getMessage());
+ }
+ }
+
+ private void processOrderedMenu(String menuInformation) {
+ String[] menuNameAndNumber = Parser.inputToMenu(menuInformation);
+ String menuName = menuNameAndNumber[0];
+ int menuNumber = Parser.stringToIntPaser(menuNameAndNumber[1]);
+ Menu orderedMenu = Menu.findMenu(menuName);
+
+ validateDuplicateMenu(orderDetails, orderedMenu);
+ validateOrderFormat(menuNameAndNumber);
+ orderDetails.put(orderedMenu, menuNumber);
+ }
+
+ private void calculateMenuQuantity() {
+ for (int count : orderDetails.values()) {
+ quantity += count;
+ }
+ }
+
+ public String toString() {
+ StringBuilder output = new StringBuilder();
+ for (Map.Entry<Menu, Integer> entry : orderDetails.entrySet()) {
+ Menu menu = entry.getKey();
+ int count = entry.getValue();
+ output.append(menu.getMenuItem().getName())
+ .append(" ")
+ .append(count)
+ .append("๊ฐ\n");
+ }
+ return output.toString();
+ }
+
+ public Map<Menu, Integer> getOrderDetails() {
+ return orderDetails;
+ }
+} | Java | `int`์ ๊ฒฝ์ฐ ํ๋์์ ๊ฐ์ ๋์
ํ์ง ์์๋ ๊ฐ์ฒด ์์ฑ์ 0์ผ๋ก ์ด๊ธฐํ ๋ฉ๋๋ค! |
@@ -0,0 +1,62 @@
+package christmas.domain;
+
+import christmas.utils.ErrorMessage;
+import christmas.parser.Parser;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static christmas.domain.validator.OrderValidator.*;
+
+public class Order {
+ private final Map<Menu, Integer> orderDetails = new HashMap<>();
+ private int quantity = 0;
+
+ public void takeOrder(String input) {
+ List<String> eachOrderedMenu = Parser.inputToEachOrderedMenu(input);
+ try {
+ eachOrderedMenu.forEach(menuInformation -> processOrderedMenu(menuInformation));
+
+ calculateMenuQuantity();
+ validateOnlyBeverage(orderDetails);
+ validateMaximumQuantity(quantity);
+ } catch (Exception e) {
+ throw new IllegalArgumentException(ErrorMessage.INPUT_ORDER_ERROR_MESSAGE.getMessage());
+ }
+ }
+
+ private void processOrderedMenu(String menuInformation) {
+ String[] menuNameAndNumber = Parser.inputToMenu(menuInformation);
+ String menuName = menuNameAndNumber[0];
+ int menuNumber = Parser.stringToIntPaser(menuNameAndNumber[1]);
+ Menu orderedMenu = Menu.findMenu(menuName);
+
+ validateDuplicateMenu(orderDetails, orderedMenu);
+ validateOrderFormat(menuNameAndNumber);
+ orderDetails.put(orderedMenu, menuNumber);
+ }
+
+ private void calculateMenuQuantity() {
+ for (int count : orderDetails.values()) {
+ quantity += count;
+ }
+ }
+
+ public String toString() {
+ StringBuilder output = new StringBuilder();
+ for (Map.Entry<Menu, Integer> entry : orderDetails.entrySet()) {
+ Menu menu = entry.getKey();
+ int count = entry.getValue();
+ output.append(menu.getMenuItem().getName())
+ .append(" ")
+ .append(count)
+ .append("๊ฐ\n");
+ }
+ return output.toString();
+ }
+
+ public Map<Menu, Integer> getOrderDetails() {
+ return orderDetails;
+ }
+} | Java | ๋๋ฉ์ธ์ด View์ ์์กดํ๋ ๊ฒ ๊ฐ์ต๋๋ค! `OutputView`์์ `Order`์ ๋ํ ๊ฐ์ ๊ฐ์ ธ์จ ํ ์ถ๋ ฅํ๋๊ฑด ์ด๋จ๊น์? |
@@ -1,3 +1,5 @@
+import {ReviewLikeButtonProps} from "@review-canvas/theme";
+
export type Shadow = 'NONE' | 'SMALL' | 'MEDIUM' | 'LARGE';
export type FocusAreaLayout = 'BEST_REVIEW_TOP' | 'BEST_REVIEW_BOTTOM' | 'BEST_REVIEW_LEFT' | 'BEST_REVIEW_RIGHT';
export type ReviewAreaLayout = 'REVIEW_TOP' | 'REVIEW_BOTTOM' | 'REVIEW_LEFT' | 'REVIEW_RIGHT';
@@ -6,6 +8,7 @@ export type AlignmentPosition = 'LEFT' | 'CENTER' | 'RIGHT';
export type DetailViewType = 'SPREAD' | 'MODAL';
export type PagingType = 'PAGE_NUMBER' | 'SEE_MORE_SCROLL';
export type FilterType = 'LIST' | 'DROPDOWN';
+export type ReviewLikeButtonType = 'NONE' | 'THUMB_UP_WITH_TEXT' | 'THUMB_UP';
export interface Margin {
left: string;
@@ -43,11 +46,11 @@ export interface Round {
}
export interface ReviewLike {
- buttonType: string;
- iconColor: string;
- textColor: string;
buttonBorderColor: string;
buttonRound: Round;
+ buttonType: ReviewLikeButtonType;
+ iconColor: string;
+ textColor: string;
}
export interface ReviewLayout { | TypeScript | ์ ์ฒด์ ์ผ๋ก Prettier๊ฐ ์ ์ฉ์ด ์ ๋์ด ์๋ ๊ฒ ๊ฐ์๋ฐ Prettier ์ ์ฒด์ ์ผ๋ก ์ ์ฉํด ์ฃผ์ธ์! |
@@ -9,50 +9,55 @@ import {
generateShadowCSS,
} from '@review-canvas/theme';
+// import ThumbUpIcon from '@/assets/icon/icon-thumb-up.svg';
import { Star } from '@/components/review/star.tsx';
import { useReviewItemStyle } from '@/contexts/style/review-item.ts';
import useMessageToShop from '@/hooks/use-message-to-shop.ts';
-import type { ReplyItem } from '@/services/api-types/review';
+import type { ReviewItemProps } from '@/services/api-types/review';
+import { useReviewService } from '@/services/review.tsx';
import { useConnectedShop } from '@/state/shop.ts';
import { MESSAGE_TYPES } from '@/utils/message';
import Reply from './reply';
-
-interface ReviewItemProps {
- id: number;
- rate: number;
- content: string;
- reviewerID: string;
- reviewer: string;
- replies: ReplyItem[];
-}
+import { useEffect, useState } from 'react';
export default function ReviewItem(props: ReviewItemProps) {
const style = useReviewItemStyle();
const { userID } = useConnectedShop();
+ const reviewService = useReviewService();
const message = useMessageToShop();
+ const [count, setCount] = useState(0);
+
+ useEffect(() => {
+ async function fetchData() {
+ return reviewService.userReviewLike(props.id);
+ }
+ void fetchData().then((response) => {
+ setCount(response.data.count);
+ });
+ }, [props.id, reviewService]);
const edit = () => {
message(MESSAGE_TYPES.OPEN_MODAL, {
type: 'edit_review',
url: `/reviews/${props.id}/edit`,
});
};
-
const deleteReview = () => {
message(MESSAGE_TYPES.OPEN_SELECTING_MODAL, {
type: 'delete',
url: `/reviews/${props.id}/delete`,
});
};
-
const showReviewDetail = () => {
message(MESSAGE_TYPES.OPEN_MODAL, {
type: 'detail',
url: `/reviews/${props.id}`,
});
};
+ const createLike = () => {};
+
return (
<li
css={[
@@ -63,6 +68,7 @@ export default function ReviewItem(props: ReviewItemProps) {
generateFontCSS(style.font),
generateShadowCSS(style.shadow, style.shadowColor),
css`
+ border-color: ${style.borderColor};
background-color: ${style.backgroundColor};
display: flex;
flex-direction: column;
@@ -88,6 +94,68 @@ export default function ReviewItem(props: ReviewItemProps) {
์์ฑ์ <span>{props.reviewer}</span>
</div>
<p className="text-left">{props.content}</p>
+ {/*{style.reviewLike.buttonType !== 'NONE' ? (*/}
+ {/* <button*/}
+ {/* onClick={(evt) => {*/}
+ {/* evt.stopPropagation();*/}
+ {/* if (userID === props.reviewerID) {*/}
+ {/* return;*/}
+ {/* }*/}
+ {/* }}*/}
+ {/* css={[*/}
+ {/* generateBorderRadiusCSS(style.reviewLike.buttonRound),*/}
+ {/* css`*/}
+ {/* border-width: 1px;*/}
+ {/* padding: 2px 6px;*/}
+ {/* margin-top: 15px;*/}
+ {/* margin-bottom: 10px;*/}
+ {/* border-color: ${style.reviewLike.buttonBorderColor};*/}
+ {/* color: ${style.reviewLike.textColor};*/}
+ {/* transition:*/}
+ {/* background-color 0.5s ease,*/}
+ {/* color 0.5s ease;*/}
+ {/* display: flex;*/}
+
+ {/* &:hover {*/}
+ {/* background-color: ${style.reviewLike.textColor};*/}
+ {/* color: white;*/}
+ {/* }*/}
+ {/* `,*/}
+ {/* ]}*/}
+ {/* >*/}
+ {/* <ThumbUpIcon />*/}
+ {/* {style.reviewLike.buttonType === 'THUMB_UP_WITH_TEXT' ? <div className="ml-1">๋์๋ผ์!</div> : null}*/}
+ {/* <div className="ml-1">0</div>*/}
+ {/* </button>*/}
+ {/*) : null}*/}
+ <button
+ css={[
+ generateBorderRadiusCSS(style.reviewLike.buttonRound),
+ css`
+ border-width: 1px;
+ padding: 2px 6px;
+ margin-top: 15px;
+ margin-bottom: 10px;
+ border-color: ${style.reviewLike.buttonBorderColor};
+ color: ${style.reviewLike.textColor};
+ transition:
+ background-color 0.5s ease,
+ color 0.5s ease;
+ display: flex;
+
+ &:hover {
+ background-color: ${style.reviewLike.textColor};
+ color: white;
+ }
+ `,
+ ]}
+ onClick={createLike}
+ type="button"
+ >
+ {/*<ThumbUpIcon />*/}
+ <div className="ml-1">๋์๋ผ์!</div>
+ <div className="ml-1">{count}</div>
+ </button>
{userID === props.reviewerID ? (
// eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions -- This is intentional
<div | Unknown | svg๋ component๋ก ๋ถ๋ฆฌํด์ Importํด์ ์ฐ๋ ๊ฒ ์ด๋จ๊ฐ์?? ๋ค๋ฅธ ๊ณณ์์๋ ์ธ ์ ์๊ณ , ์ปดํฌ๋ํธ ์ฝ๋ ๋ด์์ ๊ฐ๋
์ฑ์ด ์ข์ง ์์ ๊ฒ ๊ฐ์์์! |
@@ -9,50 +9,55 @@ import {
generateShadowCSS,
} from '@review-canvas/theme';
+// import ThumbUpIcon from '@/assets/icon/icon-thumb-up.svg';
import { Star } from '@/components/review/star.tsx';
import { useReviewItemStyle } from '@/contexts/style/review-item.ts';
import useMessageToShop from '@/hooks/use-message-to-shop.ts';
-import type { ReplyItem } from '@/services/api-types/review';
+import type { ReviewItemProps } from '@/services/api-types/review';
+import { useReviewService } from '@/services/review.tsx';
import { useConnectedShop } from '@/state/shop.ts';
import { MESSAGE_TYPES } from '@/utils/message';
import Reply from './reply';
-
-interface ReviewItemProps {
- id: number;
- rate: number;
- content: string;
- reviewerID: string;
- reviewer: string;
- replies: ReplyItem[];
-}
+import { useEffect, useState } from 'react';
export default function ReviewItem(props: ReviewItemProps) {
const style = useReviewItemStyle();
const { userID } = useConnectedShop();
+ const reviewService = useReviewService();
const message = useMessageToShop();
+ const [count, setCount] = useState(0);
+
+ useEffect(() => {
+ async function fetchData() {
+ return reviewService.userReviewLike(props.id);
+ }
+ void fetchData().then((response) => {
+ setCount(response.data.count);
+ });
+ }, [props.id, reviewService]);
const edit = () => {
message(MESSAGE_TYPES.OPEN_MODAL, {
type: 'edit_review',
url: `/reviews/${props.id}/edit`,
});
};
-
const deleteReview = () => {
message(MESSAGE_TYPES.OPEN_SELECTING_MODAL, {
type: 'delete',
url: `/reviews/${props.id}/delete`,
});
};
-
const showReviewDetail = () => {
message(MESSAGE_TYPES.OPEN_MODAL, {
type: 'detail',
url: `/reviews/${props.id}`,
});
};
+ const createLike = () => {};
+
return (
<li
css={[
@@ -63,6 +68,7 @@ export default function ReviewItem(props: ReviewItemProps) {
generateFontCSS(style.font),
generateShadowCSS(style.shadow, style.shadowColor),
css`
+ border-color: ${style.borderColor};
background-color: ${style.backgroundColor};
display: flex;
flex-direction: column;
@@ -88,6 +94,68 @@ export default function ReviewItem(props: ReviewItemProps) {
์์ฑ์ <span>{props.reviewer}</span>
</div>
<p className="text-left">{props.content}</p>
+ {/*{style.reviewLike.buttonType !== 'NONE' ? (*/}
+ {/* <button*/}
+ {/* onClick={(evt) => {*/}
+ {/* evt.stopPropagation();*/}
+ {/* if (userID === props.reviewerID) {*/}
+ {/* return;*/}
+ {/* }*/}
+ {/* }}*/}
+ {/* css={[*/}
+ {/* generateBorderRadiusCSS(style.reviewLike.buttonRound),*/}
+ {/* css`*/}
+ {/* border-width: 1px;*/}
+ {/* padding: 2px 6px;*/}
+ {/* margin-top: 15px;*/}
+ {/* margin-bottom: 10px;*/}
+ {/* border-color: ${style.reviewLike.buttonBorderColor};*/}
+ {/* color: ${style.reviewLike.textColor};*/}
+ {/* transition:*/}
+ {/* background-color 0.5s ease,*/}
+ {/* color 0.5s ease;*/}
+ {/* display: flex;*/}
+
+ {/* &:hover {*/}
+ {/* background-color: ${style.reviewLike.textColor};*/}
+ {/* color: white;*/}
+ {/* }*/}
+ {/* `,*/}
+ {/* ]}*/}
+ {/* >*/}
+ {/* <ThumbUpIcon />*/}
+ {/* {style.reviewLike.buttonType === 'THUMB_UP_WITH_TEXT' ? <div className="ml-1">๋์๋ผ์!</div> : null}*/}
+ {/* <div className="ml-1">0</div>*/}
+ {/* </button>*/}
+ {/*) : null}*/}
+ <button
+ css={[
+ generateBorderRadiusCSS(style.reviewLike.buttonRound),
+ css`
+ border-width: 1px;
+ padding: 2px 6px;
+ margin-top: 15px;
+ margin-bottom: 10px;
+ border-color: ${style.reviewLike.buttonBorderColor};
+ color: ${style.reviewLike.textColor};
+ transition:
+ background-color 0.5s ease,
+ color 0.5s ease;
+ display: flex;
+
+ &:hover {
+ background-color: ${style.reviewLike.textColor};
+ color: white;
+ }
+ `,
+ ]}
+ onClick={createLike}
+ type="button"
+ >
+ {/*<ThumbUpIcon />*/}
+ <div className="ml-1">๋์๋ผ์!</div>
+ <div className="ml-1">{count}</div>
+ </button>
{userID === props.reviewerID ? (
// eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions -- This is intentional
<div | Unknown | ๋ถํ์ํ console์ ์ ์ธํด์ฃผ์ธ์! ์์ ์ ๋ฆฌ๋ทฐ์๋ ๋์๋ผ์ ๊ฐ์ ๊ฒฝ์ฐ๋ ์คํ๋ ค alert์ผ๋ก ๋ณด์ฌ์ฃผ๋ ๊ฒ ๋ซ์ง ์์๊น ์ถ๋ค์ |
@@ -9,50 +9,55 @@ import {
generateShadowCSS,
} from '@review-canvas/theme';
+// import ThumbUpIcon from '@/assets/icon/icon-thumb-up.svg';
import { Star } from '@/components/review/star.tsx';
import { useReviewItemStyle } from '@/contexts/style/review-item.ts';
import useMessageToShop from '@/hooks/use-message-to-shop.ts';
-import type { ReplyItem } from '@/services/api-types/review';
+import type { ReviewItemProps } from '@/services/api-types/review';
+import { useReviewService } from '@/services/review.tsx';
import { useConnectedShop } from '@/state/shop.ts';
import { MESSAGE_TYPES } from '@/utils/message';
import Reply from './reply';
-
-interface ReviewItemProps {
- id: number;
- rate: number;
- content: string;
- reviewerID: string;
- reviewer: string;
- replies: ReplyItem[];
-}
+import { useEffect, useState } from 'react';
export default function ReviewItem(props: ReviewItemProps) {
const style = useReviewItemStyle();
const { userID } = useConnectedShop();
+ const reviewService = useReviewService();
const message = useMessageToShop();
+ const [count, setCount] = useState(0);
+
+ useEffect(() => {
+ async function fetchData() {
+ return reviewService.userReviewLike(props.id);
+ }
+ void fetchData().then((response) => {
+ setCount(response.data.count);
+ });
+ }, [props.id, reviewService]);
const edit = () => {
message(MESSAGE_TYPES.OPEN_MODAL, {
type: 'edit_review',
url: `/reviews/${props.id}/edit`,
});
};
-
const deleteReview = () => {
message(MESSAGE_TYPES.OPEN_SELECTING_MODAL, {
type: 'delete',
url: `/reviews/${props.id}/delete`,
});
};
-
const showReviewDetail = () => {
message(MESSAGE_TYPES.OPEN_MODAL, {
type: 'detail',
url: `/reviews/${props.id}`,
});
};
+ const createLike = () => {};
+
return (
<li
css={[
@@ -63,6 +68,7 @@ export default function ReviewItem(props: ReviewItemProps) {
generateFontCSS(style.font),
generateShadowCSS(style.shadow, style.shadowColor),
css`
+ border-color: ${style.borderColor};
background-color: ${style.backgroundColor};
display: flex;
flex-direction: column;
@@ -88,6 +94,68 @@ export default function ReviewItem(props: ReviewItemProps) {
์์ฑ์ <span>{props.reviewer}</span>
</div>
<p className="text-left">{props.content}</p>
+ {/*{style.reviewLike.buttonType !== 'NONE' ? (*/}
+ {/* <button*/}
+ {/* onClick={(evt) => {*/}
+ {/* evt.stopPropagation();*/}
+ {/* if (userID === props.reviewerID) {*/}
+ {/* return;*/}
+ {/* }*/}
+ {/* }}*/}
+ {/* css={[*/}
+ {/* generateBorderRadiusCSS(style.reviewLike.buttonRound),*/}
+ {/* css`*/}
+ {/* border-width: 1px;*/}
+ {/* padding: 2px 6px;*/}
+ {/* margin-top: 15px;*/}
+ {/* margin-bottom: 10px;*/}
+ {/* border-color: ${style.reviewLike.buttonBorderColor};*/}
+ {/* color: ${style.reviewLike.textColor};*/}
+ {/* transition:*/}
+ {/* background-color 0.5s ease,*/}
+ {/* color 0.5s ease;*/}
+ {/* display: flex;*/}
+
+ {/* &:hover {*/}
+ {/* background-color: ${style.reviewLike.textColor};*/}
+ {/* color: white;*/}
+ {/* }*/}
+ {/* `,*/}
+ {/* ]}*/}
+ {/* >*/}
+ {/* <ThumbUpIcon />*/}
+ {/* {style.reviewLike.buttonType === 'THUMB_UP_WITH_TEXT' ? <div className="ml-1">๋์๋ผ์!</div> : null}*/}
+ {/* <div className="ml-1">0</div>*/}
+ {/* </button>*/}
+ {/*) : null}*/}
+ <button
+ css={[
+ generateBorderRadiusCSS(style.reviewLike.buttonRound),
+ css`
+ border-width: 1px;
+ padding: 2px 6px;
+ margin-top: 15px;
+ margin-bottom: 10px;
+ border-color: ${style.reviewLike.buttonBorderColor};
+ color: ${style.reviewLike.textColor};
+ transition:
+ background-color 0.5s ease,
+ color 0.5s ease;
+ display: flex;
+
+ &:hover {
+ background-color: ${style.reviewLike.textColor};
+ color: white;
+ }
+ `,
+ ]}
+ onClick={createLike}
+ type="button"
+ >
+ {/*<ThumbUpIcon />*/}
+ <div className="ml-1">๋์๋ผ์!</div>
+ <div className="ml-1">{count}</div>
+ </button>
{userID === props.reviewerID ? (
// eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions -- This is intentional
<div | Unknown | ts ignore๋ ํน์ ์ ์ค์ ํด ๋์ผ์ ๊ฑธ๊น์?? |
@@ -9,50 +9,55 @@ import {
generateShadowCSS,
} from '@review-canvas/theme';
+// import ThumbUpIcon from '@/assets/icon/icon-thumb-up.svg';
import { Star } from '@/components/review/star.tsx';
import { useReviewItemStyle } from '@/contexts/style/review-item.ts';
import useMessageToShop from '@/hooks/use-message-to-shop.ts';
-import type { ReplyItem } from '@/services/api-types/review';
+import type { ReviewItemProps } from '@/services/api-types/review';
+import { useReviewService } from '@/services/review.tsx';
import { useConnectedShop } from '@/state/shop.ts';
import { MESSAGE_TYPES } from '@/utils/message';
import Reply from './reply';
-
-interface ReviewItemProps {
- id: number;
- rate: number;
- content: string;
- reviewerID: string;
- reviewer: string;
- replies: ReplyItem[];
-}
+import { useEffect, useState } from 'react';
export default function ReviewItem(props: ReviewItemProps) {
const style = useReviewItemStyle();
const { userID } = useConnectedShop();
+ const reviewService = useReviewService();
const message = useMessageToShop();
+ const [count, setCount] = useState(0);
+
+ useEffect(() => {
+ async function fetchData() {
+ return reviewService.userReviewLike(props.id);
+ }
+ void fetchData().then((response) => {
+ setCount(response.data.count);
+ });
+ }, [props.id, reviewService]);
const edit = () => {
message(MESSAGE_TYPES.OPEN_MODAL, {
type: 'edit_review',
url: `/reviews/${props.id}/edit`,
});
};
-
const deleteReview = () => {
message(MESSAGE_TYPES.OPEN_SELECTING_MODAL, {
type: 'delete',
url: `/reviews/${props.id}/delete`,
});
};
-
const showReviewDetail = () => {
message(MESSAGE_TYPES.OPEN_MODAL, {
type: 'detail',
url: `/reviews/${props.id}`,
});
};
+ const createLike = () => {};
+
return (
<li
css={[
@@ -63,6 +68,7 @@ export default function ReviewItem(props: ReviewItemProps) {
generateFontCSS(style.font),
generateShadowCSS(style.shadow, style.shadowColor),
css`
+ border-color: ${style.borderColor};
background-color: ${style.backgroundColor};
display: flex;
flex-direction: column;
@@ -88,6 +94,68 @@ export default function ReviewItem(props: ReviewItemProps) {
์์ฑ์ <span>{props.reviewer}</span>
</div>
<p className="text-left">{props.content}</p>
+ {/*{style.reviewLike.buttonType !== 'NONE' ? (*/}
+ {/* <button*/}
+ {/* onClick={(evt) => {*/}
+ {/* evt.stopPropagation();*/}
+ {/* if (userID === props.reviewerID) {*/}
+ {/* return;*/}
+ {/* }*/}
+ {/* }}*/}
+ {/* css={[*/}
+ {/* generateBorderRadiusCSS(style.reviewLike.buttonRound),*/}
+ {/* css`*/}
+ {/* border-width: 1px;*/}
+ {/* padding: 2px 6px;*/}
+ {/* margin-top: 15px;*/}
+ {/* margin-bottom: 10px;*/}
+ {/* border-color: ${style.reviewLike.buttonBorderColor};*/}
+ {/* color: ${style.reviewLike.textColor};*/}
+ {/* transition:*/}
+ {/* background-color 0.5s ease,*/}
+ {/* color 0.5s ease;*/}
+ {/* display: flex;*/}
+
+ {/* &:hover {*/}
+ {/* background-color: ${style.reviewLike.textColor};*/}
+ {/* color: white;*/}
+ {/* }*/}
+ {/* `,*/}
+ {/* ]}*/}
+ {/* >*/}
+ {/* <ThumbUpIcon />*/}
+ {/* {style.reviewLike.buttonType === 'THUMB_UP_WITH_TEXT' ? <div className="ml-1">๋์๋ผ์!</div> : null}*/}
+ {/* <div className="ml-1">0</div>*/}
+ {/* </button>*/}
+ {/*) : null}*/}
+ <button
+ css={[
+ generateBorderRadiusCSS(style.reviewLike.buttonRound),
+ css`
+ border-width: 1px;
+ padding: 2px 6px;
+ margin-top: 15px;
+ margin-bottom: 10px;
+ border-color: ${style.reviewLike.buttonBorderColor};
+ color: ${style.reviewLike.textColor};
+ transition:
+ background-color 0.5s ease,
+ color 0.5s ease;
+ display: flex;
+
+ &:hover {
+ background-color: ${style.reviewLike.textColor};
+ color: white;
+ }
+ `,
+ ]}
+ onClick={createLike}
+ type="button"
+ >
+ {/*<ThumbUpIcon />*/}
+ <div className="ml-1">๋์๋ผ์!</div>
+ <div className="ml-1">{count}</div>
+ </button>
{userID === props.reviewerID ? (
// eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions -- This is intentional
<div | Unknown | P3: interface ๊ฐ์ ๊ฒฝ์ฐ ๋ค๋ฅธ ๊ณณ์์๋ ์ฌ๋ฌ ๊ณณ์์ ์ฐ์ผ ์ ์๋๋ฐ, type ๋๋ ํ ๋ฆฌ ๋ฑ์ ๊ณตํต์ ์ธ model์ ์ ์ํด๋๊ณ extends ๋ฑ์ผ๋ก ๊ฐ์ ธ์์ ์ฐ๋ ๋ฐฉ์๋ ๊ณ ๋ คํด ๋ณผ ์ ์์ ๊ฒ ๊ฐ์ต๋๋ค. ReviewItem์ ์๋นํ ๋ง์ ๊ณณ์์ ์ฐ์ด๋ ์์๋ก ์๊ฐ๋์ ์ฐธ๊ณ ํ์๋ฉด ์ข์ ๊ฒ ๊ฐ์ ๋จ๊น๋๋ค! |
@@ -1,3 +1,5 @@
+import {ReviewLikeButtonProps} from "@review-canvas/theme";
+
export type Shadow = 'NONE' | 'SMALL' | 'MEDIUM' | 'LARGE';
export type FocusAreaLayout = 'BEST_REVIEW_TOP' | 'BEST_REVIEW_BOTTOM' | 'BEST_REVIEW_LEFT' | 'BEST_REVIEW_RIGHT';
export type ReviewAreaLayout = 'REVIEW_TOP' | 'REVIEW_BOTTOM' | 'REVIEW_LEFT' | 'REVIEW_RIGHT';
@@ -6,6 +8,7 @@ export type AlignmentPosition = 'LEFT' | 'CENTER' | 'RIGHT';
export type DetailViewType = 'SPREAD' | 'MODAL';
export type PagingType = 'PAGE_NUMBER' | 'SEE_MORE_SCROLL';
export type FilterType = 'LIST' | 'DROPDOWN';
+export type ReviewLikeButtonType = 'NONE' | 'THUMB_UP_WITH_TEXT' | 'THUMB_UP';
export interface Margin {
left: string;
@@ -43,11 +46,11 @@ export interface Round {
}
export interface ReviewLike {
- buttonType: string;
- iconColor: string;
- textColor: string;
buttonBorderColor: string;
buttonRound: Round;
+ buttonType: ReviewLikeButtonType;
+ iconColor: string;
+ textColor: string;
}
export interface ReviewLayout { | TypeScript | Plugin ์ค์น๋ฅผ ํ๋ฉด ์๋ฃ์ธ ์ค ์์๋๋ฐ ์ค์ ์์ Manually๋ก ๋ฐ๊พธ์ด์ค์ผ ํ๊ตฐ์... ํ์ฌ Prettier๋ฅผ ํ์ฑํ ์ํ๋ก ๋ณ๊ฒฝํ์์ต๋๋ค. ์ ์ฒด ํ์ผ์ ์ ์ฉํ์ฌ ๋ค์ ์ปค๋ฐํ๊ฒ ์ต๋๋ค! |
@@ -9,50 +9,55 @@ import {
generateShadowCSS,
} from '@review-canvas/theme';
+// import ThumbUpIcon from '@/assets/icon/icon-thumb-up.svg';
import { Star } from '@/components/review/star.tsx';
import { useReviewItemStyle } from '@/contexts/style/review-item.ts';
import useMessageToShop from '@/hooks/use-message-to-shop.ts';
-import type { ReplyItem } from '@/services/api-types/review';
+import type { ReviewItemProps } from '@/services/api-types/review';
+import { useReviewService } from '@/services/review.tsx';
import { useConnectedShop } from '@/state/shop.ts';
import { MESSAGE_TYPES } from '@/utils/message';
import Reply from './reply';
-
-interface ReviewItemProps {
- id: number;
- rate: number;
- content: string;
- reviewerID: string;
- reviewer: string;
- replies: ReplyItem[];
-}
+import { useEffect, useState } from 'react';
export default function ReviewItem(props: ReviewItemProps) {
const style = useReviewItemStyle();
const { userID } = useConnectedShop();
+ const reviewService = useReviewService();
const message = useMessageToShop();
+ const [count, setCount] = useState(0);
+
+ useEffect(() => {
+ async function fetchData() {
+ return reviewService.userReviewLike(props.id);
+ }
+ void fetchData().then((response) => {
+ setCount(response.data.count);
+ });
+ }, [props.id, reviewService]);
const edit = () => {
message(MESSAGE_TYPES.OPEN_MODAL, {
type: 'edit_review',
url: `/reviews/${props.id}/edit`,
});
};
-
const deleteReview = () => {
message(MESSAGE_TYPES.OPEN_SELECTING_MODAL, {
type: 'delete',
url: `/reviews/${props.id}/delete`,
});
};
-
const showReviewDetail = () => {
message(MESSAGE_TYPES.OPEN_MODAL, {
type: 'detail',
url: `/reviews/${props.id}`,
});
};
+ const createLike = () => {};
+
return (
<li
css={[
@@ -63,6 +68,7 @@ export default function ReviewItem(props: ReviewItemProps) {
generateFontCSS(style.font),
generateShadowCSS(style.shadow, style.shadowColor),
css`
+ border-color: ${style.borderColor};
background-color: ${style.backgroundColor};
display: flex;
flex-direction: column;
@@ -88,6 +94,68 @@ export default function ReviewItem(props: ReviewItemProps) {
์์ฑ์ <span>{props.reviewer}</span>
</div>
<p className="text-left">{props.content}</p>
+ {/*{style.reviewLike.buttonType !== 'NONE' ? (*/}
+ {/* <button*/}
+ {/* onClick={(evt) => {*/}
+ {/* evt.stopPropagation();*/}
+ {/* if (userID === props.reviewerID) {*/}
+ {/* return;*/}
+ {/* }*/}
+ {/* }}*/}
+ {/* css={[*/}
+ {/* generateBorderRadiusCSS(style.reviewLike.buttonRound),*/}
+ {/* css`*/}
+ {/* border-width: 1px;*/}
+ {/* padding: 2px 6px;*/}
+ {/* margin-top: 15px;*/}
+ {/* margin-bottom: 10px;*/}
+ {/* border-color: ${style.reviewLike.buttonBorderColor};*/}
+ {/* color: ${style.reviewLike.textColor};*/}
+ {/* transition:*/}
+ {/* background-color 0.5s ease,*/}
+ {/* color 0.5s ease;*/}
+ {/* display: flex;*/}
+
+ {/* &:hover {*/}
+ {/* background-color: ${style.reviewLike.textColor};*/}
+ {/* color: white;*/}
+ {/* }*/}
+ {/* `,*/}
+ {/* ]}*/}
+ {/* >*/}
+ {/* <ThumbUpIcon />*/}
+ {/* {style.reviewLike.buttonType === 'THUMB_UP_WITH_TEXT' ? <div className="ml-1">๋์๋ผ์!</div> : null}*/}
+ {/* <div className="ml-1">0</div>*/}
+ {/* </button>*/}
+ {/*) : null}*/}
+ <button
+ css={[
+ generateBorderRadiusCSS(style.reviewLike.buttonRound),
+ css`
+ border-width: 1px;
+ padding: 2px 6px;
+ margin-top: 15px;
+ margin-bottom: 10px;
+ border-color: ${style.reviewLike.buttonBorderColor};
+ color: ${style.reviewLike.textColor};
+ transition:
+ background-color 0.5s ease,
+ color 0.5s ease;
+ display: flex;
+
+ &:hover {
+ background-color: ${style.reviewLike.textColor};
+ color: white;
+ }
+ `,
+ ]}
+ onClick={createLike}
+ type="button"
+ >
+ {/*<ThumbUpIcon />*/}
+ <div className="ml-1">๋์๋ผ์!</div>
+ <div className="ml-1">{count}</div>
+ </button>
{userID === props.reviewerID ? (
// eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions -- This is intentional
<div | Unknown | ํ์ธํ์์ต๋๋ค, Alert๋ก ๋ณ๊ฒฝํ๊ฒ ์ต๋๋ค, ๋์๋ผ์!์ ๊ฒฝ์ฐ์๋ ๋ฒํผ์ด ์ ๋๋ก ๋์ํ๋ ๊ฒ์ ํ์ธํ๊ธฐ ์ํด ์์๋ก ๋ฃ์ด๋๊ณ ๋์ค์ ๋์๋ผ์ API๊ฐ ๋ฐฑ์๋์์ ๊ตฌํ๋๋ฉด ๋ก์ง์ผ๋ก ๋์ฒดํ๊ฒ ์ต๋๋ค! |
@@ -9,50 +9,55 @@ import {
generateShadowCSS,
} from '@review-canvas/theme';
+// import ThumbUpIcon from '@/assets/icon/icon-thumb-up.svg';
import { Star } from '@/components/review/star.tsx';
import { useReviewItemStyle } from '@/contexts/style/review-item.ts';
import useMessageToShop from '@/hooks/use-message-to-shop.ts';
-import type { ReplyItem } from '@/services/api-types/review';
+import type { ReviewItemProps } from '@/services/api-types/review';
+import { useReviewService } from '@/services/review.tsx';
import { useConnectedShop } from '@/state/shop.ts';
import { MESSAGE_TYPES } from '@/utils/message';
import Reply from './reply';
-
-interface ReviewItemProps {
- id: number;
- rate: number;
- content: string;
- reviewerID: string;
- reviewer: string;
- replies: ReplyItem[];
-}
+import { useEffect, useState } from 'react';
export default function ReviewItem(props: ReviewItemProps) {
const style = useReviewItemStyle();
const { userID } = useConnectedShop();
+ const reviewService = useReviewService();
const message = useMessageToShop();
+ const [count, setCount] = useState(0);
+
+ useEffect(() => {
+ async function fetchData() {
+ return reviewService.userReviewLike(props.id);
+ }
+ void fetchData().then((response) => {
+ setCount(response.data.count);
+ });
+ }, [props.id, reviewService]);
const edit = () => {
message(MESSAGE_TYPES.OPEN_MODAL, {
type: 'edit_review',
url: `/reviews/${props.id}/edit`,
});
};
-
const deleteReview = () => {
message(MESSAGE_TYPES.OPEN_SELECTING_MODAL, {
type: 'delete',
url: `/reviews/${props.id}/delete`,
});
};
-
const showReviewDetail = () => {
message(MESSAGE_TYPES.OPEN_MODAL, {
type: 'detail',
url: `/reviews/${props.id}`,
});
};
+ const createLike = () => {};
+
return (
<li
css={[
@@ -63,6 +68,7 @@ export default function ReviewItem(props: ReviewItemProps) {
generateFontCSS(style.font),
generateShadowCSS(style.shadow, style.shadowColor),
css`
+ border-color: ${style.borderColor};
background-color: ${style.backgroundColor};
display: flex;
flex-direction: column;
@@ -88,6 +94,68 @@ export default function ReviewItem(props: ReviewItemProps) {
์์ฑ์ <span>{props.reviewer}</span>
</div>
<p className="text-left">{props.content}</p>
+ {/*{style.reviewLike.buttonType !== 'NONE' ? (*/}
+ {/* <button*/}
+ {/* onClick={(evt) => {*/}
+ {/* evt.stopPropagation();*/}
+ {/* if (userID === props.reviewerID) {*/}
+ {/* return;*/}
+ {/* }*/}
+ {/* }}*/}
+ {/* css={[*/}
+ {/* generateBorderRadiusCSS(style.reviewLike.buttonRound),*/}
+ {/* css`*/}
+ {/* border-width: 1px;*/}
+ {/* padding: 2px 6px;*/}
+ {/* margin-top: 15px;*/}
+ {/* margin-bottom: 10px;*/}
+ {/* border-color: ${style.reviewLike.buttonBorderColor};*/}
+ {/* color: ${style.reviewLike.textColor};*/}
+ {/* transition:*/}
+ {/* background-color 0.5s ease,*/}
+ {/* color 0.5s ease;*/}
+ {/* display: flex;*/}
+
+ {/* &:hover {*/}
+ {/* background-color: ${style.reviewLike.textColor};*/}
+ {/* color: white;*/}
+ {/* }*/}
+ {/* `,*/}
+ {/* ]}*/}
+ {/* >*/}
+ {/* <ThumbUpIcon />*/}
+ {/* {style.reviewLike.buttonType === 'THUMB_UP_WITH_TEXT' ? <div className="ml-1">๋์๋ผ์!</div> : null}*/}
+ {/* <div className="ml-1">0</div>*/}
+ {/* </button>*/}
+ {/*) : null}*/}
+ <button
+ css={[
+ generateBorderRadiusCSS(style.reviewLike.buttonRound),
+ css`
+ border-width: 1px;
+ padding: 2px 6px;
+ margin-top: 15px;
+ margin-bottom: 10px;
+ border-color: ${style.reviewLike.buttonBorderColor};
+ color: ${style.reviewLike.textColor};
+ transition:
+ background-color 0.5s ease,
+ color 0.5s ease;
+ display: flex;
+
+ &:hover {
+ background-color: ${style.reviewLike.textColor};
+ color: white;
+ }
+ `,
+ ]}
+ onClick={createLike}
+ type="button"
+ >
+ {/*<ThumbUpIcon />*/}
+ <div className="ml-1">๋์๋ผ์!</div>
+ <div className="ml-1">{count}</div>
+ </button>
{userID === props.reviewerID ? (
// eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions -- This is intentional
<div | Unknown | ํ์ธํ์์ต๋๋ค, Import๋ก ๋์ฒดํ๊ฒ ์ต๋๋ค! |
@@ -9,50 +9,55 @@ import {
generateShadowCSS,
} from '@review-canvas/theme';
+// import ThumbUpIcon from '@/assets/icon/icon-thumb-up.svg';
import { Star } from '@/components/review/star.tsx';
import { useReviewItemStyle } from '@/contexts/style/review-item.ts';
import useMessageToShop from '@/hooks/use-message-to-shop.ts';
-import type { ReplyItem } from '@/services/api-types/review';
+import type { ReviewItemProps } from '@/services/api-types/review';
+import { useReviewService } from '@/services/review.tsx';
import { useConnectedShop } from '@/state/shop.ts';
import { MESSAGE_TYPES } from '@/utils/message';
import Reply from './reply';
-
-interface ReviewItemProps {
- id: number;
- rate: number;
- content: string;
- reviewerID: string;
- reviewer: string;
- replies: ReplyItem[];
-}
+import { useEffect, useState } from 'react';
export default function ReviewItem(props: ReviewItemProps) {
const style = useReviewItemStyle();
const { userID } = useConnectedShop();
+ const reviewService = useReviewService();
const message = useMessageToShop();
+ const [count, setCount] = useState(0);
+
+ useEffect(() => {
+ async function fetchData() {
+ return reviewService.userReviewLike(props.id);
+ }
+ void fetchData().then((response) => {
+ setCount(response.data.count);
+ });
+ }, [props.id, reviewService]);
const edit = () => {
message(MESSAGE_TYPES.OPEN_MODAL, {
type: 'edit_review',
url: `/reviews/${props.id}/edit`,
});
};
-
const deleteReview = () => {
message(MESSAGE_TYPES.OPEN_SELECTING_MODAL, {
type: 'delete',
url: `/reviews/${props.id}/delete`,
});
};
-
const showReviewDetail = () => {
message(MESSAGE_TYPES.OPEN_MODAL, {
type: 'detail',
url: `/reviews/${props.id}`,
});
};
+ const createLike = () => {};
+
return (
<li
css={[
@@ -63,6 +68,7 @@ export default function ReviewItem(props: ReviewItemProps) {
generateFontCSS(style.font),
generateShadowCSS(style.shadow, style.shadowColor),
css`
+ border-color: ${style.borderColor};
background-color: ${style.backgroundColor};
display: flex;
flex-direction: column;
@@ -88,6 +94,68 @@ export default function ReviewItem(props: ReviewItemProps) {
์์ฑ์ <span>{props.reviewer}</span>
</div>
<p className="text-left">{props.content}</p>
+ {/*{style.reviewLike.buttonType !== 'NONE' ? (*/}
+ {/* <button*/}
+ {/* onClick={(evt) => {*/}
+ {/* evt.stopPropagation();*/}
+ {/* if (userID === props.reviewerID) {*/}
+ {/* return;*/}
+ {/* }*/}
+ {/* }}*/}
+ {/* css={[*/}
+ {/* generateBorderRadiusCSS(style.reviewLike.buttonRound),*/}
+ {/* css`*/}
+ {/* border-width: 1px;*/}
+ {/* padding: 2px 6px;*/}
+ {/* margin-top: 15px;*/}
+ {/* margin-bottom: 10px;*/}
+ {/* border-color: ${style.reviewLike.buttonBorderColor};*/}
+ {/* color: ${style.reviewLike.textColor};*/}
+ {/* transition:*/}
+ {/* background-color 0.5s ease,*/}
+ {/* color 0.5s ease;*/}
+ {/* display: flex;*/}
+
+ {/* &:hover {*/}
+ {/* background-color: ${style.reviewLike.textColor};*/}
+ {/* color: white;*/}
+ {/* }*/}
+ {/* `,*/}
+ {/* ]}*/}
+ {/* >*/}
+ {/* <ThumbUpIcon />*/}
+ {/* {style.reviewLike.buttonType === 'THUMB_UP_WITH_TEXT' ? <div className="ml-1">๋์๋ผ์!</div> : null}*/}
+ {/* <div className="ml-1">0</div>*/}
+ {/* </button>*/}
+ {/*) : null}*/}
+ <button
+ css={[
+ generateBorderRadiusCSS(style.reviewLike.buttonRound),
+ css`
+ border-width: 1px;
+ padding: 2px 6px;
+ margin-top: 15px;
+ margin-bottom: 10px;
+ border-color: ${style.reviewLike.buttonBorderColor};
+ color: ${style.reviewLike.textColor};
+ transition:
+ background-color 0.5s ease,
+ color 0.5s ease;
+ display: flex;
+
+ &:hover {
+ background-color: ${style.reviewLike.textColor};
+ color: white;
+ }
+ `,
+ ]}
+ onClick={createLike}
+ type="button"
+ >
+ {/*<ThumbUpIcon />*/}
+ <div className="ml-1">๋์๋ผ์!</div>
+ <div className="ml-1">{count}</div>
+ </button>
{userID === props.reviewerID ? (
// eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions -- This is intentional
<div | Unknown | ํ
์คํธ๋ฅผ ํ ๋ ReviewLikeButton์ด 'None'์ผ๋ก ๊ณ ์ ์ด๋ผ ํ๋์ฝ๋ฉ์ผ๋ก ReviewLikeButton์ ๋ฐ๊พธ๊ณ ์์์ต๋๋ค. ๊ทธ ๊ณผ์ ์์ ์กฐ๊ฑด๋ฌธ ๊ฒฝ๊ณ ๊ฐ ๋ฐ์ํ์ฌ ์ค์ ํด๋์๋๋ฐ ํ๋์ฝ๋ฉ๋ง ์ง์ฐ๊ณ ์ด๊ทธ๋
ธ์ด๋ฅผ ๋ชป ์ง์ ๋ค์... ์ง์์ ๋ฐ์ํ๊ฒ ์ต๋๋ค! |
@@ -9,50 +9,55 @@ import {
generateShadowCSS,
} from '@review-canvas/theme';
+// import ThumbUpIcon from '@/assets/icon/icon-thumb-up.svg';
import { Star } from '@/components/review/star.tsx';
import { useReviewItemStyle } from '@/contexts/style/review-item.ts';
import useMessageToShop from '@/hooks/use-message-to-shop.ts';
-import type { ReplyItem } from '@/services/api-types/review';
+import type { ReviewItemProps } from '@/services/api-types/review';
+import { useReviewService } from '@/services/review.tsx';
import { useConnectedShop } from '@/state/shop.ts';
import { MESSAGE_TYPES } from '@/utils/message';
import Reply from './reply';
-
-interface ReviewItemProps {
- id: number;
- rate: number;
- content: string;
- reviewerID: string;
- reviewer: string;
- replies: ReplyItem[];
-}
+import { useEffect, useState } from 'react';
export default function ReviewItem(props: ReviewItemProps) {
const style = useReviewItemStyle();
const { userID } = useConnectedShop();
+ const reviewService = useReviewService();
const message = useMessageToShop();
+ const [count, setCount] = useState(0);
+
+ useEffect(() => {
+ async function fetchData() {
+ return reviewService.userReviewLike(props.id);
+ }
+ void fetchData().then((response) => {
+ setCount(response.data.count);
+ });
+ }, [props.id, reviewService]);
const edit = () => {
message(MESSAGE_TYPES.OPEN_MODAL, {
type: 'edit_review',
url: `/reviews/${props.id}/edit`,
});
};
-
const deleteReview = () => {
message(MESSAGE_TYPES.OPEN_SELECTING_MODAL, {
type: 'delete',
url: `/reviews/${props.id}/delete`,
});
};
-
const showReviewDetail = () => {
message(MESSAGE_TYPES.OPEN_MODAL, {
type: 'detail',
url: `/reviews/${props.id}`,
});
};
+ const createLike = () => {};
+
return (
<li
css={[
@@ -63,6 +68,7 @@ export default function ReviewItem(props: ReviewItemProps) {
generateFontCSS(style.font),
generateShadowCSS(style.shadow, style.shadowColor),
css`
+ border-color: ${style.borderColor};
background-color: ${style.backgroundColor};
display: flex;
flex-direction: column;
@@ -88,6 +94,68 @@ export default function ReviewItem(props: ReviewItemProps) {
์์ฑ์ <span>{props.reviewer}</span>
</div>
<p className="text-left">{props.content}</p>
+ {/*{style.reviewLike.buttonType !== 'NONE' ? (*/}
+ {/* <button*/}
+ {/* onClick={(evt) => {*/}
+ {/* evt.stopPropagation();*/}
+ {/* if (userID === props.reviewerID) {*/}
+ {/* return;*/}
+ {/* }*/}
+ {/* }}*/}
+ {/* css={[*/}
+ {/* generateBorderRadiusCSS(style.reviewLike.buttonRound),*/}
+ {/* css`*/}
+ {/* border-width: 1px;*/}
+ {/* padding: 2px 6px;*/}
+ {/* margin-top: 15px;*/}
+ {/* margin-bottom: 10px;*/}
+ {/* border-color: ${style.reviewLike.buttonBorderColor};*/}
+ {/* color: ${style.reviewLike.textColor};*/}
+ {/* transition:*/}
+ {/* background-color 0.5s ease,*/}
+ {/* color 0.5s ease;*/}
+ {/* display: flex;*/}
+
+ {/* &:hover {*/}
+ {/* background-color: ${style.reviewLike.textColor};*/}
+ {/* color: white;*/}
+ {/* }*/}
+ {/* `,*/}
+ {/* ]}*/}
+ {/* >*/}
+ {/* <ThumbUpIcon />*/}
+ {/* {style.reviewLike.buttonType === 'THUMB_UP_WITH_TEXT' ? <div className="ml-1">๋์๋ผ์!</div> : null}*/}
+ {/* <div className="ml-1">0</div>*/}
+ {/* </button>*/}
+ {/*) : null}*/}
+ <button
+ css={[
+ generateBorderRadiusCSS(style.reviewLike.buttonRound),
+ css`
+ border-width: 1px;
+ padding: 2px 6px;
+ margin-top: 15px;
+ margin-bottom: 10px;
+ border-color: ${style.reviewLike.buttonBorderColor};
+ color: ${style.reviewLike.textColor};
+ transition:
+ background-color 0.5s ease,
+ color 0.5s ease;
+ display: flex;
+
+ &:hover {
+ background-color: ${style.reviewLike.textColor};
+ color: white;
+ }
+ `,
+ ]}
+ onClick={createLike}
+ type="button"
+ >
+ {/*<ThumbUpIcon />*/}
+ <div className="ml-1">๋์๋ผ์!</div>
+ <div className="ml-1">{count}</div>
+ </button>
{userID === props.reviewerID ? (
// eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions -- This is intentional
<div | Unknown | service/api-types/review.tsx์ ๊ณตํต ๋ชจ๋ธ๋ก ์ ์ธํ์ฌ export ๋ฐ import ํ์์ต๋๋ค! |
@@ -0,0 +1,18 @@
+package com.codesquad.baseball09.controller;
+
+import java.text.SimpleDateFormat;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@RequestMapping("hcheck")
+public class HealthCheckRestController {
+
+ private final static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+
+ @GetMapping
+ public String healthCheck() {
+ return dateFormat.format(System.currentTimeMillis());
+ }
+} | Java | Spring Boot Actuator ์ฌ์ฉ ๊ฒํ ํด๋ด
๋๋ค.
https://supawer0728.github.io/2018/05/12/spring-actuator/ |
@@ -0,0 +1,99 @@
+package com.codesquad.baseball09.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import org.apache.commons.lang3.builder.ToStringBuilder;
+
+public class BattingLog {
+
+ private Long id;
+ private Long gameId;
+ private Long playerId;
+ private int inning;
+ private Status status;
+
+ private BattingLog(Long id, Long gameId, Long playerId, int inning,
+ Status status) {
+ this.id = id;
+ this.gameId = gameId;
+ this.playerId = playerId;
+ this.inning = inning;
+ this.status = status;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public Long getGameId() {
+ return gameId;
+ }
+
+ public Long getPlayerId() {
+ return playerId;
+ }
+
+ public int getInning() {
+ return inning;
+ }
+
+ public Status getStatus() {
+ return status;
+ }
+
+ @JsonIgnore
+ public int getStatusInt() {
+ return status.getValue();
+ }
+
+ public static class Builder {
+
+ private Long id;
+ private Long gameId;
+ private Long playerId;
+ private int inning;
+ private Status status;
+
+ public Builder() {
+ }
+
+ public Builder id(Long id) {
+ this.id = id;
+ return this;
+ }
+
+ public Builder gameId(Long gameId) {
+ this.gameId = gameId;
+ return this;
+ }
+
+ public Builder playerId(Long playerId) {
+ this.playerId = playerId;
+ return this;
+ }
+
+ public Builder inning(int inning) {
+ this.inning = inning;
+ return this;
+ }
+
+ public Builder status(int value) {
+ this.status = Status.of(value);
+ return this;
+ }
+
+ public BattingLog build() {
+ return new BattingLog(id, gameId, playerId, inning, status);
+ }
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this)
+ .append("id", id)
+ .append("gameId", gameId)
+ .append("playerId", playerId)
+ .append("inning", inning)
+ .append("status", status)
+ .toString();
+ }
+} | Java | ์ ์ ํ builder ์ฌ์ฉ ์ข๋ค์. ๐ |
@@ -0,0 +1,282 @@
+package com.codesquad.baseball09.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import java.util.List;
+import org.apache.commons.lang3.builder.ToStringBuilder;
+import org.apache.commons.lang3.builder.ToStringStyle;
+
+public class Board {
+
+ private Long gameId;
+ private int inning;
+
+ @JsonIgnore
+ private Long homeId;
+ private String homeName;
+ private int homeScore;
+ @JsonIgnore
+ private int homeOrder;
+
+ @JsonIgnore
+ private Long awayId;
+ private String awayName;
+ private int awayScore;
+ @JsonIgnore
+ private int awayOrder;
+
+ private boolean isBottom;
+
+ private Game game;
+ private InningStatus status;
+ private List<BattingLog> log;
+
+ private Board(Long gameId, int inning, Long homeId, String homeName, int homeScore, int homeOrder,
+ Long awayId, String awayName, int awayScore, int awayOrder, boolean isBottom, Game game,
+ InningStatus status,
+ List<BattingLog> log) {
+ this.gameId = gameId;
+ this.inning = inning;
+ this.homeId = homeId;
+ this.homeName = homeName;
+ this.homeScore = homeScore;
+ this.homeOrder = homeOrder;
+ this.awayId = awayId;
+ this.awayName = awayName;
+ this.awayScore = awayScore;
+ this.awayOrder = awayOrder;
+ this.isBottom = isBottom;
+ this.game = game;
+ this.status = status;
+ this.log = log;
+ }
+
+ public void change() {
+ this.homeOrder = 0;
+ this.awayOrder = 0;
+
+ if (isBottom) {
+ isBottom = false;
+ this.inning++;
+ } else {
+ isBottom = true;
+ }
+ }
+
+ public Long getGameId() {
+ return gameId;
+ }
+
+ public int getInning() {
+ return inning;
+ }
+
+ public Long getHomeId() {
+ return homeId;
+ }
+
+ public String getHomeName() {
+ return homeName;
+ }
+
+ public int getHomeScore() {
+ return homeScore;
+ }
+
+ public int getHomeOrder() {
+ return homeOrder;
+ }
+
+ public Long getAwayId() {
+ return awayId;
+ }
+
+ public String getAwayName() {
+ return awayName;
+ }
+
+ public int getAwayScore() {
+ return awayScore;
+ }
+
+ public int getAwayOrder() {
+ return awayOrder;
+ }
+
+ public boolean isBottom() {
+ return isBottom;
+ }
+
+ public Game getGame() {
+ return game;
+ }
+
+ public InningStatus getStatus() {
+ return status;
+ }
+
+ public List<BattingLog> getLog() {
+ return log;
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
+ .append("gameId", gameId)
+ .append("inning", inning)
+ .append("homeId", homeId)
+ .append("homeName", homeName)
+ .append("homeScore", homeScore)
+ .append("homeOrder", homeOrder)
+ .append("awayId", awayId)
+ .append("awayName", awayName)
+ .append("awayScore", awayScore)
+ .append("awayOrder", awayOrder)
+ .append("isBottom", isBottom)
+ .append("game", game)
+ .append("status", status)
+ .append("log", log)
+ .toString();
+ }
+
+ public static final class Builder {
+
+ private Long gameId;
+ private int inning;
+ private String homeName;
+ private Long homeId;
+ private int homeScore;
+ private int homeOrder;
+ private Long awayId;
+ private String awayName;
+ private int awayScore;
+ private int awayOrder;
+ private boolean isBottom;
+ private Game game;
+ private InningStatus status;
+ private List<BattingLog> log;
+
+ private Builder() {
+ }
+
+ public static Builder of() {
+ return new Builder();
+ }
+
+ public Builder(Board board) {
+ this.gameId = board.gameId;
+ this.inning = board.inning;
+ this.homeId = board.homeId;
+ this.homeName = board.homeName;
+ this.homeScore = board.homeScore;
+ this.homeOrder = board.homeOrder;
+ this.awayId = board.awayId;
+ this.awayName = board.awayName;
+ this.awayScore = board.awayScore;
+ this.awayOrder = board.awayOrder;
+ this.isBottom = board.isBottom;
+ this.game = board.game;
+ this.status = board.status;
+ this.log = board.log;
+ }
+
+ public Builder gameId(Long gameId) {
+ this.gameId = gameId;
+ return this;
+ }
+
+ public Builder inning(int inning) {
+ this.inning = inning;
+ return this;
+ }
+
+ public Builder homeId(Long homeId) {
+ this.homeId = homeId;
+ return this;
+ }
+
+ public Builder homeName(String homeName) {
+ this.homeName = homeName;
+ return this;
+ }
+
+ public Builder homeScore(int homeScore) {
+ this.homeScore = homeScore;
+ return this;
+ }
+
+ public Builder homeOrder(int homeOrder) {
+ if (homeOrder > 8) {
+ this.homeOrder = 0;
+ } else {
+ this.homeOrder = homeOrder;
+ }
+ return this;
+ }
+
+ public Builder awayId(Long awayId) {
+ this.awayId = awayId;
+ return this;
+ }
+
+ public Builder awayName(String awayName) {
+ this.awayName = awayName;
+ return this;
+ }
+
+ public Builder awayScore(int awayScore) {
+ this.awayScore = awayScore;
+ return this;
+ }
+
+ public Builder awayOrder(int awayOrder) {
+ if (awayOrder > 8) {
+ this.awayOrder = 0;
+ } else {
+ this.awayOrder = awayOrder;
+ }
+ return this;
+ }
+
+ public Builder isBottom(boolean isBottom) {
+ this.isBottom = isBottom;
+ return this;
+ }
+
+ public Builder game(Game game) {
+ this.game = game;
+ this.homeId(game.getHomeTeamId());
+ this.awayId(game.getAwayTeamId());
+ return this;
+ }
+
+ public Builder status(InningStatus status) {
+ this.status = status;
+ return this;
+ }
+
+ public Builder score(List<Score> scores) {
+ for (int i = 0; i < scores.size(); i++) {
+ Score score = scores.get(i);
+ if (score.getTeamId().equals(homeId)) {
+ homeName(score.getName());
+ homeScore(score.getScore());
+ }
+ if (score.getTeamId().equals(awayId)) {
+ awayName(score.getName());
+ awayScore(score.getScore());
+ }
+ }
+ return this;
+ }
+
+ public Builder log(List<BattingLog> log) {
+ this.log = log;
+ return this;
+ }
+
+ public Board build() {
+ return new Board(gameId, inning, homeId, homeName, homeScore, homeOrder, awayId, awayName,
+ awayScore, awayOrder, isBottom, game, status, log);
+ }
+ }
+} | Java | ์ธ์๊ฐ ๋ง์ด ํ์ํ ์์ฑ์๋ฅผ `private` ํ๊ฒ ๊ฐ๋ฆฌ๋ ๊ตฌํ ์์ฃผ ์ข์ต๋๋ค! ๐ฏ ๐ฅ |
@@ -0,0 +1,282 @@
+package com.codesquad.baseball09.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import java.util.List;
+import org.apache.commons.lang3.builder.ToStringBuilder;
+import org.apache.commons.lang3.builder.ToStringStyle;
+
+public class Board {
+
+ private Long gameId;
+ private int inning;
+
+ @JsonIgnore
+ private Long homeId;
+ private String homeName;
+ private int homeScore;
+ @JsonIgnore
+ private int homeOrder;
+
+ @JsonIgnore
+ private Long awayId;
+ private String awayName;
+ private int awayScore;
+ @JsonIgnore
+ private int awayOrder;
+
+ private boolean isBottom;
+
+ private Game game;
+ private InningStatus status;
+ private List<BattingLog> log;
+
+ private Board(Long gameId, int inning, Long homeId, String homeName, int homeScore, int homeOrder,
+ Long awayId, String awayName, int awayScore, int awayOrder, boolean isBottom, Game game,
+ InningStatus status,
+ List<BattingLog> log) {
+ this.gameId = gameId;
+ this.inning = inning;
+ this.homeId = homeId;
+ this.homeName = homeName;
+ this.homeScore = homeScore;
+ this.homeOrder = homeOrder;
+ this.awayId = awayId;
+ this.awayName = awayName;
+ this.awayScore = awayScore;
+ this.awayOrder = awayOrder;
+ this.isBottom = isBottom;
+ this.game = game;
+ this.status = status;
+ this.log = log;
+ }
+
+ public void change() {
+ this.homeOrder = 0;
+ this.awayOrder = 0;
+
+ if (isBottom) {
+ isBottom = false;
+ this.inning++;
+ } else {
+ isBottom = true;
+ }
+ }
+
+ public Long getGameId() {
+ return gameId;
+ }
+
+ public int getInning() {
+ return inning;
+ }
+
+ public Long getHomeId() {
+ return homeId;
+ }
+
+ public String getHomeName() {
+ return homeName;
+ }
+
+ public int getHomeScore() {
+ return homeScore;
+ }
+
+ public int getHomeOrder() {
+ return homeOrder;
+ }
+
+ public Long getAwayId() {
+ return awayId;
+ }
+
+ public String getAwayName() {
+ return awayName;
+ }
+
+ public int getAwayScore() {
+ return awayScore;
+ }
+
+ public int getAwayOrder() {
+ return awayOrder;
+ }
+
+ public boolean isBottom() {
+ return isBottom;
+ }
+
+ public Game getGame() {
+ return game;
+ }
+
+ public InningStatus getStatus() {
+ return status;
+ }
+
+ public List<BattingLog> getLog() {
+ return log;
+ }
+
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
+ .append("gameId", gameId)
+ .append("inning", inning)
+ .append("homeId", homeId)
+ .append("homeName", homeName)
+ .append("homeScore", homeScore)
+ .append("homeOrder", homeOrder)
+ .append("awayId", awayId)
+ .append("awayName", awayName)
+ .append("awayScore", awayScore)
+ .append("awayOrder", awayOrder)
+ .append("isBottom", isBottom)
+ .append("game", game)
+ .append("status", status)
+ .append("log", log)
+ .toString();
+ }
+
+ public static final class Builder {
+
+ private Long gameId;
+ private int inning;
+ private String homeName;
+ private Long homeId;
+ private int homeScore;
+ private int homeOrder;
+ private Long awayId;
+ private String awayName;
+ private int awayScore;
+ private int awayOrder;
+ private boolean isBottom;
+ private Game game;
+ private InningStatus status;
+ private List<BattingLog> log;
+
+ private Builder() {
+ }
+
+ public static Builder of() {
+ return new Builder();
+ }
+
+ public Builder(Board board) {
+ this.gameId = board.gameId;
+ this.inning = board.inning;
+ this.homeId = board.homeId;
+ this.homeName = board.homeName;
+ this.homeScore = board.homeScore;
+ this.homeOrder = board.homeOrder;
+ this.awayId = board.awayId;
+ this.awayName = board.awayName;
+ this.awayScore = board.awayScore;
+ this.awayOrder = board.awayOrder;
+ this.isBottom = board.isBottom;
+ this.game = board.game;
+ this.status = board.status;
+ this.log = board.log;
+ }
+
+ public Builder gameId(Long gameId) {
+ this.gameId = gameId;
+ return this;
+ }
+
+ public Builder inning(int inning) {
+ this.inning = inning;
+ return this;
+ }
+
+ public Builder homeId(Long homeId) {
+ this.homeId = homeId;
+ return this;
+ }
+
+ public Builder homeName(String homeName) {
+ this.homeName = homeName;
+ return this;
+ }
+
+ public Builder homeScore(int homeScore) {
+ this.homeScore = homeScore;
+ return this;
+ }
+
+ public Builder homeOrder(int homeOrder) {
+ if (homeOrder > 8) {
+ this.homeOrder = 0;
+ } else {
+ this.homeOrder = homeOrder;
+ }
+ return this;
+ }
+
+ public Builder awayId(Long awayId) {
+ this.awayId = awayId;
+ return this;
+ }
+
+ public Builder awayName(String awayName) {
+ this.awayName = awayName;
+ return this;
+ }
+
+ public Builder awayScore(int awayScore) {
+ this.awayScore = awayScore;
+ return this;
+ }
+
+ public Builder awayOrder(int awayOrder) {
+ if (awayOrder > 8) {
+ this.awayOrder = 0;
+ } else {
+ this.awayOrder = awayOrder;
+ }
+ return this;
+ }
+
+ public Builder isBottom(boolean isBottom) {
+ this.isBottom = isBottom;
+ return this;
+ }
+
+ public Builder game(Game game) {
+ this.game = game;
+ this.homeId(game.getHomeTeamId());
+ this.awayId(game.getAwayTeamId());
+ return this;
+ }
+
+ public Builder status(InningStatus status) {
+ this.status = status;
+ return this;
+ }
+
+ public Builder score(List<Score> scores) {
+ for (int i = 0; i < scores.size(); i++) {
+ Score score = scores.get(i);
+ if (score.getTeamId().equals(homeId)) {
+ homeName(score.getName());
+ homeScore(score.getScore());
+ }
+ if (score.getTeamId().equals(awayId)) {
+ awayName(score.getName());
+ awayScore(score.getScore());
+ }
+ }
+ return this;
+ }
+
+ public Builder log(List<BattingLog> log) {
+ this.log = log;
+ return this;
+ }
+
+ public Board build() {
+ return new Board(gameId, inning, homeId, homeName, homeScore, homeOrder, awayId, awayName,
+ awayScore, awayOrder, isBottom, game, status, log);
+ }
+ }
+} | Java | `else` ์์ด ๊ตฌํํด๋ณผ ์ ์์ง ์์์๊น์? |
@@ -0,0 +1,196 @@
+package com.codesquad.baseball09.model;
+
+import static com.codesquad.baseball09.model.Status.BALL;
+import static com.codesquad.baseball09.model.Status.HIT;
+import static com.codesquad.baseball09.model.Status.OUT;
+import static com.codesquad.baseball09.model.Status.STRIKE;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+
+public class InningStatus {
+
+ @JsonIgnore
+ private Long id;
+ private Long gameId;
+ private int inning;
+ private int strike;
+ private int ball;
+ private int out;
+ private int hit;
+
+ public InningStatus(Long id, Long gameId, int inning, int strike, int ball, int out, int hit) {
+ this.id = id;
+ this.gameId = gameId;
+ this.inning = inning;
+ this.strike = strike;
+ this.ball = ball;
+ this.out = out;
+ this.hit = hit;
+ }
+
+ private InningStatus(Long gameId, int inning, int strike, int ball, int out, int hit) {
+ this.gameId = gameId;
+ this.inning = inning;
+ this.strike = strike;
+ this.ball = ball;
+ this.out = out;
+ this.hit = hit;
+ }
+
+ public InningStatus(int strike, int ball, int out, int hit) {
+ this.strike = strike;
+ this.ball = ball;
+ this.out = out;
+ this.hit = hit;
+ }
+
+ public static InningStatus of(Long gameId, int inning, int strike, int ball, int out, int hit) {
+ return new InningStatus(gameId, inning, strike, ball, out, hit);
+ }
+
+ public int plus(Status status) {
+ int value = 0;
+
+ if (STRIKE.equals(status)) {
+ strike++;
+ value = checkThreeStrike();
+ } else if (BALL.equals(status)) {
+ ball++;
+ value = checkFourBall();
+ } else if (OUT.equals(status)) {
+ out++;
+ resetStrikeAndBall();
+ value = checkThreeOut();
+ } else if (HIT.equals(status)) {
+ hit++;
+ resetStrikeAndBall();
+ value = checkFourHit();
+ }
+ return value;
+ }
+
+ private void resetStrikeAndBall() {
+ this.strike = 0;
+ this.ball = 0;
+ }
+
+ private void resetAll() {
+ resetStrikeAndBall();
+ this.out = 0;
+ this.hit = 0;
+ }
+
+ private int checkFourHit() {
+ if (this.hit == 4) {
+ resetStrikeAndBall();
+ this.hit--;
+ return 1;
+ }
+ return 0;
+ }
+
+ private int checkThreeOut() {
+ if (this.out == 3) {
+ resetAll();
+ return -1;
+ }
+ return 0;
+ }
+
+ private int checkFourBall() {
+ if (this.ball == 4) {
+ resetStrikeAndBall();
+ plus(HIT);
+ }
+ return 2;
+ }
+
+ private int checkThreeStrike() {
+ if (this.strike == 3) {
+ resetStrikeAndBall();
+ plus(OUT);
+ }
+ return 2;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public Long getGameId() {
+ return gameId;
+ }
+
+ public int getInning() {
+ return inning;
+ }
+
+ public int getStrike() {
+ return strike;
+ }
+
+ public int getBall() {
+ return ball;
+ }
+
+ public int getOut() {
+ return out;
+ }
+
+ public int getHit() {
+ return hit;
+ }
+
+ public static final class Builder {
+
+ private Long id;
+ private Long gameId;
+ private int inning;
+ private int strike;
+ private int ball;
+ private int out;
+ private int hit;
+
+ public Builder() {
+ }
+
+ public Builder id(Long id) {
+ this.id = id;
+ return this;
+ }
+
+ public Builder gameId(Long gameId) {
+ this.gameId = gameId;
+ return this;
+ }
+
+ public Builder inning(int inning) {
+ this.inning = inning;
+ return this;
+ }
+
+ public Builder strike(int strike) {
+ this.strike = strike;
+ return this;
+ }
+
+ public Builder ball(int ball) {
+ this.ball = ball;
+ return this;
+ }
+
+ public Builder out(int out) {
+ this.out = out;
+ return this;
+ }
+
+ public Builder hit(int hit) {
+ this.hit = hit;
+ return this;
+ }
+
+ public InningStatus build() {
+ return new InningStatus(id, gameId, inning, strike, ball, out, hit);
+ }
+ }
+} | Java | ๋ค ๊ฐ์ ํ์์ ๋ํด ๊ฒฐ๊ณผ๋ฅผ ๋ฐ์ํด์ผ ํ๋ค ๋ณด๋, ๋ค ๊ฐ์ `case` ๋ฅผ ๊ฐ๋ `switch` ๋ฌธ๊ณผ ๊ฐ์ ๊ตฌํ์ด ๋์ค๊ฒ ๋์์ต๋๋ค.
์ด๋ฅผ ์ด๋ป๊ฒ ๊ฐ์ฒด์งํฅ์ ์ผ๋ก, ๊น๋ํ๊ฒ ํ ์ ์์๊น์.
๋จ์ํ ์๊ฐํด๋ณด๊ธฐ๋ก๋ `InningCount` ๋ผ๋ ๊ฐ์ฒด๊ฐ `BallCount` ๊ฐ์ฒด๋ฅผ ๋ค์ ๊ฐ๊ณ ์์ผ๋ฉด์, ์์ ์นด์ดํธ์ ๋ณผ ์นด์ดํธ๋ฅผ ๊ด๋ฆฌํ๋ ๋ฐฉ์์ด ๋ ์ค๋ฆ
๋๋ค.
๊ฐ ํ์์ ํด๋นํ๋ `enum` ์ ๊ฐ์ฒด์ ๋๊ธฐ๋ฉด ๊ทธ ๊ฐ์ฒด๊ฐ ๋๋จธ์ง ์ผ์ ์ฒ๋ฆฌํ๊ฒ ๋๋ ๊ฑฐ์ฃ .
ํ ๋ฒ ์๊ฐํด๋ณด์๊ณ ๋๋๊ธ๋ก ๊ณ์ ๊ตฌํ์ ๋ํด ์๊ฒฌ ๋๋ ๋ณด๋ฉด ์ฌ๋ฐ๊ฒ ๋ค์. |
@@ -0,0 +1,18 @@
+package com.codesquad.baseball09.controller;
+
+import java.text.SimpleDateFormat;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@RequestMapping("hcheck")
+public class HealthCheckRestController {
+
+ private final static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+
+ @GetMapping
+ public String healthCheck() {
+ return dateFormat.format(System.currentTimeMillis());
+ }
+} | Java | ๋ค์ ํ๋ก์ ํธ์ ํ๋ฒ ์ ์ฉํด๋ณด๊ฒ ์ต๋๋ค |
@@ -0,0 +1,196 @@
+package com.codesquad.baseball09.model;
+
+import static com.codesquad.baseball09.model.Status.BALL;
+import static com.codesquad.baseball09.model.Status.HIT;
+import static com.codesquad.baseball09.model.Status.OUT;
+import static com.codesquad.baseball09.model.Status.STRIKE;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+
+public class InningStatus {
+
+ @JsonIgnore
+ private Long id;
+ private Long gameId;
+ private int inning;
+ private int strike;
+ private int ball;
+ private int out;
+ private int hit;
+
+ public InningStatus(Long id, Long gameId, int inning, int strike, int ball, int out, int hit) {
+ this.id = id;
+ this.gameId = gameId;
+ this.inning = inning;
+ this.strike = strike;
+ this.ball = ball;
+ this.out = out;
+ this.hit = hit;
+ }
+
+ private InningStatus(Long gameId, int inning, int strike, int ball, int out, int hit) {
+ this.gameId = gameId;
+ this.inning = inning;
+ this.strike = strike;
+ this.ball = ball;
+ this.out = out;
+ this.hit = hit;
+ }
+
+ public InningStatus(int strike, int ball, int out, int hit) {
+ this.strike = strike;
+ this.ball = ball;
+ this.out = out;
+ this.hit = hit;
+ }
+
+ public static InningStatus of(Long gameId, int inning, int strike, int ball, int out, int hit) {
+ return new InningStatus(gameId, inning, strike, ball, out, hit);
+ }
+
+ public int plus(Status status) {
+ int value = 0;
+
+ if (STRIKE.equals(status)) {
+ strike++;
+ value = checkThreeStrike();
+ } else if (BALL.equals(status)) {
+ ball++;
+ value = checkFourBall();
+ } else if (OUT.equals(status)) {
+ out++;
+ resetStrikeAndBall();
+ value = checkThreeOut();
+ } else if (HIT.equals(status)) {
+ hit++;
+ resetStrikeAndBall();
+ value = checkFourHit();
+ }
+ return value;
+ }
+
+ private void resetStrikeAndBall() {
+ this.strike = 0;
+ this.ball = 0;
+ }
+
+ private void resetAll() {
+ resetStrikeAndBall();
+ this.out = 0;
+ this.hit = 0;
+ }
+
+ private int checkFourHit() {
+ if (this.hit == 4) {
+ resetStrikeAndBall();
+ this.hit--;
+ return 1;
+ }
+ return 0;
+ }
+
+ private int checkThreeOut() {
+ if (this.out == 3) {
+ resetAll();
+ return -1;
+ }
+ return 0;
+ }
+
+ private int checkFourBall() {
+ if (this.ball == 4) {
+ resetStrikeAndBall();
+ plus(HIT);
+ }
+ return 2;
+ }
+
+ private int checkThreeStrike() {
+ if (this.strike == 3) {
+ resetStrikeAndBall();
+ plus(OUT);
+ }
+ return 2;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public Long getGameId() {
+ return gameId;
+ }
+
+ public int getInning() {
+ return inning;
+ }
+
+ public int getStrike() {
+ return strike;
+ }
+
+ public int getBall() {
+ return ball;
+ }
+
+ public int getOut() {
+ return out;
+ }
+
+ public int getHit() {
+ return hit;
+ }
+
+ public static final class Builder {
+
+ private Long id;
+ private Long gameId;
+ private int inning;
+ private int strike;
+ private int ball;
+ private int out;
+ private int hit;
+
+ public Builder() {
+ }
+
+ public Builder id(Long id) {
+ this.id = id;
+ return this;
+ }
+
+ public Builder gameId(Long gameId) {
+ this.gameId = gameId;
+ return this;
+ }
+
+ public Builder inning(int inning) {
+ this.inning = inning;
+ return this;
+ }
+
+ public Builder strike(int strike) {
+ this.strike = strike;
+ return this;
+ }
+
+ public Builder ball(int ball) {
+ this.ball = ball;
+ return this;
+ }
+
+ public Builder out(int out) {
+ this.out = out;
+ return this;
+ }
+
+ public Builder hit(int hit) {
+ this.hit = hit;
+ return this;
+ }
+
+ public InningStatus build() {
+ return new InningStatus(id, gameId, inning, strike, ball, out, hit);
+ }
+ }
+} | Java | @wheejuni ๋ฆ๊ฒ ๋ตํด๋๋ ค ์ฃ์กํฉ๋๋ค..
ํ์ฌ `InningStatus` ๊ฐ์ฒด๋ inning, strike, ball, out, hit๋ฅผ primitive ํ ๊ฐ์ผ๋ก ๋ณด๊ดํ๊ณ ์์ต๋๋ค.
๋ง์ํ์ ๋ฐฉ๋ฒ์ ball, out์ ๊ด๋ฆฌํ๋ `BallCount`๋ผ๋ ๊ฐ์ฒด๋ฅผ ๋ง๋ค์ด์ ํด๋น ํ์์ ๋ํด ์ด ๊ฐ์ฒด์์ ์ฒ๋ฆฌํ๋๋ก ๋ง๋๋ ๋ฐฉ๋ฒ์ด๋ผ ์ดํด๋ฉ๋๋ค.
๊ทธ๋ฆฌ๊ณ ๋๋จธ์ง ์ผ์ ์ฒ๋ฆฌํ๋ ๋ถ๋ถ์, `4ball`์ผ ๊ฒฝ์ฐ, `1 out`์ด ์ฌ๋ผ๊ฐ๋๋ก ํน์ `3 out` ์ ๊ณต์๊ต๋๋ฅผ ํ ์ ์๋๋ก ์๋ ค์ฃผ๋ ์ญํ ์ด๋ผ ์๊ฐ๋ฉ๋๋ค. ์ ๊ฐ ์ ๋๋ก ์ดํดํ ๊ฒ์ด ๋ง์๊น์? |
@@ -0,0 +1,196 @@
+package com.codesquad.baseball09.model;
+
+import static com.codesquad.baseball09.model.Status.BALL;
+import static com.codesquad.baseball09.model.Status.HIT;
+import static com.codesquad.baseball09.model.Status.OUT;
+import static com.codesquad.baseball09.model.Status.STRIKE;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+
+public class InningStatus {
+
+ @JsonIgnore
+ private Long id;
+ private Long gameId;
+ private int inning;
+ private int strike;
+ private int ball;
+ private int out;
+ private int hit;
+
+ public InningStatus(Long id, Long gameId, int inning, int strike, int ball, int out, int hit) {
+ this.id = id;
+ this.gameId = gameId;
+ this.inning = inning;
+ this.strike = strike;
+ this.ball = ball;
+ this.out = out;
+ this.hit = hit;
+ }
+
+ private InningStatus(Long gameId, int inning, int strike, int ball, int out, int hit) {
+ this.gameId = gameId;
+ this.inning = inning;
+ this.strike = strike;
+ this.ball = ball;
+ this.out = out;
+ this.hit = hit;
+ }
+
+ public InningStatus(int strike, int ball, int out, int hit) {
+ this.strike = strike;
+ this.ball = ball;
+ this.out = out;
+ this.hit = hit;
+ }
+
+ public static InningStatus of(Long gameId, int inning, int strike, int ball, int out, int hit) {
+ return new InningStatus(gameId, inning, strike, ball, out, hit);
+ }
+
+ public int plus(Status status) {
+ int value = 0;
+
+ if (STRIKE.equals(status)) {
+ strike++;
+ value = checkThreeStrike();
+ } else if (BALL.equals(status)) {
+ ball++;
+ value = checkFourBall();
+ } else if (OUT.equals(status)) {
+ out++;
+ resetStrikeAndBall();
+ value = checkThreeOut();
+ } else if (HIT.equals(status)) {
+ hit++;
+ resetStrikeAndBall();
+ value = checkFourHit();
+ }
+ return value;
+ }
+
+ private void resetStrikeAndBall() {
+ this.strike = 0;
+ this.ball = 0;
+ }
+
+ private void resetAll() {
+ resetStrikeAndBall();
+ this.out = 0;
+ this.hit = 0;
+ }
+
+ private int checkFourHit() {
+ if (this.hit == 4) {
+ resetStrikeAndBall();
+ this.hit--;
+ return 1;
+ }
+ return 0;
+ }
+
+ private int checkThreeOut() {
+ if (this.out == 3) {
+ resetAll();
+ return -1;
+ }
+ return 0;
+ }
+
+ private int checkFourBall() {
+ if (this.ball == 4) {
+ resetStrikeAndBall();
+ plus(HIT);
+ }
+ return 2;
+ }
+
+ private int checkThreeStrike() {
+ if (this.strike == 3) {
+ resetStrikeAndBall();
+ plus(OUT);
+ }
+ return 2;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public Long getGameId() {
+ return gameId;
+ }
+
+ public int getInning() {
+ return inning;
+ }
+
+ public int getStrike() {
+ return strike;
+ }
+
+ public int getBall() {
+ return ball;
+ }
+
+ public int getOut() {
+ return out;
+ }
+
+ public int getHit() {
+ return hit;
+ }
+
+ public static final class Builder {
+
+ private Long id;
+ private Long gameId;
+ private int inning;
+ private int strike;
+ private int ball;
+ private int out;
+ private int hit;
+
+ public Builder() {
+ }
+
+ public Builder id(Long id) {
+ this.id = id;
+ return this;
+ }
+
+ public Builder gameId(Long gameId) {
+ this.gameId = gameId;
+ return this;
+ }
+
+ public Builder inning(int inning) {
+ this.inning = inning;
+ return this;
+ }
+
+ public Builder strike(int strike) {
+ this.strike = strike;
+ return this;
+ }
+
+ public Builder ball(int ball) {
+ this.ball = ball;
+ return this;
+ }
+
+ public Builder out(int out) {
+ this.out = out;
+ return this;
+ }
+
+ public Builder hit(int hit) {
+ this.hit = hit;
+ return this;
+ }
+
+ public InningStatus build() {
+ return new InningStatus(id, gameId, inning, strike, ball, out, hit);
+ }
+ }
+} | Java | strike, ball, out, hit ๊ฐ๊ฐ ์ญํ ์ด ์๋ ๋งํผ , ๋ชจ๋ ๊ฐ์ฒด๋ก ๋ง๋๋ ๊ฒ์ด ์ข ๋ ๊น๋ํ ๋ฐฉ๋ฒ์ผ๊น์?
์ด๋ ๊ฒ ์ด๋ค ๋ณํ์ ๋ฐ๋ผ ์ํฅ ๋ฐ๋ ๊ฒ๋ค์ด ๋ง์ ๋, ์ด๋ป๊ฒ ๊ทธ๋ฌํ ์ํธ์์ฉ์ ๊ตฌํํ ์ ์์์ง, ๋๊ฐํฉ๋๋คใ
ใ
|
@@ -0,0 +1,27 @@
+package racingcar.dao;
+
+import java.util.HashMap;
+import java.util.Map;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
+import racingcar.dao.entity.GameEntity;
+
+public class InsertGameDao {
+
+ private final SimpleJdbcInsert insertActor;
+
+ public InsertGameDao(final JdbcTemplate jdbcTemplate) {
+ insertActor = new SimpleJdbcInsert(jdbcTemplate)
+ .withTableName("game")
+ .usingGeneratedKeyColumns("game_id");
+ }
+
+ public GameEntity insert(final GameEntity gameEntity) {
+ final Map<String, Object> parameters = new HashMap<>(3);
+ parameters.put("game_id", gameEntity.getGameId().getValue());
+ parameters.put("trial_count", gameEntity.getTrialCount());
+ parameters.put("created_at", gameEntity.getCreatedAt());
+
+ return new GameEntity(insertActor.executeAndReturnKey(parameters).intValue(), gameEntity.getTrialCount());
+ }
+} | Java | ์ด๊ฑฐ ์ธ ์ ๋ ? |
@@ -0,0 +1,97 @@
+package christmas.config;
+
+import christmas.controller.EventController;
+import christmas.exception.RetryHandler;
+import christmas.service.EventService;
+import christmas.service.MenuService;
+import christmas.validator.InputValidator;
+import christmas.view.input.ConsoleReader;
+import christmas.view.input.InputView;
+import christmas.view.input.Reader;
+import christmas.view.output.ConsoleWriter;
+import christmas.view.output.OutputView;
+import christmas.view.output.Writer;
+
+public class AppConfig {
+ private static AppConfig appConfig;
+ private EventController eventController;
+ private EventService eventService;
+ private MenuService menuService;
+ private InputValidator inputValidator;
+ private RetryHandler retryHandler;
+ private InputView inputView;
+ private OutputView outputView;
+ private Reader reader;
+ private Writer writer;
+
+ public static AppConfig getInstance() {
+ if (appConfig == null) {
+ appConfig = new AppConfig();
+ }
+ return appConfig;
+ }
+
+ public EventController eventController() {
+ if (eventController == null) {
+ eventController = new EventController(discountService(), menuService(),
+ inputView(), outputView(), exceptionHandler());
+ }
+ return eventController;
+ }
+
+ public EventService discountService() {
+ if (eventService == null) {
+ eventService = new EventService();
+ }
+ return eventService;
+ }
+
+ public MenuService menuService() {
+ if (menuService == null) {
+ menuService = new MenuService();
+ }
+ return menuService;
+ }
+
+ public RetryHandler exceptionHandler() {
+ if (retryHandler == null) {
+ retryHandler = new RetryHandler(outputView());
+ }
+ return retryHandler;
+ }
+
+ public InputView inputView() {
+ if (inputView == null) {
+ inputView = new InputView(reader(), inputValidator());
+ }
+ return inputView;
+ }
+
+ public InputValidator inputValidator() {
+ if (inputValidator == null) {
+ inputValidator = new InputValidator();
+ }
+ return inputValidator;
+ }
+
+ public Reader reader() {
+ if (reader == null) {
+ reader = new ConsoleReader();
+ }
+ return reader;
+ }
+
+ public OutputView outputView() {
+ if (outputView == null) {
+ outputView = new OutputView(writer());
+ }
+ return outputView;
+ }
+
+ public Writer writer() {
+ if (writer == null) {
+ writer = new ConsoleWriter();
+ }
+ return writer;
+ }
+} | Java | ์ ์ฒด์ ์ผ๋ก null ์ฒดํฌ๋ฅผ ํด์ฃผ์ ์ด์ ๊ฐ ๊ถ๊ธํฉ๋๋ค! |
@@ -0,0 +1,30 @@
+package christmas.constants.event;
+
+public enum BadgeType {
+ NONE("์์", 0),
+ STAR("๋ณ", 5_000),
+ TREE("ํธ๋ฆฌ", 10_000),
+ SANTA("์ฐํ", 20_000);
+
+ private final String name;
+ private final int threshold;
+
+ BadgeType(String name, int threshold) {
+ this.name = name;
+ this.threshold = threshold;
+ }
+
+ public static BadgeType from(int benefitPrice) {
+ BadgeType result = NONE;
+ for (BadgeType badgeType : values()) {
+ if (benefitPrice >= badgeType.threshold) {
+ result = badgeType;
+ }
+ }
+ return result;
+ }
+
+ public String getName() {
+ return name;
+ }
+} | Java | ๋ฐฐ์ง ์์์ NONE์ผ๋ก ๊ด๋ฆฌํ์ ๋ถ๋ถ๋ ์ข์ ์ ๋ต์ด๋ผ๊ณ ์๊ฐํฉ๋๋ค :)
Optional์ ๊ณ ๋ คํด๋ณด์๋ ๊ฒ๋ ์ข์ ๊ฒ ๊ฐ์์! ์ด๋ฒ์ Optional์ ์ฒ์ ํ์ฉํด๋ดค๋๋ฐ์, **์์ ์๋ ์๋ค ๋ผ๋ ๋น์ฆ๋์ค ์๊ตฌ์ฌํญ**์ **์ฝ๋๋ก ๋ช
์**ํ ์ ์๋ ์ ์ด ์ ๋ง ํฐ ์ฅ์ ์ธ ๊ฒ ๊ฐ์ต๋๋ค :)
๋ง์ฝ Optional์ ๋์
ํ๋ค๋ฉด `from` ๋ฉ์๋๋ฅผ ์ด๋ ๊ฒ ๋ฆฌํฉํฐ๋งํด๋ณผ ์ ์์ ๊ฒ ๊ฐ์์!
```java
public static Optional<BadgeType> from(int benefitPrice) {
Optional<Badge> badge = Arrays.stream(values())
.filter(badge -> badge.minTotalBenefitAmount <= totalBenefitAmount)
.findFirst();
if (badge.isPresent()) {
return badge.get();
}
return badge.empty();
}
}
```
์ ๋ ์์ง Optional์ ์ธ์ ์ฌ์ฉํด์ผ ๋จ์ฉ์ด ์๋๊น? ๋ผ๋ ํ์คํ ๊ธฐ์ค์ ์์ด์, ์ฐธ๊ณ ์ ๋๋ง ํ์๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค :) |
@@ -0,0 +1,54 @@
+package christmas.constants.menu;
+
+import static christmas.constants.menu.MenuType.APPETIZER;
+import static christmas.constants.menu.MenuType.DESSERT;
+import static christmas.constants.menu.MenuType.DRINKS;
+import static christmas.constants.menu.MenuType.MAIN;
+import static christmas.exception.ErrorCode.INVALID_MENU_ORDER;
+
+import java.util.Arrays;
+import java.util.Objects;
+
+public enum Menu {
+ MUSHROOM_SOUP(APPETIZER, "์์ก์ด์ํ", 6000),
+ TAPAS(APPETIZER, "ํํ์ค", 5500),
+ SALAD(APPETIZER, "์์ ์๋ฌ๋", 8000),
+ STAKE(MAIN, "ํฐ๋ณธ์คํ
์ดํฌ", 55_000),
+ LIB(MAIN, "๋ฐ๋นํ๋ฆฝ", 54_000),
+ PASTA_(MAIN, "ํด์ฐ๋ฌผํ์คํ", 35_000),
+ PASTA(MAIN, "ํฌ๋ฆฌ์ค๋ง์คํ์คํ", 25_000),
+ CAKE(DESSERT, "์ด์ฝ์ผ์ดํฌ", 15_000),
+ ICE_CREAM(DESSERT, "์์ด์คํฌ๋ฆผ", 5000),
+ ZERO_COLA(DRINKS, "์ ๋ก์ฝ๋ผ", 3000),
+ WINE(DRINKS, "๋ ๋์์ธ", 60_000),
+ CHAMPAGNE(DRINKS, "์ดํ์ธ", 25_000);
+
+ private final MenuType menuType;
+ private final String name;
+ private final int price;
+
+ Menu(MenuType menuType, String name, int price) {
+ this.menuType = menuType;
+ this.name = name;
+ this.price = price;
+ }
+
+ public static Menu from(String input) {
+ return Arrays.stream(values())
+ .filter(menu -> Objects.equals(menu.name, input))
+ .findFirst()
+ .orElseThrow(() -> new IllegalArgumentException(INVALID_MENU_ORDER.getMessage()));
+ }
+
+ public MenuType getMenuType() {
+ return menuType;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+} | Java | `์ด๋ฆ`์ ๋ํ `๋ฉ๋ด`๋ฅผ HashMap์ผ๋ก ์บ์ฑํด๋๋ ์ ๋ต๋ ์ถ์ฒ๋๋ฆฝ๋๋ค.
Enum์์ static ๋ธ๋ก์ ์ถ๊ฐํ ์ ์๋๋ฐ์, ์๋ฐ์์ผ๋ก ๊ตฌํํ ์ ์์ต๋๋ค!
```java
public enum Menu {
// ์ด๊ฑฐํ ์์๋ค ...
private static final Map<String, Menu> cachedMenu = new HashMap<>();
static {
for (Menu menu : values()) {
cachedMenu.put(menu.getName(), menu);
}
}
}
```
์ด๋ ๊ฒ Map์ผ๋ก ์บ์ฑํด๋๋ฉด, ๋งค ๋ฒ ์ด๊ฑฐํ ์์๋ค์ ์ํํ์ง ์์๋ ๋๋ ์ฅ์ ์ด ์์ต๋๋ค :)
ํ์ง๋ง NPE๊ฐ ๋ฐ์ํ ์ํ์ด ์๊ธฐ ๋๋ฌธ์, Optional์ ์ฌ์ฉํด๋ณด์๋ ๊ฒ๋ ๊ณ ๋ คํด๋ณด์๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค.
๊ทธ๋ ๊ฒ ํ๋ฉด
```java
public static Optional<Menu> from(String menuName) {
return Optional.ofNullalbe(cachedMenu.get(menuName);
}
```
์์ ๊ฐ์ด ๋ฆฌํฉํฐ๋ง ํด๋ณผ ์ ์์ ๊ฒ ๊ฐ์์ :) |
@@ -0,0 +1,98 @@
+package christmas.service;
+
+import static christmas.constants.event.EventRule.MAX_MENU_AMOUNT;
+import static christmas.constants.menu.MenuType.DRINKS;
+import static christmas.exception.ErrorCode.INVALID_MENU_ORDER;
+
+import christmas.constants.menu.Menu;
+import christmas.constants.menu.MenuType;
+import christmas.dto.SingleMenu;
+import java.util.Collections;
+import java.util.EnumMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Stream;
+
+public class MenuService {
+ private final Map<Menu, Integer> menuScript;
+
+ public MenuService() {
+ this.menuScript = new EnumMap<>(Menu.class);
+ }
+
+ public void order(List<SingleMenu> singleMenus) {
+ validate(singleMenus);
+ singleMenus.forEach(singleOrder -> {
+ Menu menu = Menu.from(singleOrder.menu());
+ menuScript.put(menu, singleOrder.amount());
+ });
+ }
+
+ public int getOrderPrice() {
+ return menuScript.keySet()
+ .stream()
+ .mapToInt(menu -> menu.getPrice() * menuScript.get(menu))
+ .sum();
+ }
+
+ private void validate(List<SingleMenu> singleMenus) {
+ validateDuplicate(singleMenus);
+ validatePerMenuAmount(singleMenus);
+ validateOnlyDrink(singleMenus);
+ validateTotalMenuAmount(singleMenus);
+ }
+
+ private void validateDuplicate(List<SingleMenu> singleMenus) {
+ int count = (int) getMenuStream(singleMenus)
+ .distinct()
+ .count();
+
+ if (count != singleMenus.size()) {
+ throw new IllegalArgumentException(INVALID_MENU_ORDER.getMessage());
+ }
+ }
+
+ private void validateOnlyDrink(List<SingleMenu> singleMenus) {
+ int drinks = (int) getMenuStream(singleMenus)
+ .filter(menu -> menu.getMenuType() == DRINKS)
+ .count();
+
+ if (drinks > 0 && drinks == singleMenus.size()) {
+ throw new IllegalArgumentException(INVALID_MENU_ORDER.getMessage());
+ }
+ }
+
+ private Stream<Menu> getMenuStream(List<SingleMenu> singleMenus) {
+ return singleMenus.stream()
+ .map(singleOrder -> Menu.from(singleOrder.menu()));
+ }
+
+ private void validatePerMenuAmount(List<SingleMenu> singleMenus) {
+ boolean present = singleMenus.stream()
+ .anyMatch(singleOrder -> singleOrder.amount() < 1);
+ if (present) {
+ throw new IllegalArgumentException(INVALID_MENU_ORDER.getMessage());
+ }
+ }
+
+ private void validateTotalMenuAmount(List<SingleMenu> singleMenus) {
+ int totalAmount = singleMenus.stream()
+ .mapToInt(SingleMenu::amount)
+ .sum();
+ if (totalAmount >= MAX_MENU_AMOUNT.getValue()) {
+ throw new IllegalArgumentException(INVALID_MENU_ORDER.getMessage());
+ }
+ }
+
+ public int getAmountByMenu(MenuType menuType) {
+ return menuScript.keySet()
+ .stream()
+ .filter(target -> target.getMenuType() == menuType)
+ .mapToInt(menuScript::get)
+ .sum();
+ }
+
+ public Map<Menu, Integer> getMenuScript() {
+ return Collections.unmodifiableMap(menuScript);
+ }
+} | Java | `MenuService` ์์ ์ฃผ๋ฌธ ์ ๋ณด๋ค์ ๋ด๊ณ ์๋๊ฒ ์ธ์๊น์ต๋๋ค!
์ด๊ฒ๋ ์ข์ ์ ๊ทผ ๋ฐฉ์์ธ ๊ฒ ๊ฐ์ง๋ง, `Map<Menu, Integer>`๊ฐ `์ฃผ๋ฌธ ์ ๋ณด` ๋ผ๋ ์ฌ์ค์ ์ถ์ ํ๊ธฐ ์ด๋ ค์ธ ์๋ ์์ ๊ฒ ๊ฐ์์!
`Order` Domain ํด๋์ค๋ฅผ ์์ฑํ๊ณ , validate ๊ฒ์ฆ ์ญํ ๋ ์์ํด์ฃผ๋ฉด MenuService ํด๋์ค๊ฐ ํ์ธต ์์์ง ์ ์์ ๊ฒ ๊ฐ์ต๋๋ค.
์ฌ๊ธฐ์ Service Layer์ ํด๋์ค๊ฐ ์์์ง๋ค๋ ๊ฒ์ **Domain ๊ฐ์ฒด์๊ฒ ์์ฒญํ์ฌ ๊ฒฐ๊ณผ ๊ฐ์ ๋ฐํํ๋ ์ญํ **, **๋น์ฆ๋์ค ๋ก์ง ํ๋ฆ์ ๋ด๋นํ๋ ์ญํ **๋ก ์ถ์ ๋๋ค๋ ์๋ฏธ๋ผ๊ณ ์๊ฐํด์. ์ด๋์ ์ฅ์ ์ **MenuService ๋น์ฆ๋์ค ๋ก์ง์ด ์ด๋ค ํ๋ฆ์ผ๋ก ์งํ๋๋๊ตฌ๋** ์ถ์ ํ๊ธฐ ํธํด์ง๋ ์ ๊ฐ์ต๋๋ค :) |
@@ -0,0 +1,32 @@
+package christmas.util;
+
+import static christmas.exception.ErrorCode.INVALID_DATE;
+import static christmas.exception.ErrorCode.INVALID_MENU_ORDER;
+
+import java.util.List;
+
+public class Parser {
+ public static int parseToDate(String input) {
+ try {
+ return Integer.parseInt(input);
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException(INVALID_DATE.getMessage());
+ }
+ }
+
+ public static int parseToAmount(String input) {
+ try {
+ return Integer.parseInt(input);
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException(INVALID_MENU_ORDER.getMessage());
+ }
+ }
+
+ public static List<String> parseToMenu(String input, String delimiter) {
+ try {
+ return List.of(input.split(delimiter));
+ } catch (IndexOutOfBoundsException e) {
+ throw new IllegalArgumentException(INVALID_MENU_ORDER.getMessage());
+ }
+ }
+} | Java | catch ํ ์ด๋ ํ Exception์ ๋ค๋ฅธ Exception์ผ๋ก ๋ํํ์ฌ ๋ค์ ๋์ ธ์ค ๋, catch ํ๋ Exception๋ ๋ฃ์ด์ ๋๊ฒจ์ฃผ๋ ๊ฒ์ ์ถ์ฒ๋๋ฆฝ๋๋ค.
```java
public static int parseToDate(String input) {
try {
return Integer.parseInt(input);
} catch (NumberFormatException e) {
throw new IllegalArgumentException(INVALID_DATE.getMessage(), e);
}
}
```
๊ทธ๋ ์ง ์์ผ๋ฉด ๊ธฐ์กด์ catch ํ๋ ์์ธ๊ฐ ๋ ์๊ฐ๋ฒ๋ฆฌ๋ ์ํฉ์ด ๋์ด, ์ธ๋ถ ์์ธ๋ฅผ ์คํ ํธ๋ ์ด์ค ํ ์ ์๊ฒ๋ฉ๋๋น! |
@@ -0,0 +1,25 @@
+package christmas.constants.event;
+
+public enum EventRule {
+ EVENT_THRESHOLD(10_000),
+ PRESENT_THRESHOLD(120_000),
+ EVENT_START(1),
+ EVENT_END(31),
+ MAX_MENU_AMOUNT(20),
+ CHRISTMAS_EVENT_END(25),
+ CHRISTMAS_INIT_PRICE(1_000),
+ CHRISTMAS_EXTRA_DISCOUNT(100),
+ MENU_DISCOUNT(2_023),
+ SPECIAL_DISCOUNT(1_000);
+
+
+ private final int value;
+
+ EventRule(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+} | Java | ์ด๋ฒคํธ ๋ฃฐ์ ํ ๊ณณ์ ๋ชจ์๋์ผ๋ ์ฝ๋๊ฐ ์ฝ๊ฒ ์ฝํ์ง ์๋๊ฑฐ ๊ฐ์์! ์ด๋ฒคํธ ์ข
๋ฅ์ ๋ฐ๋ผ ๋ถ๋ฆฌํ๊ฑฐ๋, EventType์ ๋ฉค๋ฒ๋ณ์๋ก ๋ฃฐ์ ์ ์ํ์๋ ๊ฒ์ ์ด๋ค๊ฐ์? |
@@ -0,0 +1,38 @@
+package christmas.exception;
+
+import christmas.view.output.OutputView;
+import java.util.Arrays;
+import java.util.function.Supplier;
+
+public class RetryHandler implements ExceptionHandler {
+ private final OutputView outputView;
+
+ public RetryHandler(OutputView outputView) {
+ this.outputView = outputView;
+ }
+
+ @Override
+ @SafeVarargs
+ public final <T> T execute(Supplier<T> action, Class<? extends Exception>... exceptions) {
+ while (true) {
+ try {
+ return action.get();
+ } catch (IllegalArgumentException e) {
+ printException(e, exceptions);
+ }
+ }
+ }
+
+ private void printException(Exception actual, Class<? extends Exception>... exceptions) {
+ if (isExpectedException(actual, exceptions)) {
+ outputView.printError(actual.getMessage());
+ return;
+ }
+ throw new RuntimeException(actual);
+ }
+
+ private boolean isExpectedException(Exception actual, Class<? extends Exception>... exceptions) {
+ return Arrays.stream(exceptions)
+ .anyMatch(exception -> exception.isInstance(actual));
+ }
+} | Java | ์ค์ exception๊ณผ ์ธ์๋ก ๋ฐ์ exception์ ๋น๊ตํ๋ ๋ก์ง์ด ํ์ํ ์ด์ ๊ฐ ๊ถ๊ธํด์! |
@@ -0,0 +1,19 @@
+package christmas.constants.event;
+
+public enum EventType {
+ CHRISTMAS("ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ"),
+ WEEKDAY("ํ์ผ ํ ์ธ"),
+ WEEKEND("์ฃผ๋ง ํ ์ธ"),
+ SPECIAL("ํน๋ณ ํ ์ธ"),
+ PRESENT("์ฆ์ ์ด๋ฒคํธ");
+
+ private final String description;
+
+ EventType(String description) {
+ this.description = description;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+} | Java | `Eventable` ์ธํฐํ์ด์ค์ `๊ฐ๊ฐ์ ์ด๋ฒคํธ ๊ตฌํ์ฒด ํด๋์ค`์์ ํ ์ธ / ์ฆ์ ์ํ ๊ณ์ฐ ์ฒ๋ฆฌํ์ ๋ฐฉ๋ฒ๋ ๊ต์ฅํ ์ง๊ด์ ์ผ๋ก ์ฝํ๊ณ ์ ๋ง ์ข์ ๊ฒ ๊ฐ์ต๋๋ค! ๐
์ ๋ `ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด/ ํ์ผ/ ์ฃผ๋ง /ํน๋ณ ํ ์ธ ์ด๋ฒคํธ ์ ํ`๊ณผ `ํ ์ธ ์ด๋ฒคํธ ์ ํ์ ํด๋นํ๋ ๊ณ์ฐ ์ฒ๋ฆฌ`๋ **์๋ก ๋ฐ์ ํ ์ฐ๊ด์ด ์๋ ์์**๋ผ๋ ์๊ฐ์ด ๋ค์์ต๋๋ค! ๊ทธ๋์ `EventType Enum`์์ ํ ์ธ ๊ณ์ฐ ์ฒ๋ฆฌ๋ ํจ๊ป ๊ด๋ฆฌํ๋๋ก ํ์ต๋๋ค.
์ด๋ ๊ฒ ์ฒ๋ฆฌ๋ฅผ ํ๋ **ํ ์ธ ์ด๋ฒคํธ ์ ํ์ด๋ผ๋ ์ํ**์ **์ด๋ฒคํธ ์ ํ์ ๋ํ ๊ณ์ฐ์ฒ๋ฆฌ๋ผ๋ ํ์**๊ฐ ํ ๊ณณ์ ๋ฐ์ง๋์ด ์์ด ์ ์ง๋ณด์ํ๊ธฐ ํธํ ๊ฒ ๊ฐ๋ค๋ ์๊ฐ์ด ๋ค์์ต๋๋ค! ์ด ๋ถ๋ถ์ ๋ํด์ HEY๋ ์๊ฒฌ์ด ๊ถ๊ธํฉ๋๋ค ๐ |
@@ -0,0 +1,7 @@
+package christmas.model;
+
+public interface Eventable<T> {
+ boolean canJoinEvent(T condition);
+
+ int getDiscountPrice();
+} | Java | Eventable์ด๋ผ๋ ๊ฐ์ฒด๋ช
์ด ์กฐ๊ธ ํท๊ฐ๋ฆฌ๋๊ฑฐ ๊ฐ์์. ํ์ฌ Eventable์ ์ด๋ฒคํธ ์ฌ๋ถ๋ฅผ ํ๋จํ๋ ๋ฉ์๋์ ํ ์ธ ๊ธ์ก์ ๊ณ์ฐํ๋ ๋ฉ์๋๊ฐ ์กด์ฌํด์. ํ์ง๋ง Eventable ๋ค์ด๋ฐ์ ํ ์ธ ์ฌ๋ถ๋ง ํ๋จํ๋ ์ญํ ์ด๋ผ๊ณ ์คํดํ ์ ์์๊ฑฐ ๊ฐ์ต๋๋ค ๐ฅ |
@@ -0,0 +1,33 @@
+package christmas.model;
+
+import static christmas.constants.event.EventRule.PRESENT_THRESHOLD;
+import static christmas.constants.menu.Menu.CHAMPAGNE;
+
+public class PresentEvent implements Eventable<Integer> {
+ private final int amount;
+
+ private PresentEvent(int orderPrice) {
+ if (canJoinEvent(orderPrice)) {
+ this.amount = 1;
+ return;
+ }
+ this.amount = 0;
+ }
+
+ public static PresentEvent create(int orderPrice) {
+ return new PresentEvent(orderPrice);
+ }
+
+ @Override
+ public boolean canJoinEvent(Integer orderPrice) {
+ if (orderPrice < PRESENT_THRESHOLD.getValue()) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public int getDiscountPrice() {
+ return CHAMPAGNE.getPrice() * amount;
+ }
+} | Java | 1 ์ด๋ผ๋ ์ซ์๋ฅผ ์์๋ก ์ ์ธํ๋ ๊ฒ์ ์ด๋ค๊ฐ์? ์๊ตฌ์ฌํญ์ ์ดํดํ์ง ๋ชปํ ์ฌ๋์ด ์ฝ๋๋ฅผ ๋ณด๋ ๊ฒฝ์ฐ 1์ด๋ผ๋ ์ซ์์ ์๋ฏธ๋ฅผ ํ์
ํ๊ธฐ ์ด๋ ค์ธ๊ฑฐ ๊ฐ์์ :) |
@@ -0,0 +1,80 @@
+package christmas.service;
+
+import static christmas.constants.event.EventRule.EVENT_THRESHOLD;
+import static christmas.constants.event.EventType.CHRISTMAS;
+import static christmas.constants.event.EventType.PRESENT;
+import static christmas.constants.event.EventType.SPECIAL;
+import static christmas.constants.event.EventType.WEEKDAY;
+import static christmas.constants.event.EventType.WEEKEND;
+
+import christmas.constants.event.EventType;
+import christmas.dto.EventDetail;
+import christmas.dto.UserOrder;
+import christmas.model.ChristmasEvent;
+import christmas.model.Eventable;
+import christmas.model.PresentEvent;
+import christmas.model.SpecialEvent;
+import christmas.model.WeekdayEvent;
+import christmas.model.WeekendEvent;
+import java.util.EnumMap;
+import java.util.List;
+import java.util.Map;
+
+public class EventService {
+ private final Map<EventType, Eventable> eventResult;
+ private final int INVALID_VALUE = 0;
+
+ public EventService() {
+ eventResult = new EnumMap<>(EventType.class);
+ }
+
+ public void applyEvent(UserOrder userOrder) {
+ if (!canJoinEvent(userOrder.orderPrice())) {
+ userOrder = new UserOrder(INVALID_VALUE, INVALID_VALUE, INVALID_VALUE, INVALID_VALUE);
+ }
+
+ eventResult.put(PRESENT, PresentEvent.create(userOrder.orderPrice()));
+ eventResult.put(CHRISTMAS, ChristmasEvent.create(userOrder.date()));
+ eventResult.put(WEEKDAY, WeekdayEvent.create(userOrder));
+ eventResult.put(WEEKEND, WeekendEvent.create(userOrder));
+ eventResult.put(SPECIAL, SpecialEvent.create(userOrder.date()));
+ }
+
+ private boolean canJoinEvent(int orderPrice) {
+ if (orderPrice < EVENT_THRESHOLD.getValue()) {
+ return false;
+ }
+ return true;
+ }
+
+ public int getDiscountPriceByEvent(EventType eventType) {
+ return eventResult.get(eventType).getDiscountPrice();
+ }
+
+ public int getExpectedPrice(UserOrder userOrder) {
+ return userOrder.orderPrice() - getTotalDiscountPrice();
+ }
+
+ public int getTotalDiscountPrice() {
+ return eventResult.entrySet()
+ .stream()
+ .filter(entry -> entry.getKey() != PRESENT)
+ .mapToInt(value -> value.getValue().getDiscountPrice())
+ .sum();
+ }
+
+ public int getTotalBenefitPrice() {
+ return eventResult.values()
+ .stream()
+ .mapToInt(Eventable::getDiscountPrice)
+ .sum();
+ }
+
+ public List<EventDetail> convertToEventDetails() {
+ return eventResult.entrySet()
+ .stream()
+ .filter(entry -> entry.getValue().getDiscountPrice() != 0)
+ .map(entry -> new EventDetail(entry.getKey(), entry.getValue().getDiscountPrice()))
+ .toList();
+ }
+} | Java | EventService๋ ์ถฉ๋ถํ ์ข์ ์ฝ๋๋ผ๊ณ ์๊ฐ๋ฉ๋๋ค!
์ด๋ฒคํธ๋ `ํ ์ธ`์ ๋ํ ์ด๋ฒคํธ, `์ฆ์ ์ํ`์ ๋ํ ์ด๋ฒคํธ๋ก ๋๋๊ธฐ ๋๋ฌธ์ `DiscountEventService`, `GiftEventService`๋ก ๋๋๋ค๋ฉด, ๊ฐ ์๋น์ค ํด๋์ค๊ฐ ์ด๋ค ์ด๋ฒคํธ์ ๋ํด ์ฒ๋ฆฌํ๋์ง ๋ณด๋ค ๋ช
ํํด์ง๊ณ ์ ์ง๋ณด์ํ๊ธฐ๋ ์ข์์ง ๊ฒ ๊ฐ์ต๋๋ค :) |
@@ -0,0 +1,31 @@
+package christmas.model;
+
+import static christmas.constants.event.EventRule.SPECIAL_DISCOUNT;
+
+import christmas.util.DayAnalyzer;
+
+public class SpecialEvent implements Eventable<Integer> {
+ private final int discountPrice;
+
+ private SpecialEvent(Integer date) {
+ if (canJoinEvent(date)) {
+ discountPrice = SPECIAL_DISCOUNT.getValue();
+ return;
+ }
+ discountPrice = 0;
+ }
+
+ public static SpecialEvent create(Integer date) {
+ return new SpecialEvent(date);
+ }
+
+ @Override
+ public boolean canJoinEvent(Integer date) {
+ return DayAnalyzer.isSpecialDay(date);
+ }
+
+ @Override
+ public int getDiscountPrice() {
+ return this.discountPrice;
+ }
+} | Java | ํด๋น ๋ก์ง์ ์ ์ ๋ฉ์๋์ ๋ค์ด๊ฐ๋ ๊ฒ์ด ์ ํฉํ ๊ฑฐ ๊ฐ์๋ฐ ์ด๋ป๊ฒ ์๊ฐํ์๋์? ์์ฑ์๋ ๊ฐ์ฒด๋ฅผ ์์ฑํ๋ ์ฑ
์๋ง ๊ฐ๊ณ , ์ ์ ๋ฉ์๋์์ ์กฐ๊ฑด์ ๋ฐ๋ฅธ discountPrice๊ฐ์ ์์ฑ์๋ก ๋๊ฒจ์ค ์ ์์๊ฑฐ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,80 @@
+package christmas.service;
+
+import static christmas.constants.event.EventRule.EVENT_THRESHOLD;
+import static christmas.constants.event.EventType.CHRISTMAS;
+import static christmas.constants.event.EventType.PRESENT;
+import static christmas.constants.event.EventType.SPECIAL;
+import static christmas.constants.event.EventType.WEEKDAY;
+import static christmas.constants.event.EventType.WEEKEND;
+
+import christmas.constants.event.EventType;
+import christmas.dto.EventDetail;
+import christmas.dto.UserOrder;
+import christmas.model.ChristmasEvent;
+import christmas.model.Eventable;
+import christmas.model.PresentEvent;
+import christmas.model.SpecialEvent;
+import christmas.model.WeekdayEvent;
+import christmas.model.WeekendEvent;
+import java.util.EnumMap;
+import java.util.List;
+import java.util.Map;
+
+public class EventService {
+ private final Map<EventType, Eventable> eventResult;
+ private final int INVALID_VALUE = 0;
+
+ public EventService() {
+ eventResult = new EnumMap<>(EventType.class);
+ }
+
+ public void applyEvent(UserOrder userOrder) {
+ if (!canJoinEvent(userOrder.orderPrice())) {
+ userOrder = new UserOrder(INVALID_VALUE, INVALID_VALUE, INVALID_VALUE, INVALID_VALUE);
+ }
+
+ eventResult.put(PRESENT, PresentEvent.create(userOrder.orderPrice()));
+ eventResult.put(CHRISTMAS, ChristmasEvent.create(userOrder.date()));
+ eventResult.put(WEEKDAY, WeekdayEvent.create(userOrder));
+ eventResult.put(WEEKEND, WeekendEvent.create(userOrder));
+ eventResult.put(SPECIAL, SpecialEvent.create(userOrder.date()));
+ }
+
+ private boolean canJoinEvent(int orderPrice) {
+ if (orderPrice < EVENT_THRESHOLD.getValue()) {
+ return false;
+ }
+ return true;
+ }
+
+ public int getDiscountPriceByEvent(EventType eventType) {
+ return eventResult.get(eventType).getDiscountPrice();
+ }
+
+ public int getExpectedPrice(UserOrder userOrder) {
+ return userOrder.orderPrice() - getTotalDiscountPrice();
+ }
+
+ public int getTotalDiscountPrice() {
+ return eventResult.entrySet()
+ .stream()
+ .filter(entry -> entry.getKey() != PRESENT)
+ .mapToInt(value -> value.getValue().getDiscountPrice())
+ .sum();
+ }
+
+ public int getTotalBenefitPrice() {
+ return eventResult.values()
+ .stream()
+ .mapToInt(Eventable::getDiscountPrice)
+ .sum();
+ }
+
+ public List<EventDetail> convertToEventDetails() {
+ return eventResult.entrySet()
+ .stream()
+ .filter(entry -> entry.getValue().getDiscountPrice() != 0)
+ .map(entry -> new EventDetail(entry.getKey(), entry.getValue().getDiscountPrice()))
+ .toList();
+ }
+} | Java | ํด๋น ๋ก์ง์ EnumMap์ ์ด๊ธฐํํ๋ ๋ก์ง์ธ๊ฑฐ ๊ฐ์์. ๊ทธ๋ผ ์์ฑ์๊ฐ ์๋ init ์ด๋ผ๋ ์ด๋ฆ์ ์ ์ ๋ฉ์๋๋ฅผ ํตํด ๋ด๋ถ ๋ก์ง์ ์ข ๋ ๋ช
ํํ ํ์
ํ ์ ์๋๋ก ํ๋ ๊ฒ์ ์ด๋ค๊ฐ์? |
@@ -0,0 +1,80 @@
+package christmas.service;
+
+import static christmas.constants.event.EventRule.EVENT_THRESHOLD;
+import static christmas.constants.event.EventType.CHRISTMAS;
+import static christmas.constants.event.EventType.PRESENT;
+import static christmas.constants.event.EventType.SPECIAL;
+import static christmas.constants.event.EventType.WEEKDAY;
+import static christmas.constants.event.EventType.WEEKEND;
+
+import christmas.constants.event.EventType;
+import christmas.dto.EventDetail;
+import christmas.dto.UserOrder;
+import christmas.model.ChristmasEvent;
+import christmas.model.Eventable;
+import christmas.model.PresentEvent;
+import christmas.model.SpecialEvent;
+import christmas.model.WeekdayEvent;
+import christmas.model.WeekendEvent;
+import java.util.EnumMap;
+import java.util.List;
+import java.util.Map;
+
+public class EventService {
+ private final Map<EventType, Eventable> eventResult;
+ private final int INVALID_VALUE = 0;
+
+ public EventService() {
+ eventResult = new EnumMap<>(EventType.class);
+ }
+
+ public void applyEvent(UserOrder userOrder) {
+ if (!canJoinEvent(userOrder.orderPrice())) {
+ userOrder = new UserOrder(INVALID_VALUE, INVALID_VALUE, INVALID_VALUE, INVALID_VALUE);
+ }
+
+ eventResult.put(PRESENT, PresentEvent.create(userOrder.orderPrice()));
+ eventResult.put(CHRISTMAS, ChristmasEvent.create(userOrder.date()));
+ eventResult.put(WEEKDAY, WeekdayEvent.create(userOrder));
+ eventResult.put(WEEKEND, WeekendEvent.create(userOrder));
+ eventResult.put(SPECIAL, SpecialEvent.create(userOrder.date()));
+ }
+
+ private boolean canJoinEvent(int orderPrice) {
+ if (orderPrice < EVENT_THRESHOLD.getValue()) {
+ return false;
+ }
+ return true;
+ }
+
+ public int getDiscountPriceByEvent(EventType eventType) {
+ return eventResult.get(eventType).getDiscountPrice();
+ }
+
+ public int getExpectedPrice(UserOrder userOrder) {
+ return userOrder.orderPrice() - getTotalDiscountPrice();
+ }
+
+ public int getTotalDiscountPrice() {
+ return eventResult.entrySet()
+ .stream()
+ .filter(entry -> entry.getKey() != PRESENT)
+ .mapToInt(value -> value.getValue().getDiscountPrice())
+ .sum();
+ }
+
+ public int getTotalBenefitPrice() {
+ return eventResult.values()
+ .stream()
+ .mapToInt(Eventable::getDiscountPrice)
+ .sum();
+ }
+
+ public List<EventDetail> convertToEventDetails() {
+ return eventResult.entrySet()
+ .stream()
+ .filter(entry -> entry.getValue().getDiscountPrice() != 0)
+ .map(entry -> new EventDetail(entry.getKey(), entry.getValue().getDiscountPrice()))
+ .toList();
+ }
+} | Java | ์ด๋ฒคํธ์ ๋ํ ์ ์ฑ
๋ค์ ์ธ๋ถ์์ ์ฃผ์
๋ฐ๋๋ก ํ๋ ๊ฒ์ ์ด๋ค๊ฐ์? ํ์ฌ ์ฝ๋๋ ์์กด ์ญ์ ์์น(DIP)์ ์ค์ํ์ง ์์ ์ฝ๋๋ผ๊ณ ์๊ฐํฉ๋๋ค. ํ ์ธ ์ข
๋ฅ์ ๋ํ ์ ์ฑ
์ด ๋ณํ๋ ๊ฒฝ์ฐ ์ ํ๋ฆฌ์ผ์ด์
์ฝ๋๋ฅผ ์์ ํด์ผํ๋ ๋ฌธ์ ๊ฐ ๋ฐ์ํฉ๋๋ค. ๋ฐ๋ผ์, ์ ํ๋ฆฌ์ผ์ด์
๋ด๋ถ์์๋ ์ถ์ ๊ฐ์ฒด์ ์์กดํ๊ณ , service ์์ฑ์์ EnumMap์ ๋๊ฒจ์ฃผ๋ ๊ฒ์ ์ด๋ค๊ฐ์? |
@@ -0,0 +1,98 @@
+package christmas.service;
+
+import static christmas.constants.event.EventRule.MAX_MENU_AMOUNT;
+import static christmas.constants.menu.MenuType.DRINKS;
+import static christmas.exception.ErrorCode.INVALID_MENU_ORDER;
+
+import christmas.constants.menu.Menu;
+import christmas.constants.menu.MenuType;
+import christmas.dto.SingleMenu;
+import java.util.Collections;
+import java.util.EnumMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Stream;
+
+public class MenuService {
+ private final Map<Menu, Integer> menuScript;
+
+ public MenuService() {
+ this.menuScript = new EnumMap<>(Menu.class);
+ }
+
+ public void order(List<SingleMenu> singleMenus) {
+ validate(singleMenus);
+ singleMenus.forEach(singleOrder -> {
+ Menu menu = Menu.from(singleOrder.menu());
+ menuScript.put(menu, singleOrder.amount());
+ });
+ }
+
+ public int getOrderPrice() {
+ return menuScript.keySet()
+ .stream()
+ .mapToInt(menu -> menu.getPrice() * menuScript.get(menu))
+ .sum();
+ }
+
+ private void validate(List<SingleMenu> singleMenus) {
+ validateDuplicate(singleMenus);
+ validatePerMenuAmount(singleMenus);
+ validateOnlyDrink(singleMenus);
+ validateTotalMenuAmount(singleMenus);
+ }
+
+ private void validateDuplicate(List<SingleMenu> singleMenus) {
+ int count = (int) getMenuStream(singleMenus)
+ .distinct()
+ .count();
+
+ if (count != singleMenus.size()) {
+ throw new IllegalArgumentException(INVALID_MENU_ORDER.getMessage());
+ }
+ }
+
+ private void validateOnlyDrink(List<SingleMenu> singleMenus) {
+ int drinks = (int) getMenuStream(singleMenus)
+ .filter(menu -> menu.getMenuType() == DRINKS)
+ .count();
+
+ if (drinks > 0 && drinks == singleMenus.size()) {
+ throw new IllegalArgumentException(INVALID_MENU_ORDER.getMessage());
+ }
+ }
+
+ private Stream<Menu> getMenuStream(List<SingleMenu> singleMenus) {
+ return singleMenus.stream()
+ .map(singleOrder -> Menu.from(singleOrder.menu()));
+ }
+
+ private void validatePerMenuAmount(List<SingleMenu> singleMenus) {
+ boolean present = singleMenus.stream()
+ .anyMatch(singleOrder -> singleOrder.amount() < 1);
+ if (present) {
+ throw new IllegalArgumentException(INVALID_MENU_ORDER.getMessage());
+ }
+ }
+
+ private void validateTotalMenuAmount(List<SingleMenu> singleMenus) {
+ int totalAmount = singleMenus.stream()
+ .mapToInt(SingleMenu::amount)
+ .sum();
+ if (totalAmount >= MAX_MENU_AMOUNT.getValue()) {
+ throw new IllegalArgumentException(INVALID_MENU_ORDER.getMessage());
+ }
+ }
+
+ public int getAmountByMenu(MenuType menuType) {
+ return menuScript.keySet()
+ .stream()
+ .filter(target -> target.getMenuType() == menuType)
+ .mapToInt(menuScript::get)
+ .sum();
+ }
+
+ public Map<Menu, Integer> getMenuScript() {
+ return Collections.unmodifiableMap(menuScript);
+ }
+} | Java | ์ผ๋ฐ์ ์ผ๋ก validate ๊ฒ์ฆ ํ
์คํธ๋ public ๋ฉ์๋๋ฅผ ํ
์คํธํ์ฌ ์งํํ๋๋ฐ, ๋ชจ๋ private ๋ฉ์๋๊ฐ ๋์ผํ ์์ธ๋ฅผ ๋์ง๊ณ ์๊ธฐ ๋๋ฌธ์ ๋ฉ์์ง ๋ด์ฉ์ ํ์ธํ๋ ๋ฑ ์ธ๋ถ์ ์ธ ๊ฒ์ฆ ์ ์ฐจ๊ฐ ํ์ํ๋ค ์๊ฐํฉ๋๋ค. `IllegalArgumentException`์ด ์ ํํ ์ด๋ ์ง์ ์์ ๋ฐ์ํ๋์ง ์๊ธฐ ์ด๋ ค์ฐ๋๊น์!
ํ์ง๋ง ์ด๋ฒ ๋ฏธ์
์ `์๋ฌ๋ฌธ ๋ด์ฉ์ด 2๊ฐ์ง`๋ก ์ ํด์ ธ ์๊ธฐ ๋๋ฌธ์, ์ด์ ๋ฏธ์
๊ฐ์ด `์๋ฌ๋ฌธ ๋ด์ฉ์ผ๋ก ์ธ๋ถ์ ์ธ ํ
์คํธ`๋ฅผ ํ๊ธฐ๊ฐ ์ด๋ ค์ ์ต๋๋ค. ๊ทธ๋์ ์ ๋ ์ธ๋ถ ๊ฒ์ฆ์ ์ํด **์ปค์คํ
์์ธ**๋ฅผ ๋์
ํ์ฌ ์ด ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ์๋๋ฐ, ์ฐธ๊ณ ํ์๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค :)
์กฐ๊ธ ์ค๋ฒ์์ง๋์ด๋ง ๊ฐ์ ์๊ฐ๋ ๋ค์ด ์ฌ๋ฐ๋ฅธ ์ ๊ทผ ๋ฐฉ์์ธ์ง๋ ์ ๋ชจ๋ฅด๊ฒ ๋ค์ ใ
ใ
.. |
@@ -0,0 +1,45 @@
+package christmas.util;
+
+import static christmas.constants.Day.FRIDAY;
+import static christmas.constants.Day.SATURDAY;
+import static christmas.constants.Day.SUNDAY;
+import static christmas.constants.Day.THURSDAY;
+
+import christmas.constants.Day;
+import java.util.Arrays;
+
+public class DayAnalyzer {
+ private static final int DAY_OF_WEEK = 7;
+ private static final int CHRISTMAS_DAY = 25;
+
+ private static Day getDay(int date) {
+ return Arrays.stream(Day.values())
+ .filter(day -> day.getIndex() == date % DAY_OF_WEEK)
+ .findFirst()
+ .orElseThrow();
+ }
+
+ public static boolean isWeekday(int date) {
+ Day targetDay = getDay(date);
+ if (targetDay.compareTo(THURSDAY) <= 0 && targetDay.compareTo(SUNDAY) >= 0) {
+ return true;
+ }
+ return false;
+ }
+
+ public static boolean isWeekend(int date) {
+ Day targetDay = getDay(date);
+ if (targetDay == FRIDAY || targetDay == SATURDAY) {
+ return true;
+ }
+ return false;
+ }
+
+ public static boolean isSpecialDay(int date) {
+ Day targetDay = getDay(date);
+ if (targetDay == SUNDAY || date == CHRISTMAS_DAY) {
+ return true;
+ }
+ return false;
+ }
+} | Java | ์ ๋ ๋ ์ง๋ฅผ ํ๋์ฝ๋ฉํด๋ฒ๋ ธ๋๋ฐ,,, DayAnalyzer ํด๋์ค ์ ๋ง ์ง๊ด์ ์ด๊ณ ์ข์ ์ ๊ทผ ๋ฐฉ์์ธ ๊ฒ ๊ฐ์ต๋๋ค ๐๐ |
@@ -0,0 +1,7 @@
+package christmas.exception;
+
+import java.util.function.Supplier;
+
+public interface ExceptionHandler {
+ <T> T execute(Supplier<T> action, Class<? extends Exception>... exceptions);
+} | Java | `Class<? extends Exception>... exceptions`๋ ์ด๋ค ์ญํ ์ ํ๋ผ๋ฏธํฐ์ธ์ง, ์ด๋ป๊ฒ ํ์ฉ๋๋์ง ์ฌ์ญค๋ณด๊ณ ์ถ์ต๋๋ค! |
@@ -0,0 +1,30 @@
+package christmas.constants.event;
+
+public enum BadgeType {
+ NONE("์์", 0),
+ STAR("๋ณ", 5_000),
+ TREE("ํธ๋ฆฌ", 10_000),
+ SANTA("์ฐํ", 20_000);
+
+ private final String name;
+ private final int threshold;
+
+ BadgeType(String name, int threshold) {
+ this.name = name;
+ this.threshold = threshold;
+ }
+
+ public static BadgeType from(int benefitPrice) {
+ BadgeType result = NONE;
+ for (BadgeType badgeType : values()) {
+ if (benefitPrice >= badgeType.threshold) {
+ result = badgeType;
+ }
+ }
+ return result;
+ }
+
+ public String getName() {
+ return name;
+ }
+} | Java | stream์ผ๋ก ์ต์ ํ ํ ์ ์์ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,13 @@
+package christmas.dto;
+
+import christmas.util.Parser;
+import java.util.List;
+
+public record SingleMenu(String menu, int amount) {
+ private static final String DELIMITER = "-";
+
+ public static SingleMenu create(String singleOrder) {
+ List<String> parsed = Parser.parseToMenu(singleOrder, DELIMITER);
+ return new SingleMenu(parsed.get(0), Parser.parseToAmount(parsed.get(1)));
+ }
+} | Java | SingleMenu๋ฅผ record๋ก ํ์ ์ด์ ๊ฐ ๋ฌด์์ธ๊ฐ์? |
@@ -0,0 +1,38 @@
+package christmas.exception;
+
+import christmas.view.output.OutputView;
+import java.util.Arrays;
+import java.util.function.Supplier;
+
+public class RetryHandler implements ExceptionHandler {
+ private final OutputView outputView;
+
+ public RetryHandler(OutputView outputView) {
+ this.outputView = outputView;
+ }
+
+ @Override
+ @SafeVarargs
+ public final <T> T execute(Supplier<T> action, Class<? extends Exception>... exceptions) {
+ while (true) {
+ try {
+ return action.get();
+ } catch (IllegalArgumentException e) {
+ printException(e, exceptions);
+ }
+ }
+ }
+
+ private void printException(Exception actual, Class<? extends Exception>... exceptions) {
+ if (isExpectedException(actual, exceptions)) {
+ outputView.printError(actual.getMessage());
+ return;
+ }
+ throw new RuntimeException(actual);
+ }
+
+ private boolean isExpectedException(Exception actual, Class<? extends Exception>... exceptions) {
+ return Arrays.stream(exceptions)
+ .anyMatch(exception -> exception.isInstance(actual));
+ }
+} | Java | @safevarargs๋ ์ ์ฌ์ฉํ์ ๊ฑด๊ฐ์? |
@@ -0,0 +1,80 @@
+package christmas.service;
+
+import static christmas.constants.event.EventRule.EVENT_THRESHOLD;
+import static christmas.constants.event.EventType.CHRISTMAS;
+import static christmas.constants.event.EventType.PRESENT;
+import static christmas.constants.event.EventType.SPECIAL;
+import static christmas.constants.event.EventType.WEEKDAY;
+import static christmas.constants.event.EventType.WEEKEND;
+
+import christmas.constants.event.EventType;
+import christmas.dto.EventDetail;
+import christmas.dto.UserOrder;
+import christmas.model.ChristmasEvent;
+import christmas.model.Eventable;
+import christmas.model.PresentEvent;
+import christmas.model.SpecialEvent;
+import christmas.model.WeekdayEvent;
+import christmas.model.WeekendEvent;
+import java.util.EnumMap;
+import java.util.List;
+import java.util.Map;
+
+public class EventService {
+ private final Map<EventType, Eventable> eventResult;
+ private final int INVALID_VALUE = 0;
+
+ public EventService() {
+ eventResult = new EnumMap<>(EventType.class);
+ }
+
+ public void applyEvent(UserOrder userOrder) {
+ if (!canJoinEvent(userOrder.orderPrice())) {
+ userOrder = new UserOrder(INVALID_VALUE, INVALID_VALUE, INVALID_VALUE, INVALID_VALUE);
+ }
+
+ eventResult.put(PRESENT, PresentEvent.create(userOrder.orderPrice()));
+ eventResult.put(CHRISTMAS, ChristmasEvent.create(userOrder.date()));
+ eventResult.put(WEEKDAY, WeekdayEvent.create(userOrder));
+ eventResult.put(WEEKEND, WeekendEvent.create(userOrder));
+ eventResult.put(SPECIAL, SpecialEvent.create(userOrder.date()));
+ }
+
+ private boolean canJoinEvent(int orderPrice) {
+ if (orderPrice < EVENT_THRESHOLD.getValue()) {
+ return false;
+ }
+ return true;
+ }
+
+ public int getDiscountPriceByEvent(EventType eventType) {
+ return eventResult.get(eventType).getDiscountPrice();
+ }
+
+ public int getExpectedPrice(UserOrder userOrder) {
+ return userOrder.orderPrice() - getTotalDiscountPrice();
+ }
+
+ public int getTotalDiscountPrice() {
+ return eventResult.entrySet()
+ .stream()
+ .filter(entry -> entry.getKey() != PRESENT)
+ .mapToInt(value -> value.getValue().getDiscountPrice())
+ .sum();
+ }
+
+ public int getTotalBenefitPrice() {
+ return eventResult.values()
+ .stream()
+ .mapToInt(Eventable::getDiscountPrice)
+ .sum();
+ }
+
+ public List<EventDetail> convertToEventDetails() {
+ return eventResult.entrySet()
+ .stream()
+ .filter(entry -> entry.getValue().getDiscountPrice() != 0)
+ .map(entry -> new EventDetail(entry.getKey(), entry.getValue().getDiscountPrice()))
+ .toList();
+ }
+} | Java | ์ด๋ฒคํธ๊ฐ ์ถ๊ฐ๋ ๋๋ง๋ค put์ ํด์ผํ๋ ๋ถํธํจ์ด ์์ ๊ฒ ๊ฐ์ต๋๋ค |
@@ -0,0 +1,98 @@
+package christmas.service;
+
+import static christmas.constants.event.EventRule.MAX_MENU_AMOUNT;
+import static christmas.constants.menu.MenuType.DRINKS;
+import static christmas.exception.ErrorCode.INVALID_MENU_ORDER;
+
+import christmas.constants.menu.Menu;
+import christmas.constants.menu.MenuType;
+import christmas.dto.SingleMenu;
+import java.util.Collections;
+import java.util.EnumMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Stream;
+
+public class MenuService {
+ private final Map<Menu, Integer> menuScript;
+
+ public MenuService() {
+ this.menuScript = new EnumMap<>(Menu.class);
+ }
+
+ public void order(List<SingleMenu> singleMenus) {
+ validate(singleMenus);
+ singleMenus.forEach(singleOrder -> {
+ Menu menu = Menu.from(singleOrder.menu());
+ menuScript.put(menu, singleOrder.amount());
+ });
+ }
+
+ public int getOrderPrice() {
+ return menuScript.keySet()
+ .stream()
+ .mapToInt(menu -> menu.getPrice() * menuScript.get(menu))
+ .sum();
+ }
+
+ private void validate(List<SingleMenu> singleMenus) {
+ validateDuplicate(singleMenus);
+ validatePerMenuAmount(singleMenus);
+ validateOnlyDrink(singleMenus);
+ validateTotalMenuAmount(singleMenus);
+ }
+
+ private void validateDuplicate(List<SingleMenu> singleMenus) {
+ int count = (int) getMenuStream(singleMenus)
+ .distinct()
+ .count();
+
+ if (count != singleMenus.size()) {
+ throw new IllegalArgumentException(INVALID_MENU_ORDER.getMessage());
+ }
+ }
+
+ private void validateOnlyDrink(List<SingleMenu> singleMenus) {
+ int drinks = (int) getMenuStream(singleMenus)
+ .filter(menu -> menu.getMenuType() == DRINKS)
+ .count();
+
+ if (drinks > 0 && drinks == singleMenus.size()) {
+ throw new IllegalArgumentException(INVALID_MENU_ORDER.getMessage());
+ }
+ }
+
+ private Stream<Menu> getMenuStream(List<SingleMenu> singleMenus) {
+ return singleMenus.stream()
+ .map(singleOrder -> Menu.from(singleOrder.menu()));
+ }
+
+ private void validatePerMenuAmount(List<SingleMenu> singleMenus) {
+ boolean present = singleMenus.stream()
+ .anyMatch(singleOrder -> singleOrder.amount() < 1);
+ if (present) {
+ throw new IllegalArgumentException(INVALID_MENU_ORDER.getMessage());
+ }
+ }
+
+ private void validateTotalMenuAmount(List<SingleMenu> singleMenus) {
+ int totalAmount = singleMenus.stream()
+ .mapToInt(SingleMenu::amount)
+ .sum();
+ if (totalAmount >= MAX_MENU_AMOUNT.getValue()) {
+ throw new IllegalArgumentException(INVALID_MENU_ORDER.getMessage());
+ }
+ }
+
+ public int getAmountByMenu(MenuType menuType) {
+ return menuScript.keySet()
+ .stream()
+ .filter(target -> target.getMenuType() == menuType)
+ .mapToInt(menuScript::get)
+ .sum();
+ }
+
+ public Map<Menu, Integer> getMenuScript() {
+ return Collections.unmodifiableMap(menuScript);
+ }
+} | Java | stream์ int๋ก ์บ์คํ
ํ๋ ๊ฒ์ด ์ดํด๊ฐ ๋์ง ์์ต๋๋ค. |
@@ -0,0 +1,167 @@
+## ํ ์ค๋ก ํํํ๋ ํต์ฌ ๊ธฐ๋ฅ!
+
+> ๐๋ ์ง์ ์ฃผ๋ฌธ ๋ด์ญ์ ์กฐ๊ฑด์ ๋ง์ถฐ 12์ ํ ์ธ ์ด๋ฒคํธ๋ฅผ ์ ์ฉํ๊ธฐ
+
+---
+
+### ๊ธฐ๋ฅ ์๊ตฌ ์ฌํญ
+
+1๏ธโฃ 12์ ์ด๋ฒคํธ์ ๊ด๋ จ๋ ์ ๋ณด ์
๋ ฅ๋ฐ๊ธฐ
+
+-[x] ์ธ์ฟ๋ง ์ถ๋ ฅ
+-[x] ์์ ๋ฐฉ๋ฌธ ๋ ์ง ์
๋ ฅ๋ฐ๊ธฐ
+ -[x] โ ๏ธ ์ ํจํ์ง ์์ ๊ฐ์ ๋ฐ์์ ๋ ์์ธ์ฒ๋ฆฌ
+ -[x] ์ซ์๋ฅผ ์
๋ ฅํ์ง ์์์ ๋
+ -[x] 1์ผ์์ 31์ผ ์ฌ์ด์ ์๊ฐ ์๋ ๋: *[ERROR] ์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.*
+ -[x] ์ ํจํ์ง ์์ ๊ฐ์ ์
๋ ฅ๋ฐ์์ ๊ฒฝ์ฐ, ์ ํจํ ๊ฐ์ ์
๋ ฅํ ๋๊น์ง ๋ค์ ์
๋ ฅ๋ฐ๊ธฐ
+-[x] ์ฃผ๋ฌธ ๋ฉ๋ด ์
๋ ฅ๋ฐ๊ธฐ
+ -[x] โ ๏ธ ์ ํจํ์ง ์์ ๊ฐ์ ๋ฐ์์ ๋ ์์ธ์ฒ๋ฆฌ
+ -[x] ๋ฉ๋ดํ์ ์๋ ๋ฉ๋ด๋ฅผ ์
๋ ฅํ๋ ๊ฒฝ์ฐ: *[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.*
+ -[x] ๋ฉ๋ด์ ์ฃผ๋ฌธ ๊ฐ์๊ฐ 1 ์ด์์ ์ซ์๊ฐ ์๋ ๊ฒฝ์ฐ: *[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.*
+ -[x] ์๋ฃ๋ง ์ฃผ๋ฌธํ ๊ฒฝ์ฐ: *[ERROR] ์๋ฃ๋ง ์ฃผ๋ฌธํ ์ ์์ต๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.*
+ -[x] ๋ฉ๋ด ํ์์ด ์์์ ๋ค๋ฅธ ๊ฒฝ์ฐ
+ -[x] `๋ฉ๋ด๋ช
-๊ฐ์`์ ํ์์ผ๋ก ์ด๋ฃจ์ด์ ธ ์์ง ์์ ๊ฒฝ์ฐ
+ -[x] `๋ฉ๋ด๋ช
-๊ฐ์`๊ฐ ,๋ฅผ ํตํด ๊ตฌ๋ถ๋์ง ์๋ ๊ฒฝ์ฐ
+ -[x] ์ค๋ณต ๋ฉ๋ด๋ฅผ ์
๋ ฅํ ๊ฒฝ์ฐ: *[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.*
+ -[x] ์ฃผ๋ฌธํ ๋ฉ๋ด์ ์ด ๊ฐ์๊ฐ 20๊ฐ๋ฅผ ์ด๊ณผํ ๊ฒฝ์ฐ: *[ERROR] ๋ฉ๋ด๋ ์ต๋ 20๊ฐ๊น์ง๋ง ์ฃผ๋ฌธํ ์ ์์ต๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.*
+ -[x] ์ ํจํ์ง ์์ ๊ฐ์ ์
๋ ฅ๋ฐ์์ ๊ฒฝ์ฐ, ์ ํจํ ๊ฐ์ ์
๋ ฅํ ๋๊น์ง ๋ค์ ์
๋ ฅ๋ฐ๊ธฐ
+
+2๏ธโฃ ์ฃผ๋ฌธ ๋ฉ๋ด ์ถ๋ ฅํ๊ธฐ
+
+-[x] ์
๋ ฅ๋ฐ์ ์ฃผ๋ฌธ ๋ฉ๋ด ์ถ๋ ฅ
+ -[x] ์ฃผ๋ฌธ ๋ฉ๋ด์ ์ถ๋ ฅ ์์๋ ์์ ๋กญ๊ฒ : ๐ฅ์ํผํ์ด์ - ๋ฉ์ธ - ๋์ ํธ - ์๋ฃ ์์๋ฉด ๋ ์ข์ ๊ฒ ๊ฐ๋ค
+ -[x] ํฌ๋ฉง: ๋ฉ๋ด "{๋ฉ๋ด ์ด๋ฆ} {x๊ฐ}" ex) ์ ๋ก์ฝ๋ผ 1๊ฐ
+
+3๏ธโฃ ํ ์ธ ์ ์ด์ฃผ๋ฌธ ๊ธ์ก: MenuService
+
+-[x] ํ ์ธ ์ ์ด์ฃผ๋ฌธ ๊ธ์ก ์ถ๋ ฅ
+ -[x] `๋ฉ๋ด์ ๊ฐ๊ฒฉ * ์๋`์ ์ด ํฉ๊ณ
+
+4๏ธโฃ ์ฆ์ ๋ฉ๋ดโจ
+
+-[x] ์ด ์ฃผ๋ฌธ ๊ธ์ก์ ํ์ธํ๊ณ , ๊ธ์ก์ ๋ฐ๋ผ ์ฆ์ ์ฌ๋ถ ๊ฒฐ์
+ -[x] ์ ๋ฌ๋ฐ์ ๋ ์ง๋ฅผ ํตํด ์ฆ์ ์ฌ๋ถ ๊ฒฐ์
+ -[x] `์ด์ฃผ๋ฌธ ๊ธ์ก`์ด `120,000์` ์ด์์ธ ๊ฒฝ์ฐ, ์ฆ์ ๊ฐ์ 1๋ก ์ค์
+ -[x] `์ด์ฃผ๋ฌธ ๊ธ์ก`์ด `120,000์` ๋ฏธ๋ง์ธ ๊ฒฝ์ฐ, ์ฆ์ ๊ฐ์ 0์ผ๋ก ์ค์
+ -[x] ์กฐ๊ฑด์ ๋ฐ๋ผ ์ฆ์ ๊ฒฐ๊ณผ ์ถ๋ ฅ
+ -[x] `์ด์ฃผ๋ฌธ ๊ธ์ก`์ด `120,000์` ์ด์์ธ ๊ฒฝ์ฐ, "์ดํ์ธ n๊ฐ" ์ถ๋ ฅ
+ -[x] `์ด์ฃผ๋ฌธ ๊ธ์ก`์ด `120,000์` ๋ฏธ๋ง์ธ ๊ฒฝ์ฐ, "์์" ์ถ๋ ฅ
+
+5๏ธโฃ ํํ ๋ด์ญโจ : DiscountService -> EventService
+
+-[x] ํํ์ ๋ฐ์ ์ ์๋ ์กฐ๊ฑด์ธ์ง ํ์ธ
+ -[x] `์ด์ฃผ๋ฌธ๊ธ์ก`์ด 10,000์ ์ด์์ธ์ง ํ์ธ
+-[x] ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ
+ -[x] 1์ผ๋ถํฐ 25์ผ ์ฌ์ด์ ๋ ์ง์๋ง ์ด๋ฒคํธ ์ ์ฉ
+ -[x] 1์ผ์ 1000์๋ถํฐ ์์ํ์ฌ, ํ๋ฃจ๊ฐ ์ง๋ ์๋ก 100์์ฉ ์ถ๊ฐ ํ ์ธ
+ -[x] "ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ: -1,200์" ํํ๋ก ์ถ๋ ฅ
+-[x] ํ์ผ ํ ์ธ
+ -[x] ์ผ์์ผ~๋ชฉ์์ผ ์งํ
+ -[x] `๋์ ํธ`๋ฉ๋ด๋ฅผ `1๊ฐ๋น 2023์` ํ ์ธ
+ -[x] "ํ์ผ ํ ์ธ: -4,046์" ํํ๋ก ์ถ๋ ฅ. ๋จ ํ ์ธ์ด ์๋๋ ๊ฒฝ์ฐ, ์ถ๋ ฅ์ ๋ณ๋๋ก ํ์ง ์์
+-[x] ์ฃผ๋ง ํ ์ธ
+ -[x] ๊ธ์์ผ~ํ ์์ผ ์งํ
+ -[x] `๋ฉ์ธ`๋ฉ๋ด๋ฅผ `1๊ฐ๋น 2,023์` ํ ์ธ
+ -[x] "์ฃผ๋ง ํ ์ธ: -1,000์" ํํ๋ก ์ถ๋ ฅ. ๋จ ํ ์ธ์ด ์๋๋ ๊ฒฝ์ฐ, ์ถ๋ ฅ์ ๋ณ๋๋ก ํ์ง ์์
+-[x] ํน๋ณ ํ ์ธ
+ -[x] ์ด๋ฒคํธ ๋ฌ๋ ฅ์ ๋ณ์ด ์๋ ๊ฒฝ์ฐ(๋งค์ฃผ ์ผ์์ผ + 25์ผ)
+ -[x] `์ด ๊ธ์ก`์์ `1000์` ํ ์ธ
+ -[x] "ํน๋ณ ํ ์ธ: -1,000์" ํํ๋ก ์ถ๋ ฅ. ๋จ ํ ์ธ์ด ์๋๋ ๊ฒฝ์ฐ, ์ถ๋ ฅ์ ๋ณ๋๋ก ํ์ง ์์
+-[x] ํํ ๋ด์ญ์ ๋ํด ์ถ๋ ฅ
+ -[x] ํฌ๋งท์ {์ข
๋ฅ} ํ ์ธ: -{ํ ์ธ ๊ฐ๊ฒฉ}์. ์ด ๋, ๊ฐ๊ฒฉ์ 1000์ ๋จ์๋ก ์ผํ(,)๋ฅผ ๋ฃ๋๋ค
+ -[x] ๋ง์ผ, ๋ชจ๋ ํํ์ ๋ฐ์ง ๋ชปํ ๊ฒฝ์ฐ์๋ "์์"์ผ๋ก ํ์ํ๋ค
+
+6๏ธโฃ ์ดํํ ๊ธ์ก : DiscountService -> EventService
+
+-[x] ์ดํํ ๊ธ์ก์ ๋ํด ๊ณ์ฐ ๋ฐ ์ถ๋ ฅ
+ -[x] ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด, ํ์ผ, ํน๋ณ, ์ฆ์ ์ด๋ฒคํธ ํ ์ธ์ ๋ชจ๋ ํฉํ ๊ฐ๊ฒฉ์ ํ์ํ๋ค (์ด ํ ์ธ ๊ธ์ก + ์ฆ์ ๋ฉ๋ด์ ๊ฐ๊ฒฉ)
+ -[x] ์์ -๊ฐ ๋ถ์ผ๋ฉฐ, 1000์ ๋จ์๋ง๋ค ์ผํ(,)๋ฅผ ์ถ๊ฐํ๋ค
+
+7๏ธโฃ ํ ์ธ ํ, ์์ ๊ฒฐ์ ๊ธ์ก
+
+-[x] ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก์ ๋ํด ๊ณ์ฐ ๋ฐ ์ถ๋ ฅ
+ -[x] `ํ ์ธ ์ ์ด์ฃผ๋ฌธ ๊ธ์ก` - `์ดํํ ๊ธ์ก`์ ๊ณ์ฐํ ๊ฒฐ๊ณผ๋ฅผ ์ถ๋ ฅํ๋ค
+ -[x] 1000์ ๋จ์๋ง๋ค ์ผํ(,)๋ฅผ ์ถ๊ฐํ๋ค
+
+8๏ธโฃ 12์ ์ด๋ฒคํธ ๋ฐฐ์ง
+
+-[x] ์ด๋ฒคํธ ๋ฐฐ์ง: `์ด ํํ ๊ธ์ก`์ ๋ฐ๋ผ ๋ฐฐ์ง ๋ถ์ฌ ๋ฐ ์ถ๋ ฅ
+ -[x] ์ด๋ฒคํธ ๋ฐฐ์ง์ ๋ํด ๊ณ์ฐ
+ -[x] 5000 <= x < 10,000 : ๋ณ
+ -[x] 10,000 <= x < 20,000 : ํธ๋ฆฌ
+ -[x] 20,000 <= x : ์ฐํ
+
+---
+
+### ํ๋ก๊ทธ๋๋ฐ ์๊ตฌ ์ฌํญ
+
+-[x] ApplicationTest์ ๋ชจ๋ ํ
์คํธ๊ฐ ์ฑ๊ณตํด์ผ ํ๋ค.
+-[x] indent depth๋ 2๊น์ง ํ์ฉํ๋ค.
+-[x] ๋ฉ์๋์ ๊ธธ์ด๊ฐ 15๋ฅผ ๋์ด๊ฐ์ง ์๋๋ก ํ๋ค.
+-[x] ์ฌ์ฉ์๊ฐ ์๋ชป๋ ๊ฐ์ ์
๋ ฅํ ๊ฒฝ์ฐ, `IllegalArgumentException`์ ๋ฐ์์ํค๊ณ , `[ERROR]`๋ก ์์ํ๋ ์๋ฌ ๋ฉ์์ง๋ฅผ ์ถ๋ ฅํ ํ, ๊ทธ ๋ถ๋ถ๋ถํฐ ์
๋ ฅ์ ๋ค์ ๋ฐ๋๋ค.
+-[x] ์
๋ ฅ๊ณผ ์ถ๋ ฅ์ ๋ด๋นํ๋ ํด๋์ค๋ฅผ ๋ณ๋๋ก ๊ตฌํํ๋ค.
+ -[x] InputView: readDate()...
+ -[x] OutputView : printMenu()...
+-[x] Console.readLine()์ ํ์ฉํ๋ค.
+
+---
+
+### 3์ฃผ์ฐจ ํผ๋๋ฐฑ ๋ด์ฉ
+
+-[x] 3์ฃผ์ฐจ ๊ณตํตํผ๋๋ฐฑ ์งํค๊ธฐ!
+-[x] `Integer.parseInt()`๋ฅผ ์ฌ์ฉํ๋ฉด ์ ์์ ๋ฒ์๊ฐ ์๋ ๋์๋ ์์ธ๊ฐ ๋ฐ์ํ๋๋ฐ, ์์ธ ๋ฉ์์ง๋ฅด ์กฐ๊ธ ๋ ๊ผผ๊ผผํ๊ฒ ์ฑ๊ธฐ์
+-[x] Enum์์ ๋ฌธ์์ด์ ํฉ์น ๋ `+`๋ณด๋ค๋, `String.format()`์ ์ฌ์ฉํ์
+-[x] `System.lineSeperator()`์ `String.format("%n")`์ ๊ฐ์ ์ญํ ์ ํ๋ค. ํ์ฉํด๋ณด์!
+-[x] ์๊ตฌ์ฌํญ์ ๊ผผ๊ผผํ๊ฒ ์ฝ์. (์ธ์๋ฆฌ๋ง๋ค ์ผํ๋ฅผ ๋ฃ์ด์ค๋ค๋์ง...)
+-[x] ์์๋ฅผ enum์ผ๋ก ๋บ์ผ๋ฉด ์ด๋ฅผ ํ์ฉํ์! ๋งค์ง ๋๋ฒ์ ์ฌ์ฉ์ ์ค์ด์! ํ์ฅ์ฑ์ ๊ณ ๋ คํ ๊ตฌ์กฐ๋ฅผ ๋ง๋ค์!
+-[x] ์์ธ๋ฅผ ๋ค์ ๋ฐ๋ ๋ฐฉ๋ฒ์ผ๋ก ์ฌ๊ท๋ฅผ ์ฌ์ฉํ๋๋ฐ, ๋ฉ๋ชจ๋ฆฌ๊ฐ ํฐ์ง ๊ฐ๋ฅ์ฑ์ด ์๋ค. `Supplier`๋ฅผ ๋์
ํด๋ณด์.
+-[x] ๊ฒ์ฆ(Validate)๊ณผ ํ์ฑ(Parsing)์ ๋ก์ง์ ์ด๋์ ๋๋ฉด ์ข์๊น? ๊ณ ๋ฏผํด๋ณด์.
+-[x] ๋๋ฏธํฐ์ ๋ฒ์น!
+-[x] `Console.close()`๋ฅผ ํตํด ์ฌ์ฉ ์๋ฃํ ์ฝ์์ ๋ซ์์ฃผ์
+
+---
+
+### ๊ฐ๋ฐ ์ค ์์ฑํ๋ ๋ฆฌํฉํ ๋ง ๋ชฉ๋ก
+
+-[x] IoC ์ปจํ
์ด๋ ์ ์ฉํ๊ธฐ
+-[x] Enum์ด ๋๋ฌด ์ฐํ์ฃฝ์ ์๊ธด ๊ฒ ๊ฐ๋ค! ์ ๋ฆฌํ ์ ์๋ ๋ถ๋ถ์ ์ ๋ฆฌํด๋ณด์
+-[x] InputView, OutputView์์ `readLine()`๊ณผ `System.out.print` ๋ถ๋ถ ์ถ์ํํ๊ธฐ
+-[x] `Supplier`๋ฅผ ์ด์ฉํ์ฌ ์ฌ์
๋ ฅ ์ฒ๋ฆฌํ๊ธฐ
+-[x] Validator(๊ฒ์ฆ)์ ์ญํ ์ด ์ ์ ํ๊ฒ ๋ถ๋ฐฐ๋์ด ์๋์ง ํ์ธ
+ -[x] MenuService์ validate ํจ์๋ค์ ๋ํด ์ค๋ณต๋์ด์๋ ์ฝ๋ ์ฒ๋ฆฌํ๊ธฐ
+-[x] MenuService์ ์ฝ๋๊ฐ ์กฐ๊ธ ๋์กํ ๊ฒ ๊ฐ์
+-[x] Message์ %n์ ๋ํด ์ด๋ป๊ฒ...์ฒ๋ฆฌ ์ข ํ๊ธฐ
+-[ ] Parser์์ parseToDate, parseToAmount์ ์ฝ๋๊ฐ ๊ฒน์น๋ค. ์ ๋ฌํ๋ ์์ธ ๋ฉ์ธ์ง๋ง ๋ค๋ฅธ๋ฐ... ๋ฐฉ๋ฒ์ ์ฐพ์๋ณด์.
+-[x] DiscountResult์ ๋๋ฌด ๋ง์ ์ฑ
์์ด ์๋ ๊ฒ ๊ฐ๋ค! DiscountService์๊ฒ ์ฑ
์์ ๋ ๋ถ์ฌํ์.
+ -> DiscountResult -> EventResult -> EventService๋ก ๋ณ๊ฒฝ ๋ฐ ์ญํ ๋ถ์ฌ
+-[x] ๋ฉ์๋, ๋ณ์๋ช
์ด ์ ์ ํ์ง ํ์ธ ํ ์์
+-[x] ๋ฉ๋ด๋ฅผ ์๋ชป์
๋ ฅํ์ ๋ `IndexOutOfBounds`๊ฐ ๋ฐ์ํ๋ฉด์ ์ข
๋ฃ๋๋ค.
+-[x] OutputView์์ formatting์ ํ๋ฉด์ ๊ฒน์น๋ ์ฝ๋๊ฐ ๊ณณ๊ณณ์ ์๋ค. ์์ ํ์!
+
+---
+
+### ๊ตฌํํ๋ฉด์ ์ง์คํ๋ ๋ถ๋ถ๋ค! ๊ณ ๋ฏผ๊ฑฐ๋ฆฌ!
+
+#### โ
Discountable(Eventable๋ก ๋ณ๊ฒฝ) ์ธํฐํ์ด์ค์ ์ ๋๋ฆญ์ ์ ์ฉํ์
+
+> ๐ง ๊ณ ๋ฏผ ๋ด์ฉ ๐ง
+> ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด, ์ฆ์ ์ด๋ฒคํธ, ํ์ผ ํ ์ธ, ์ฃผ๋ง ํ ์ธ, ํน๋ณ ํ ์ธ ๋ชจ๋ ๊ฐ์๋ง์ ๊ณ ์ ํ ํ ์ธ ์กฐ๊ฑด๋ค์ด ์๋ค.
+> ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด์ ์ฆ์ ์ด๋ฒคํธ๋ `์ด ์ฃผ๋ฌธ ๊ธ์ก`๊ณผ `๋ ์ง`๋ฅผ ํ์ธํ๋ฉด ๋๋๋ฐ, ์ด๋ค์ ๋ชจ๋ intํ์ผ๋ก ์ฒ๋ฆฌ๊ฐ ๊ฐ๋ฅํ๋ค.
+>
+> ํ์ง๋ง ํ์ผ, ์ฃผ๋ง ํ ์ธ์ `๋ ์ง`๋ง ๋ฐ๋ ๊ฒ์ด ์๋๋ผ, ๋ฉ๋ด์ ๋ํ ์ต์ํ์ ์ ๋ณด๊ฐ ์ถ๊ฐ์ ์ผ๋ก ํ์ํ๋ค.
+> ๋ชจ๋ ํ ์ธ ํด๋์ค๋ค์ด ๊ณตํต์ผ๋ก ๊ฐ์ง๊ณ ์์ด์ผ ํ๋ ๊ฒ๋ค์ `Discountable ์ธํฐํ์ด์ค(Eventable ์ธํฐํ์ด์ค๋ก ๋ณ๊ฒฝ)`๋ก ํํํ๊ณ ์ถ์๋ฐ ์ด๋ป๊ฒ ํ๋ฉด ์ข์๊น?
+
+์ด์ ๋ํด ์๊ฐ๋ ํด๋ต์ ๋ฐ๋ก `์ ๋๋ฆญ`์ ์ฌ์ฉํ๋ ๊ฒ์ด์๋ค.
+`์ ๋๋ฆญ`์ ์ฌ์ฉํ๋ฉด `canDiscount`์ ๋งค๊ฐ๋ณ์์ ์๋ฃํ์ ์๊ด์์ด ์ ๋ฌํ๊ณ ์ถ์ ๋ฐ์ดํฐ๋ฅผ ์ ๋ฌํ ์ ์๊ธฐ ๋๋ฌธ์ด๋ค.
+๋ฐ๋ผ์ `Discountable` ์ธํฐํ์ด์ค์ `canDiscount()`์ ๋งค๊ฐ๋ณ์๋ก ์ ๋ฌ๋๋ ์กฐ๊ฑด(`condition`) `์ ๋๋ฆญ <T>`๋ฅผ ์ ์ฉํ๋ค.
+
+<br>
+
+#### โ
View์์ ์ ์ ํ ๋ณํํด์ ์ ๋ฌํ์. ๊ผญ String์ผ๋ก ์ ๋ฌํ ํ์๊ฐ ์๋ค.
+
+<br>
+
+#### โ
๋ค๋ฅธ ๊ณ์ธต๊ณผ ๋ฐ์ดํฐ๋ฅผ ์ฃผ๊ณ ๋ฐ์ ๋์๋ DTO๋ฅผ ์ด์ฉํ์.
+
+
+ | Unknown | ์ ๋ค๋ฆญ์ ์ฌ์ฉํด Discountable๋ก ํํํ ๊ฒ์ด ๋งค์ฐ ์ธ์๊น๋ค์! ์ฝ๋ ๋ฆฌ๋ทฐํ ๋๋ ๋ณด๋ฉด์ ๊ณต๋ถํ๋๋ก ํ๊ฒ ์ต๋๋ค ๐ซก |
@@ -0,0 +1,97 @@
+package christmas.config;
+
+import christmas.controller.EventController;
+import christmas.exception.RetryHandler;
+import christmas.service.EventService;
+import christmas.service.MenuService;
+import christmas.validator.InputValidator;
+import christmas.view.input.ConsoleReader;
+import christmas.view.input.InputView;
+import christmas.view.input.Reader;
+import christmas.view.output.ConsoleWriter;
+import christmas.view.output.OutputView;
+import christmas.view.output.Writer;
+
+public class AppConfig {
+ private static AppConfig appConfig;
+ private EventController eventController;
+ private EventService eventService;
+ private MenuService menuService;
+ private InputValidator inputValidator;
+ private RetryHandler retryHandler;
+ private InputView inputView;
+ private OutputView outputView;
+ private Reader reader;
+ private Writer writer;
+
+ public static AppConfig getInstance() {
+ if (appConfig == null) {
+ appConfig = new AppConfig();
+ }
+ return appConfig;
+ }
+
+ public EventController eventController() {
+ if (eventController == null) {
+ eventController = new EventController(discountService(), menuService(),
+ inputView(), outputView(), exceptionHandler());
+ }
+ return eventController;
+ }
+
+ public EventService discountService() {
+ if (eventService == null) {
+ eventService = new EventService();
+ }
+ return eventService;
+ }
+
+ public MenuService menuService() {
+ if (menuService == null) {
+ menuService = new MenuService();
+ }
+ return menuService;
+ }
+
+ public RetryHandler exceptionHandler() {
+ if (retryHandler == null) {
+ retryHandler = new RetryHandler(outputView());
+ }
+ return retryHandler;
+ }
+
+ public InputView inputView() {
+ if (inputView == null) {
+ inputView = new InputView(reader(), inputValidator());
+ }
+ return inputView;
+ }
+
+ public InputValidator inputValidator() {
+ if (inputValidator == null) {
+ inputValidator = new InputValidator();
+ }
+ return inputValidator;
+ }
+
+ public Reader reader() {
+ if (reader == null) {
+ reader = new ConsoleReader();
+ }
+ return reader;
+ }
+
+ public OutputView outputView() {
+ if (outputView == null) {
+ outputView = new OutputView(writer());
+ }
+ return outputView;
+ }
+
+ public Writer writer() {
+ if (writer == null) {
+ writer = new ConsoleWriter();
+ }
+ return writer;
+ }
+} | Java | outview์ ๊ฒฝ์ฐ static๋ฉ์๋๋ฅผ ํ์ฉํด ๊ฐ์ฒด๋ฅผ ์์ฑํ์ง ์๋ ๋ฐฉ๋ฒ๋ ์๋๋ฐ, ๊ทธ๋ผ์๋ ์ฑ๊ธํค ํจํด์ ์ ์งํ์ ์ด์ ๊ฐ ์์๊น์? |
@@ -0,0 +1,94 @@
+package christmas.controller;
+
+import static christmas.constants.event.EventType.PRESENT;
+import static christmas.constants.menu.MenuType.DESSERT;
+import static christmas.constants.menu.MenuType.MAIN;
+
+import christmas.constants.event.BadgeType;
+import christmas.dto.SingleMenu;
+import christmas.dto.UserOrder;
+import christmas.exception.RetryHandler;
+import christmas.service.EventService;
+import christmas.service.MenuService;
+import christmas.view.input.InputView;
+import christmas.view.output.OutputView;
+import java.util.List;
+
+public class EventController {
+ private final EventService eventService;
+ private final MenuService menuService;
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final RetryHandler retryHandler;
+
+ public EventController(EventService eventService, MenuService menuService, InputView inputView,
+ OutputView outputView, RetryHandler retryHandler) {
+ this.eventService = eventService;
+ this.menuService = menuService;
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.retryHandler = retryHandler;
+ }
+
+ public void run() {
+ int visitDate = getVisitDate();
+ UserOrder userOrder = receiveOrder(visitDate);
+ printOrderInformation();
+
+ applyEvent(userOrder);
+ printEventDetails(userOrder);
+
+ printBadge();
+ inputView.close();
+ }
+
+ private int getVisitDate() {
+ outputView.printGreeting();
+ outputView.printAskVisitDate();
+
+ return retryHandler.execute(inputView::askVisitDate, IllegalArgumentException.class);
+ }
+
+ private UserOrder receiveOrder(int visitDate) {
+ outputView.printAskMenu();
+ UserOrder userOrder = retryHandler.execute(() -> getUserOrder(visitDate), IllegalArgumentException.class);
+ outputView.printPreview(visitDate);
+
+ return userOrder;
+ }
+
+ private UserOrder getUserOrder(int visitDate) {
+ List<SingleMenu> singleMenus = inputView.askOrderMenu();
+ menuService.order(singleMenus);
+ return new UserOrder(
+ menuService.getOrderPrice(),
+ visitDate,
+ menuService.getAmountByMenu(MAIN),
+ menuService.getAmountByMenu(DESSERT)
+ );
+ }
+
+ private void printOrderInformation() {
+ outputView.printOrderMenu(menuService.getMenuScript());
+ outputView.printBeforeDiscountPrice(menuService.getOrderPrice());
+ }
+
+ private void applyEvent(UserOrder userOrder) {
+ eventService.applyEvent(userOrder);
+ }
+
+ private void printEventDetails(UserOrder userOrder) {
+ int discountPrice = eventService.getDiscountPriceByEvent(PRESENT);
+ int expectedPrice = eventService.getExpectedPrice(userOrder);
+
+ outputView.printPresent(discountPrice);
+ outputView.printEventDetails(eventService.convertToEventDetails());
+ outputView.printTotalBenefitPrice(eventService.getTotalBenefitPrice());
+ outputView.printExpectedPrice(expectedPrice);
+ }
+
+ private void printBadge() {
+ int totalDiscountPrice = eventService.getTotalBenefitPrice();
+ outputView.printEventBadge(BadgeType.from(totalDiscountPrice));
+ }
+} | Java | print๋ผ๋ ๋ค์ด๋ฐ์ ์ปจํธ๋กค๋ฌ๊ฐ ์ถ๋ ฅ์ ๋ด๋นํ๋ค ๋ผ๋ ๋ป์ผ๋ก ๋ณด์
๋๋ค! ๋ค๋ฅธ ๋ง๋ก ๋์ฒด ํ๋๊ฑด ์ด๋ป๊ฒ ์๊ฐํ์ธ์? |
@@ -0,0 +1,25 @@
+package christmas.constants.event;
+
+public enum EventRule {
+ EVENT_THRESHOLD(10_000),
+ PRESENT_THRESHOLD(120_000),
+ EVENT_START(1),
+ EVENT_END(31),
+ MAX_MENU_AMOUNT(20),
+ CHRISTMAS_EVENT_END(25),
+ CHRISTMAS_INIT_PRICE(1_000),
+ CHRISTMAS_EXTRA_DISCOUNT(100),
+ MENU_DISCOUNT(2_023),
+ SPECIAL_DISCOUNT(1_000);
+
+
+ private final int value;
+
+ EventRule(int value) {
+ this.value = value;
+ }
+
+ public int getValue() {
+ return value;
+ }
+} | Java | ๊ฐ์ธ์ ์ผ๋ก enum์ ์ฐ๊ด๋ ์์๋ฅผ ๋ชจ์๋๋ ๊ณณ์ด๋ผ๊ณ ์๊ฐํฉ๋๋ค!
CHRISTMAS_EXTRA_DISCOUNT(100),
MENU_DISCOUNT(2_023),
๋ฑ์ ์๋ก ๋ค๋ฅธ ๊ฐ์ฒด๋จ์๋ก ๋ถ๋ฆฌ๊ฐ ๊ฐ๋ฅํด๋ณด์ฌ์!
์ฐจ๋ผ๋ฆฌ ๊ฐ์ฒด ๋ด๋ถ์ ์์ ํ๋๋ก ๊ด๋ฆฌํ๋ ๊ฒ์ ์ด๋ ์ธ์? |
@@ -0,0 +1,167 @@
+## ํ ์ค๋ก ํํํ๋ ํต์ฌ ๊ธฐ๋ฅ!
+
+> ๐๋ ์ง์ ์ฃผ๋ฌธ ๋ด์ญ์ ์กฐ๊ฑด์ ๋ง์ถฐ 12์ ํ ์ธ ์ด๋ฒคํธ๋ฅผ ์ ์ฉํ๊ธฐ
+
+---
+
+### ๊ธฐ๋ฅ ์๊ตฌ ์ฌํญ
+
+1๏ธโฃ 12์ ์ด๋ฒคํธ์ ๊ด๋ จ๋ ์ ๋ณด ์
๋ ฅ๋ฐ๊ธฐ
+
+-[x] ์ธ์ฟ๋ง ์ถ๋ ฅ
+-[x] ์์ ๋ฐฉ๋ฌธ ๋ ์ง ์
๋ ฅ๋ฐ๊ธฐ
+ -[x] โ ๏ธ ์ ํจํ์ง ์์ ๊ฐ์ ๋ฐ์์ ๋ ์์ธ์ฒ๋ฆฌ
+ -[x] ์ซ์๋ฅผ ์
๋ ฅํ์ง ์์์ ๋
+ -[x] 1์ผ์์ 31์ผ ์ฌ์ด์ ์๊ฐ ์๋ ๋: *[ERROR] ์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.*
+ -[x] ์ ํจํ์ง ์์ ๊ฐ์ ์
๋ ฅ๋ฐ์์ ๊ฒฝ์ฐ, ์ ํจํ ๊ฐ์ ์
๋ ฅํ ๋๊น์ง ๋ค์ ์
๋ ฅ๋ฐ๊ธฐ
+-[x] ์ฃผ๋ฌธ ๋ฉ๋ด ์
๋ ฅ๋ฐ๊ธฐ
+ -[x] โ ๏ธ ์ ํจํ์ง ์์ ๊ฐ์ ๋ฐ์์ ๋ ์์ธ์ฒ๋ฆฌ
+ -[x] ๋ฉ๋ดํ์ ์๋ ๋ฉ๋ด๋ฅผ ์
๋ ฅํ๋ ๊ฒฝ์ฐ: *[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.*
+ -[x] ๋ฉ๋ด์ ์ฃผ๋ฌธ ๊ฐ์๊ฐ 1 ์ด์์ ์ซ์๊ฐ ์๋ ๊ฒฝ์ฐ: *[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.*
+ -[x] ์๋ฃ๋ง ์ฃผ๋ฌธํ ๊ฒฝ์ฐ: *[ERROR] ์๋ฃ๋ง ์ฃผ๋ฌธํ ์ ์์ต๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.*
+ -[x] ๋ฉ๋ด ํ์์ด ์์์ ๋ค๋ฅธ ๊ฒฝ์ฐ
+ -[x] `๋ฉ๋ด๋ช
-๊ฐ์`์ ํ์์ผ๋ก ์ด๋ฃจ์ด์ ธ ์์ง ์์ ๊ฒฝ์ฐ
+ -[x] `๋ฉ๋ด๋ช
-๊ฐ์`๊ฐ ,๋ฅผ ํตํด ๊ตฌ๋ถ๋์ง ์๋ ๊ฒฝ์ฐ
+ -[x] ์ค๋ณต ๋ฉ๋ด๋ฅผ ์
๋ ฅํ ๊ฒฝ์ฐ: *[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.*
+ -[x] ์ฃผ๋ฌธํ ๋ฉ๋ด์ ์ด ๊ฐ์๊ฐ 20๊ฐ๋ฅผ ์ด๊ณผํ ๊ฒฝ์ฐ: *[ERROR] ๋ฉ๋ด๋ ์ต๋ 20๊ฐ๊น์ง๋ง ์ฃผ๋ฌธํ ์ ์์ต๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.*
+ -[x] ์ ํจํ์ง ์์ ๊ฐ์ ์
๋ ฅ๋ฐ์์ ๊ฒฝ์ฐ, ์ ํจํ ๊ฐ์ ์
๋ ฅํ ๋๊น์ง ๋ค์ ์
๋ ฅ๋ฐ๊ธฐ
+
+2๏ธโฃ ์ฃผ๋ฌธ ๋ฉ๋ด ์ถ๋ ฅํ๊ธฐ
+
+-[x] ์
๋ ฅ๋ฐ์ ์ฃผ๋ฌธ ๋ฉ๋ด ์ถ๋ ฅ
+ -[x] ์ฃผ๋ฌธ ๋ฉ๋ด์ ์ถ๋ ฅ ์์๋ ์์ ๋กญ๊ฒ : ๐ฅ์ํผํ์ด์ - ๋ฉ์ธ - ๋์ ํธ - ์๋ฃ ์์๋ฉด ๋ ์ข์ ๊ฒ ๊ฐ๋ค
+ -[x] ํฌ๋ฉง: ๋ฉ๋ด "{๋ฉ๋ด ์ด๋ฆ} {x๊ฐ}" ex) ์ ๋ก์ฝ๋ผ 1๊ฐ
+
+3๏ธโฃ ํ ์ธ ์ ์ด์ฃผ๋ฌธ ๊ธ์ก: MenuService
+
+-[x] ํ ์ธ ์ ์ด์ฃผ๋ฌธ ๊ธ์ก ์ถ๋ ฅ
+ -[x] `๋ฉ๋ด์ ๊ฐ๊ฒฉ * ์๋`์ ์ด ํฉ๊ณ
+
+4๏ธโฃ ์ฆ์ ๋ฉ๋ดโจ
+
+-[x] ์ด ์ฃผ๋ฌธ ๊ธ์ก์ ํ์ธํ๊ณ , ๊ธ์ก์ ๋ฐ๋ผ ์ฆ์ ์ฌ๋ถ ๊ฒฐ์
+ -[x] ์ ๋ฌ๋ฐ์ ๋ ์ง๋ฅผ ํตํด ์ฆ์ ์ฌ๋ถ ๊ฒฐ์
+ -[x] `์ด์ฃผ๋ฌธ ๊ธ์ก`์ด `120,000์` ์ด์์ธ ๊ฒฝ์ฐ, ์ฆ์ ๊ฐ์ 1๋ก ์ค์
+ -[x] `์ด์ฃผ๋ฌธ ๊ธ์ก`์ด `120,000์` ๋ฏธ๋ง์ธ ๊ฒฝ์ฐ, ์ฆ์ ๊ฐ์ 0์ผ๋ก ์ค์
+ -[x] ์กฐ๊ฑด์ ๋ฐ๋ผ ์ฆ์ ๊ฒฐ๊ณผ ์ถ๋ ฅ
+ -[x] `์ด์ฃผ๋ฌธ ๊ธ์ก`์ด `120,000์` ์ด์์ธ ๊ฒฝ์ฐ, "์ดํ์ธ n๊ฐ" ์ถ๋ ฅ
+ -[x] `์ด์ฃผ๋ฌธ ๊ธ์ก`์ด `120,000์` ๋ฏธ๋ง์ธ ๊ฒฝ์ฐ, "์์" ์ถ๋ ฅ
+
+5๏ธโฃ ํํ ๋ด์ญโจ : DiscountService -> EventService
+
+-[x] ํํ์ ๋ฐ์ ์ ์๋ ์กฐ๊ฑด์ธ์ง ํ์ธ
+ -[x] `์ด์ฃผ๋ฌธ๊ธ์ก`์ด 10,000์ ์ด์์ธ์ง ํ์ธ
+-[x] ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ
+ -[x] 1์ผ๋ถํฐ 25์ผ ์ฌ์ด์ ๋ ์ง์๋ง ์ด๋ฒคํธ ์ ์ฉ
+ -[x] 1์ผ์ 1000์๋ถํฐ ์์ํ์ฌ, ํ๋ฃจ๊ฐ ์ง๋ ์๋ก 100์์ฉ ์ถ๊ฐ ํ ์ธ
+ -[x] "ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ: -1,200์" ํํ๋ก ์ถ๋ ฅ
+-[x] ํ์ผ ํ ์ธ
+ -[x] ์ผ์์ผ~๋ชฉ์์ผ ์งํ
+ -[x] `๋์ ํธ`๋ฉ๋ด๋ฅผ `1๊ฐ๋น 2023์` ํ ์ธ
+ -[x] "ํ์ผ ํ ์ธ: -4,046์" ํํ๋ก ์ถ๋ ฅ. ๋จ ํ ์ธ์ด ์๋๋ ๊ฒฝ์ฐ, ์ถ๋ ฅ์ ๋ณ๋๋ก ํ์ง ์์
+-[x] ์ฃผ๋ง ํ ์ธ
+ -[x] ๊ธ์์ผ~ํ ์์ผ ์งํ
+ -[x] `๋ฉ์ธ`๋ฉ๋ด๋ฅผ `1๊ฐ๋น 2,023์` ํ ์ธ
+ -[x] "์ฃผ๋ง ํ ์ธ: -1,000์" ํํ๋ก ์ถ๋ ฅ. ๋จ ํ ์ธ์ด ์๋๋ ๊ฒฝ์ฐ, ์ถ๋ ฅ์ ๋ณ๋๋ก ํ์ง ์์
+-[x] ํน๋ณ ํ ์ธ
+ -[x] ์ด๋ฒคํธ ๋ฌ๋ ฅ์ ๋ณ์ด ์๋ ๊ฒฝ์ฐ(๋งค์ฃผ ์ผ์์ผ + 25์ผ)
+ -[x] `์ด ๊ธ์ก`์์ `1000์` ํ ์ธ
+ -[x] "ํน๋ณ ํ ์ธ: -1,000์" ํํ๋ก ์ถ๋ ฅ. ๋จ ํ ์ธ์ด ์๋๋ ๊ฒฝ์ฐ, ์ถ๋ ฅ์ ๋ณ๋๋ก ํ์ง ์์
+-[x] ํํ ๋ด์ญ์ ๋ํด ์ถ๋ ฅ
+ -[x] ํฌ๋งท์ {์ข
๋ฅ} ํ ์ธ: -{ํ ์ธ ๊ฐ๊ฒฉ}์. ์ด ๋, ๊ฐ๊ฒฉ์ 1000์ ๋จ์๋ก ์ผํ(,)๋ฅผ ๋ฃ๋๋ค
+ -[x] ๋ง์ผ, ๋ชจ๋ ํํ์ ๋ฐ์ง ๋ชปํ ๊ฒฝ์ฐ์๋ "์์"์ผ๋ก ํ์ํ๋ค
+
+6๏ธโฃ ์ดํํ ๊ธ์ก : DiscountService -> EventService
+
+-[x] ์ดํํ ๊ธ์ก์ ๋ํด ๊ณ์ฐ ๋ฐ ์ถ๋ ฅ
+ -[x] ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด, ํ์ผ, ํน๋ณ, ์ฆ์ ์ด๋ฒคํธ ํ ์ธ์ ๋ชจ๋ ํฉํ ๊ฐ๊ฒฉ์ ํ์ํ๋ค (์ด ํ ์ธ ๊ธ์ก + ์ฆ์ ๋ฉ๋ด์ ๊ฐ๊ฒฉ)
+ -[x] ์์ -๊ฐ ๋ถ์ผ๋ฉฐ, 1000์ ๋จ์๋ง๋ค ์ผํ(,)๋ฅผ ์ถ๊ฐํ๋ค
+
+7๏ธโฃ ํ ์ธ ํ, ์์ ๊ฒฐ์ ๊ธ์ก
+
+-[x] ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก์ ๋ํด ๊ณ์ฐ ๋ฐ ์ถ๋ ฅ
+ -[x] `ํ ์ธ ์ ์ด์ฃผ๋ฌธ ๊ธ์ก` - `์ดํํ ๊ธ์ก`์ ๊ณ์ฐํ ๊ฒฐ๊ณผ๋ฅผ ์ถ๋ ฅํ๋ค
+ -[x] 1000์ ๋จ์๋ง๋ค ์ผํ(,)๋ฅผ ์ถ๊ฐํ๋ค
+
+8๏ธโฃ 12์ ์ด๋ฒคํธ ๋ฐฐ์ง
+
+-[x] ์ด๋ฒคํธ ๋ฐฐ์ง: `์ด ํํ ๊ธ์ก`์ ๋ฐ๋ผ ๋ฐฐ์ง ๋ถ์ฌ ๋ฐ ์ถ๋ ฅ
+ -[x] ์ด๋ฒคํธ ๋ฐฐ์ง์ ๋ํด ๊ณ์ฐ
+ -[x] 5000 <= x < 10,000 : ๋ณ
+ -[x] 10,000 <= x < 20,000 : ํธ๋ฆฌ
+ -[x] 20,000 <= x : ์ฐํ
+
+---
+
+### ํ๋ก๊ทธ๋๋ฐ ์๊ตฌ ์ฌํญ
+
+-[x] ApplicationTest์ ๋ชจ๋ ํ
์คํธ๊ฐ ์ฑ๊ณตํด์ผ ํ๋ค.
+-[x] indent depth๋ 2๊น์ง ํ์ฉํ๋ค.
+-[x] ๋ฉ์๋์ ๊ธธ์ด๊ฐ 15๋ฅผ ๋์ด๊ฐ์ง ์๋๋ก ํ๋ค.
+-[x] ์ฌ์ฉ์๊ฐ ์๋ชป๋ ๊ฐ์ ์
๋ ฅํ ๊ฒฝ์ฐ, `IllegalArgumentException`์ ๋ฐ์์ํค๊ณ , `[ERROR]`๋ก ์์ํ๋ ์๋ฌ ๋ฉ์์ง๋ฅผ ์ถ๋ ฅํ ํ, ๊ทธ ๋ถ๋ถ๋ถํฐ ์
๋ ฅ์ ๋ค์ ๋ฐ๋๋ค.
+-[x] ์
๋ ฅ๊ณผ ์ถ๋ ฅ์ ๋ด๋นํ๋ ํด๋์ค๋ฅผ ๋ณ๋๋ก ๊ตฌํํ๋ค.
+ -[x] InputView: readDate()...
+ -[x] OutputView : printMenu()...
+-[x] Console.readLine()์ ํ์ฉํ๋ค.
+
+---
+
+### 3์ฃผ์ฐจ ํผ๋๋ฐฑ ๋ด์ฉ
+
+-[x] 3์ฃผ์ฐจ ๊ณตํตํผ๋๋ฐฑ ์งํค๊ธฐ!
+-[x] `Integer.parseInt()`๋ฅผ ์ฌ์ฉํ๋ฉด ์ ์์ ๋ฒ์๊ฐ ์๋ ๋์๋ ์์ธ๊ฐ ๋ฐ์ํ๋๋ฐ, ์์ธ ๋ฉ์์ง๋ฅด ์กฐ๊ธ ๋ ๊ผผ๊ผผํ๊ฒ ์ฑ๊ธฐ์
+-[x] Enum์์ ๋ฌธ์์ด์ ํฉ์น ๋ `+`๋ณด๋ค๋, `String.format()`์ ์ฌ์ฉํ์
+-[x] `System.lineSeperator()`์ `String.format("%n")`์ ๊ฐ์ ์ญํ ์ ํ๋ค. ํ์ฉํด๋ณด์!
+-[x] ์๊ตฌ์ฌํญ์ ๊ผผ๊ผผํ๊ฒ ์ฝ์. (์ธ์๋ฆฌ๋ง๋ค ์ผํ๋ฅผ ๋ฃ์ด์ค๋ค๋์ง...)
+-[x] ์์๋ฅผ enum์ผ๋ก ๋บ์ผ๋ฉด ์ด๋ฅผ ํ์ฉํ์! ๋งค์ง ๋๋ฒ์ ์ฌ์ฉ์ ์ค์ด์! ํ์ฅ์ฑ์ ๊ณ ๋ คํ ๊ตฌ์กฐ๋ฅผ ๋ง๋ค์!
+-[x] ์์ธ๋ฅผ ๋ค์ ๋ฐ๋ ๋ฐฉ๋ฒ์ผ๋ก ์ฌ๊ท๋ฅผ ์ฌ์ฉํ๋๋ฐ, ๋ฉ๋ชจ๋ฆฌ๊ฐ ํฐ์ง ๊ฐ๋ฅ์ฑ์ด ์๋ค. `Supplier`๋ฅผ ๋์
ํด๋ณด์.
+-[x] ๊ฒ์ฆ(Validate)๊ณผ ํ์ฑ(Parsing)์ ๋ก์ง์ ์ด๋์ ๋๋ฉด ์ข์๊น? ๊ณ ๋ฏผํด๋ณด์.
+-[x] ๋๋ฏธํฐ์ ๋ฒ์น!
+-[x] `Console.close()`๋ฅผ ํตํด ์ฌ์ฉ ์๋ฃํ ์ฝ์์ ๋ซ์์ฃผ์
+
+---
+
+### ๊ฐ๋ฐ ์ค ์์ฑํ๋ ๋ฆฌํฉํ ๋ง ๋ชฉ๋ก
+
+-[x] IoC ์ปจํ
์ด๋ ์ ์ฉํ๊ธฐ
+-[x] Enum์ด ๋๋ฌด ์ฐํ์ฃฝ์ ์๊ธด ๊ฒ ๊ฐ๋ค! ์ ๋ฆฌํ ์ ์๋ ๋ถ๋ถ์ ์ ๋ฆฌํด๋ณด์
+-[x] InputView, OutputView์์ `readLine()`๊ณผ `System.out.print` ๋ถ๋ถ ์ถ์ํํ๊ธฐ
+-[x] `Supplier`๋ฅผ ์ด์ฉํ์ฌ ์ฌ์
๋ ฅ ์ฒ๋ฆฌํ๊ธฐ
+-[x] Validator(๊ฒ์ฆ)์ ์ญํ ์ด ์ ์ ํ๊ฒ ๋ถ๋ฐฐ๋์ด ์๋์ง ํ์ธ
+ -[x] MenuService์ validate ํจ์๋ค์ ๋ํด ์ค๋ณต๋์ด์๋ ์ฝ๋ ์ฒ๋ฆฌํ๊ธฐ
+-[x] MenuService์ ์ฝ๋๊ฐ ์กฐ๊ธ ๋์กํ ๊ฒ ๊ฐ์
+-[x] Message์ %n์ ๋ํด ์ด๋ป๊ฒ...์ฒ๋ฆฌ ์ข ํ๊ธฐ
+-[ ] Parser์์ parseToDate, parseToAmount์ ์ฝ๋๊ฐ ๊ฒน์น๋ค. ์ ๋ฌํ๋ ์์ธ ๋ฉ์ธ์ง๋ง ๋ค๋ฅธ๋ฐ... ๋ฐฉ๋ฒ์ ์ฐพ์๋ณด์.
+-[x] DiscountResult์ ๋๋ฌด ๋ง์ ์ฑ
์์ด ์๋ ๊ฒ ๊ฐ๋ค! DiscountService์๊ฒ ์ฑ
์์ ๋ ๋ถ์ฌํ์.
+ -> DiscountResult -> EventResult -> EventService๋ก ๋ณ๊ฒฝ ๋ฐ ์ญํ ๋ถ์ฌ
+-[x] ๋ฉ์๋, ๋ณ์๋ช
์ด ์ ์ ํ์ง ํ์ธ ํ ์์
+-[x] ๋ฉ๋ด๋ฅผ ์๋ชป์
๋ ฅํ์ ๋ `IndexOutOfBounds`๊ฐ ๋ฐ์ํ๋ฉด์ ์ข
๋ฃ๋๋ค.
+-[x] OutputView์์ formatting์ ํ๋ฉด์ ๊ฒน์น๋ ์ฝ๋๊ฐ ๊ณณ๊ณณ์ ์๋ค. ์์ ํ์!
+
+---
+
+### ๊ตฌํํ๋ฉด์ ์ง์คํ๋ ๋ถ๋ถ๋ค! ๊ณ ๋ฏผ๊ฑฐ๋ฆฌ!
+
+#### โ
Discountable(Eventable๋ก ๋ณ๊ฒฝ) ์ธํฐํ์ด์ค์ ์ ๋๋ฆญ์ ์ ์ฉํ์
+
+> ๐ง ๊ณ ๋ฏผ ๋ด์ฉ ๐ง
+> ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด, ์ฆ์ ์ด๋ฒคํธ, ํ์ผ ํ ์ธ, ์ฃผ๋ง ํ ์ธ, ํน๋ณ ํ ์ธ ๋ชจ๋ ๊ฐ์๋ง์ ๊ณ ์ ํ ํ ์ธ ์กฐ๊ฑด๋ค์ด ์๋ค.
+> ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด์ ์ฆ์ ์ด๋ฒคํธ๋ `์ด ์ฃผ๋ฌธ ๊ธ์ก`๊ณผ `๋ ์ง`๋ฅผ ํ์ธํ๋ฉด ๋๋๋ฐ, ์ด๋ค์ ๋ชจ๋ intํ์ผ๋ก ์ฒ๋ฆฌ๊ฐ ๊ฐ๋ฅํ๋ค.
+>
+> ํ์ง๋ง ํ์ผ, ์ฃผ๋ง ํ ์ธ์ `๋ ์ง`๋ง ๋ฐ๋ ๊ฒ์ด ์๋๋ผ, ๋ฉ๋ด์ ๋ํ ์ต์ํ์ ์ ๋ณด๊ฐ ์ถ๊ฐ์ ์ผ๋ก ํ์ํ๋ค.
+> ๋ชจ๋ ํ ์ธ ํด๋์ค๋ค์ด ๊ณตํต์ผ๋ก ๊ฐ์ง๊ณ ์์ด์ผ ํ๋ ๊ฒ๋ค์ `Discountable ์ธํฐํ์ด์ค(Eventable ์ธํฐํ์ด์ค๋ก ๋ณ๊ฒฝ)`๋ก ํํํ๊ณ ์ถ์๋ฐ ์ด๋ป๊ฒ ํ๋ฉด ์ข์๊น?
+
+์ด์ ๋ํด ์๊ฐ๋ ํด๋ต์ ๋ฐ๋ก `์ ๋๋ฆญ`์ ์ฌ์ฉํ๋ ๊ฒ์ด์๋ค.
+`์ ๋๋ฆญ`์ ์ฌ์ฉํ๋ฉด `canDiscount`์ ๋งค๊ฐ๋ณ์์ ์๋ฃํ์ ์๊ด์์ด ์ ๋ฌํ๊ณ ์ถ์ ๋ฐ์ดํฐ๋ฅผ ์ ๋ฌํ ์ ์๊ธฐ ๋๋ฌธ์ด๋ค.
+๋ฐ๋ผ์ `Discountable` ์ธํฐํ์ด์ค์ `canDiscount()`์ ๋งค๊ฐ๋ณ์๋ก ์ ๋ฌ๋๋ ์กฐ๊ฑด(`condition`) `์ ๋๋ฆญ <T>`๋ฅผ ์ ์ฉํ๋ค.
+
+<br>
+
+#### โ
View์์ ์ ์ ํ ๋ณํํด์ ์ ๋ฌํ์. ๊ผญ String์ผ๋ก ์ ๋ฌํ ํ์๊ฐ ์๋ค.
+
+<br>
+
+#### โ
๋ค๋ฅธ ๊ณ์ธต๊ณผ ๋ฐ์ดํฐ๋ฅผ ์ฃผ๊ณ ๋ฐ์ ๋์๋ DTO๋ฅผ ์ด์ฉํ์.
+
+
+ | Unknown | ๊ณ ๋ฏผ ๋ด์ฉ์ ์ ์ผ์ ๊ฒ... ์ฐธ์ ํ๋ค์ !! ์ ๋ ๋ฆฌ๋๋ฏธ ์์ฑ์ด ํ๋ค์ด์ ใ
.ใ
๋ฐฐ์๊ฐ๋๋ค ๐ |
@@ -0,0 +1,24 @@
+package com.requestrealpiano.songrequest.controller;
+
+import com.requestrealpiano.songrequest.service.AccountService;
+import lombok.RequiredArgsConstructor;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.*;
+
+@RequiredArgsConstructor
+@RestController
+@RequestMapping("/api/accounts")
+public class AccountController {
+
+ private final AccountService accountService;
+
+ @GetMapping("/auth")
+ public ResponseEntity<Void> generateToken(@RequestHeader HttpHeaders httpHeaders) {
+ String jwtToken = accountService.generateJwtToken(httpHeaders.getFirst(HttpHeaders.AUTHORIZATION));
+ HttpHeaders responseHeaders = new HttpHeaders();
+ responseHeaders.add(HttpHeaders.AUTHORIZATION, jwtToken);
+ return new ResponseEntity<>(responseHeaders, HttpStatus.NO_CONTENT);
+ }
+} | Java | ๋ค๋ฅธ ์ปจํธ๋กค๋ฌ์์๋ ResponseStatus๋ก ์ง์ ํ๋๋ฐ ์ฌ๊ธด ResponseEntity๋ก ์ง์ ํ๊ตฐ์ ์ด๋ค ์ด์ ๋ก ์ง์ ํ๋์ง ๊ถ๊ธํฉ๋๋ค. |
@@ -2,18 +2,18 @@
import com.requestrealpiano.songrequest.domain.song.searchapi.response.SearchApiResponse;
import com.requestrealpiano.songrequest.global.response.ApiResponse;
+import com.requestrealpiano.songrequest.global.response.StatusCode;
import com.requestrealpiano.songrequest.service.SongService;
import lombok.RequiredArgsConstructor;
+import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.bind.annotation.*;
import javax.validation.constraints.Size;
import static com.requestrealpiano.songrequest.global.constant.ValidationCondition.*;
-import static com.requestrealpiano.songrequest.global.response.ApiResponse.OK;
+import static com.requestrealpiano.songrequest.global.response.ApiResponse.SUCCESS;
+import static com.requestrealpiano.songrequest.global.response.StatusCode.OK;
@RequiredArgsConstructor
@Validated
@@ -23,12 +23,13 @@ public class SongController {
private final SongService songService;
+ @ResponseStatus(HttpStatus.OK)
@GetMapping
public ApiResponse<SearchApiResponse> search(@RequestParam(defaultValue = "artist") @Size(max = ARTIST_MAX)
String artist,
@RequestParam(defaultValue = "title") @Size(max = TITLE_MAX)
String title) {
SearchApiResponse searchApiResponse = songService.searchSong(artist, title);
- return OK(searchApiResponse);
+ return SUCCESS(OK, searchApiResponse);
}
} | Java | ์ด ๋ถ๋ถ์ ์ปจํธ๋กค๋ฌ์์ Validation์ ์ก๊ธฐ๋ณด๋จ Validation DTO๋ฅผ ์์ฑํด์ ํด๋น ๊ฐ์ฒด์์ ๊ด๋ฆฌํ๋ฉด ๋์ฑ ํธ๋ฆฌํ๊ณ ๋ณด๊ธฐ๊ฐ ์ข์๋ฏ ํฉ๋๋ค. |
@@ -1,5 +1,6 @@
package com.requestrealpiano.songrequest.domain.account;
+import com.requestrealpiano.songrequest.security.oauth.OAuthAttributes;
import com.requestrealpiano.songrequest.domain.base.BaseTimeEntity;
import com.requestrealpiano.songrequest.domain.letter.Letter;
import lombok.AccessLevel;
@@ -8,9 +9,6 @@
import lombok.NoArgsConstructor;
import javax.persistence.*;
-import java.time.LocalDate;
-import java.time.LocalDateTime;
-import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
@@ -25,7 +23,7 @@ public class Account extends BaseTimeEntity {
private Long id;
@Column(name = "google_oauth_id")
- private Long googleOauthId;
+ private String googleOauthId;
private String name;
@@ -44,12 +42,36 @@ public class Account extends BaseTimeEntity {
private List<Letter> letters = new ArrayList<>();
@Builder
- private Account(Long googleOauthId, String name, String email, Role role, String avatarUrl, Integer requestCount) {
+ private Account(String googleOauthId, String name, String email, Role role, String avatarUrl, Integer requestCount) {
this.googleOauthId = googleOauthId;
this.name = name;
this.email = email;
this.role = role;
this.avatarUrl = avatarUrl;
this.requestCount = requestCount;
}
+
+ public String getRoleKey() { return role.getKey(); }
+
+ public String getRoleValue() {
+ return role.getValue();
+ }
+
+ public Account updateProfile(OAuthAttributes attributes) {
+ this.name = attributes.getName();
+ this.email = attributes.getEmail();
+ this.avatarUrl = attributes.getAvatarUrl();
+ return this;
+ }
+
+ public static Account from(OAuthAttributes oAuthAttributes) {
+ return Account.builder()
+ .googleOauthId(oAuthAttributes.getGoogleOauthId())
+ .name(oAuthAttributes.getName())
+ .email(oAuthAttributes.getEmail())
+ .role(Role.MEMBER)
+ .avatarUrl(oAuthAttributes.getAvatarUrl())
+ .requestCount(0)
+ .build();
+ }
} | Java | ์ใ
ใ
ใ
ใ
OAuthId๋ฅผ ํ์ธํ์๊ณ ๋ฐ๊พธ์
จ๊ตฐ์. |
@@ -1,5 +1,6 @@
package com.requestrealpiano.songrequest.domain.account;
+import com.requestrealpiano.songrequest.security.oauth.OAuthAttributes;
import com.requestrealpiano.songrequest.domain.base.BaseTimeEntity;
import com.requestrealpiano.songrequest.domain.letter.Letter;
import lombok.AccessLevel;
@@ -8,9 +9,6 @@
import lombok.NoArgsConstructor;
import javax.persistence.*;
-import java.time.LocalDate;
-import java.time.LocalDateTime;
-import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
@@ -25,7 +23,7 @@ public class Account extends BaseTimeEntity {
private Long id;
@Column(name = "google_oauth_id")
- private Long googleOauthId;
+ private String googleOauthId;
private String name;
@@ -44,12 +42,36 @@ public class Account extends BaseTimeEntity {
private List<Letter> letters = new ArrayList<>();
@Builder
- private Account(Long googleOauthId, String name, String email, Role role, String avatarUrl, Integer requestCount) {
+ private Account(String googleOauthId, String name, String email, Role role, String avatarUrl, Integer requestCount) {
this.googleOauthId = googleOauthId;
this.name = name;
this.email = email;
this.role = role;
this.avatarUrl = avatarUrl;
this.requestCount = requestCount;
}
+
+ public String getRoleKey() { return role.getKey(); }
+
+ public String getRoleValue() {
+ return role.getValue();
+ }
+
+ public Account updateProfile(OAuthAttributes attributes) {
+ this.name = attributes.getName();
+ this.email = attributes.getEmail();
+ this.avatarUrl = attributes.getAvatarUrl();
+ return this;
+ }
+
+ public static Account from(OAuthAttributes oAuthAttributes) {
+ return Account.builder()
+ .googleOauthId(oAuthAttributes.getGoogleOauthId())
+ .name(oAuthAttributes.getName())
+ .email(oAuthAttributes.getEmail())
+ .role(Role.MEMBER)
+ .avatarUrl(oAuthAttributes.getAvatarUrl())
+ .requestCount(0)
+ .build();
+ }
} | Java | ์ฌ๊ธฐ ์ ํ์๋ MaginNumber 0์ ์ด๋ค์๋ฏธ์ธ๊ฐ์? |
@@ -11,6 +11,12 @@ public enum ErrorCode {
METHOD_NOT_ALLOWED(405, "์ง์ํ์ง ์๋ ์์ฒญ ๋ฉ์๋ ์
๋๋ค."),
INTERNAL_SERVER_ERROR(500, "์๋ฒ์์ ์์ฒญ์ ์ฒ๋ฆฌํ์ง ๋ชปํ์ต๋๋ค."),
+ // Auth
+ UNAUTHENTICATED_ERROR(401, "์ธ์ฆ์ด ํ์ํฉ๋๋ค. ๋ก๊ทธ์ธ ์ดํ ๋ค์ ์๋ ํด์ฃผ์ธ์."),
+ JWT_INVALID_ERROR(400, "์ฌ๋ฐ๋ฅธ ์ธ์ฆ ์ ๋ณด๊ฐ ์๋๋๋ค. ๋ค์ ๋ก๊ทธ์ธ ํด์ฃผ์ธ์."),
+ JWT_EXPIRATION_ERROR(401, "์ธ์ฆ ์ ๋ณด๊ฐ ๋ง๋ฃ ๋์์ต๋๋ค. ๋ค์ ๋ก๊ทธ์ธ ํด์ฃผ์ธ์."),
+ ACCESS_DENIED_ERROR(403, "ํด๋น ์์ฒญ์ ๋ํ ์ ๊ทผ ๊ถํ์ด ์์ต๋๋ค."),
+
// Account
ACCOUNT_NOT_FOUND(404, "ํด๋น ๊ณ์ ์ด ์กด์ฌํ์ง ์์ต๋๋ค."),
| Java | ์ฌ๊ธฐ์ JWT ์ธ์ฆํ ๋ ๋๊ฐ์ง ์กฐ๊ฑด์ด ์๋๊ตฐ์.
1. JWT๊ฐ ์๋ Token์ ์ฌ์ฉํ ๊ฒฝ์ฐ - 400
2. JWT๋ ๋ง๋๋ฐ ์ฌ๋ฐ๋ฅธ JWT๊ฐ ์๋ ๊ฒฝ์ฐ - 401
๋๊ฐ์ง ๊ณ ๋ คํ์๋๊ฑด ์ด๋ ์ ์ง ๋๋ ์๊ฒฌ์ด ๊ถ๊ธํฉ๋๋ค. |
@@ -11,6 +11,12 @@ public enum ErrorCode {
METHOD_NOT_ALLOWED(405, "์ง์ํ์ง ์๋ ์์ฒญ ๋ฉ์๋ ์
๋๋ค."),
INTERNAL_SERVER_ERROR(500, "์๋ฒ์์ ์์ฒญ์ ์ฒ๋ฆฌํ์ง ๋ชปํ์ต๋๋ค."),
+ // Auth
+ UNAUTHENTICATED_ERROR(401, "์ธ์ฆ์ด ํ์ํฉ๋๋ค. ๋ก๊ทธ์ธ ์ดํ ๋ค์ ์๋ ํด์ฃผ์ธ์."),
+ JWT_INVALID_ERROR(400, "์ฌ๋ฐ๋ฅธ ์ธ์ฆ ์ ๋ณด๊ฐ ์๋๋๋ค. ๋ค์ ๋ก๊ทธ์ธ ํด์ฃผ์ธ์."),
+ JWT_EXPIRATION_ERROR(401, "์ธ์ฆ ์ ๋ณด๊ฐ ๋ง๋ฃ ๋์์ต๋๋ค. ๋ค์ ๋ก๊ทธ์ธ ํด์ฃผ์ธ์."),
+ ACCESS_DENIED_ERROR(403, "ํด๋น ์์ฒญ์ ๋ํ ์ ๊ทผ ๊ถํ์ด ์์ต๋๋ค."),
+
// Account
ACCOUNT_NOT_FOUND(404, "ํด๋น ๊ณ์ ์ด ์กด์ฌํ์ง ์์ต๋๋ค."),
| Java | ์ฌ๊ธฐ์๋ ์ด์ผ๊ธฐ ํ๊ณ ์ถ์๊ฒ์ด ์์ต๋๋ค. ํด๋น API๋ฅผ ์ฌ์ฉํ ๋ ๊ถํ์ ๋ง๋ ๊ฒ์ด 403์ด์ง๋ง ๋ง์ฝ ๋น๊ณต๊ฐ๋ ์ ๋ณด๋ฅผ API๋ฅผ ์ฌ์ฉํ์ฌ ๊ฐ์ ธ์ฌ๋๋ 404๋ก Not Found๋ก ๋์์ผํ๋ค๊ณ ํ๋๊ตฐ์.
๊ทธ์ ๋ํ ๋๋น์ฑ
๋ ํ์ํด ๋ณด์
๋๋ค. |
@@ -0,0 +1,105 @@
+package com.requestrealpiano.songrequest.security;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.requestrealpiano.songrequest.domain.account.Role;
+import com.requestrealpiano.songrequest.security.filter.JwtAuthorizationFilter;
+import com.requestrealpiano.songrequest.security.jwt.JwtTokenProvider;
+import com.requestrealpiano.songrequest.security.oauth.CustomAccessDeniedHandler;
+import com.requestrealpiano.songrequest.security.oauth.CustomAuthenticationEntryPoint;
+import com.requestrealpiano.songrequest.security.oauth.CustomAuthenticationSuccessHandler;
+import com.requestrealpiano.songrequest.security.oauth.CustomOAuth2UserService;
+import com.requestrealpiano.songrequest.domain.account.AccountRepository;
+import lombok.RequiredArgsConstructor;
+import org.springframework.boot.autoconfigure.security.servlet.PathRequest;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.http.HttpMethod;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.annotation.web.builders.WebSecurity;
+import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
+import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
+import org.springframework.security.config.http.SessionCreationPolicy;
+import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
+import org.springframework.security.web.csrf.CsrfFilter;
+import org.springframework.web.cors.CorsConfiguration;
+import org.springframework.web.cors.CorsConfigurationSource;
+import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
+import org.springframework.web.filter.CharacterEncodingFilter;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+import static org.springframework.security.config.Customizer.withDefaults;
+
+@RequiredArgsConstructor
+@Configuration
+@EnableWebSecurity
+public class SecurityConfig extends WebSecurityConfigurerAdapter {
+
+ private final CustomOAuth2UserService customOAuth2UserService;
+ private final CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;
+ private final CustomAuthenticationEntryPoint customAuthenticationEntryPoint;
+ private final CustomAccessDeniedHandler customAccessDeniedHandler;
+ private final AccountRepository accountRepository;
+ private final JwtTokenProvider jwtTokenProvider;
+ private final ObjectMapper objectMapper;
+
+ @Override
+ public void configure(WebSecurity web) throws Exception {
+ web.ignoring().requestMatchers(PathRequest.toStaticResources().atCommonLocations());
+
+ web.ignoring().antMatchers(HttpMethod.GET, "/api/accounts/auth")
+ .antMatchers(HttpMethod.GET, "/api/letters/**")
+ ;
+ }
+
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http.cors(withDefaults());
+
+ http.csrf().disable()
+ .httpBasic().disable();
+
+ http.authorizeRequests()
+// .antMatchers("/**").permitAll()
+ .antMatchers("/api/letters").hasAnyRole(Role.MEMBER.getKey(), Role.ADMIN.getKey())
+ .antMatchers("/api/songs").hasAnyRole(Role.MEMBER.getKey(), Role.ADMIN.getKey())
+ .anyRequest().authenticated();
+
+ http.sessionManagement()
+ .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
+
+ http.addFilterBefore(characterEncodingFilter(), CsrfFilter.class)
+ .addFilterBefore(JwtAuthorizationFilter.of(accountRepository, jwtTokenProvider, objectMapper), UsernamePasswordAuthenticationFilter.class);
+
+ http.oauth2Login()
+ .userInfoEndpoint()
+ .userService(customOAuth2UserService)
+ .and()
+ .successHandler(customAuthenticationSuccessHandler);
+
+ http.exceptionHandling()
+ .authenticationEntryPoint(customAuthenticationEntryPoint)
+ .accessDeniedHandler(customAccessDeniedHandler);
+ }
+
+ public CharacterEncodingFilter characterEncodingFilter() {
+ CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
+ encodingFilter.setEncoding("UTF-8");
+ encodingFilter.setForceEncoding(true);
+ return encodingFilter;
+ }
+
+ @Bean
+ CorsConfigurationSource corsConfigurationSource() {
+ CorsConfiguration configuration = new CorsConfiguration();
+ configuration.setAllowedOrigins(Collections.singletonList("*"));
+ configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
+ configuration.setAllowedHeaders(Collections.singletonList("*"));
+ configuration.setExposedHeaders(Collections.singletonList("Authorization"));
+ configuration.setAllowCredentials(true);
+ UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
+ source.registerCorsConfiguration("/**", configuration);
+ return source;
+ }
+} | Java | ์ฌ์ฉํ์์ง ์์ ์ฝ๋๋ฉด ์ญ์ ํ๊ณ ๊ทธ๋๋ ์ฃผ์์ฒ๋ฆฌ๋ฅผ ๋จ๊ธฐ๊ณ ์ถ๋ค๋ฉด ์ ์ฃผ์์ฒ๋ฆฌํ๋์ง์ ๋ํ ์ค๋ช
์ ์ถ๊ฐํด์ฃผ์ธ์ |
@@ -0,0 +1,105 @@
+package com.requestrealpiano.songrequest.security;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.requestrealpiano.songrequest.domain.account.Role;
+import com.requestrealpiano.songrequest.security.filter.JwtAuthorizationFilter;
+import com.requestrealpiano.songrequest.security.jwt.JwtTokenProvider;
+import com.requestrealpiano.songrequest.security.oauth.CustomAccessDeniedHandler;
+import com.requestrealpiano.songrequest.security.oauth.CustomAuthenticationEntryPoint;
+import com.requestrealpiano.songrequest.security.oauth.CustomAuthenticationSuccessHandler;
+import com.requestrealpiano.songrequest.security.oauth.CustomOAuth2UserService;
+import com.requestrealpiano.songrequest.domain.account.AccountRepository;
+import lombok.RequiredArgsConstructor;
+import org.springframework.boot.autoconfigure.security.servlet.PathRequest;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.http.HttpMethod;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.annotation.web.builders.WebSecurity;
+import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
+import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
+import org.springframework.security.config.http.SessionCreationPolicy;
+import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
+import org.springframework.security.web.csrf.CsrfFilter;
+import org.springframework.web.cors.CorsConfiguration;
+import org.springframework.web.cors.CorsConfigurationSource;
+import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
+import org.springframework.web.filter.CharacterEncodingFilter;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+import static org.springframework.security.config.Customizer.withDefaults;
+
+@RequiredArgsConstructor
+@Configuration
+@EnableWebSecurity
+public class SecurityConfig extends WebSecurityConfigurerAdapter {
+
+ private final CustomOAuth2UserService customOAuth2UserService;
+ private final CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;
+ private final CustomAuthenticationEntryPoint customAuthenticationEntryPoint;
+ private final CustomAccessDeniedHandler customAccessDeniedHandler;
+ private final AccountRepository accountRepository;
+ private final JwtTokenProvider jwtTokenProvider;
+ private final ObjectMapper objectMapper;
+
+ @Override
+ public void configure(WebSecurity web) throws Exception {
+ web.ignoring().requestMatchers(PathRequest.toStaticResources().atCommonLocations());
+
+ web.ignoring().antMatchers(HttpMethod.GET, "/api/accounts/auth")
+ .antMatchers(HttpMethod.GET, "/api/letters/**")
+ ;
+ }
+
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http.cors(withDefaults());
+
+ http.csrf().disable()
+ .httpBasic().disable();
+
+ http.authorizeRequests()
+// .antMatchers("/**").permitAll()
+ .antMatchers("/api/letters").hasAnyRole(Role.MEMBER.getKey(), Role.ADMIN.getKey())
+ .antMatchers("/api/songs").hasAnyRole(Role.MEMBER.getKey(), Role.ADMIN.getKey())
+ .anyRequest().authenticated();
+
+ http.sessionManagement()
+ .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
+
+ http.addFilterBefore(characterEncodingFilter(), CsrfFilter.class)
+ .addFilterBefore(JwtAuthorizationFilter.of(accountRepository, jwtTokenProvider, objectMapper), UsernamePasswordAuthenticationFilter.class);
+
+ http.oauth2Login()
+ .userInfoEndpoint()
+ .userService(customOAuth2UserService)
+ .and()
+ .successHandler(customAuthenticationSuccessHandler);
+
+ http.exceptionHandling()
+ .authenticationEntryPoint(customAuthenticationEntryPoint)
+ .accessDeniedHandler(customAccessDeniedHandler);
+ }
+
+ public CharacterEncodingFilter characterEncodingFilter() {
+ CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
+ encodingFilter.setEncoding("UTF-8");
+ encodingFilter.setForceEncoding(true);
+ return encodingFilter;
+ }
+
+ @Bean
+ CorsConfigurationSource corsConfigurationSource() {
+ CorsConfiguration configuration = new CorsConfiguration();
+ configuration.setAllowedOrigins(Collections.singletonList("*"));
+ configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
+ configuration.setAllowedHeaders(Collections.singletonList("*"));
+ configuration.setExposedHeaders(Collections.singletonList("Authorization"));
+ configuration.setAllowCredentials(true);
+ UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
+ source.registerCorsConfiguration("/**", configuration);
+ return source;
+ }
+} | Java | Role์ ์์ฃผ ์ฌ์ฉํ์ค ๋ฏํ๋ฐ import static์ผ๋ก ์ ์ธํ๋ ๊ฒ๋ ๋์์ง ์๋ค๊ณ ์๊ฐํฉ๋๋ค. |
@@ -0,0 +1,105 @@
+package com.requestrealpiano.songrequest.security;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.requestrealpiano.songrequest.domain.account.Role;
+import com.requestrealpiano.songrequest.security.filter.JwtAuthorizationFilter;
+import com.requestrealpiano.songrequest.security.jwt.JwtTokenProvider;
+import com.requestrealpiano.songrequest.security.oauth.CustomAccessDeniedHandler;
+import com.requestrealpiano.songrequest.security.oauth.CustomAuthenticationEntryPoint;
+import com.requestrealpiano.songrequest.security.oauth.CustomAuthenticationSuccessHandler;
+import com.requestrealpiano.songrequest.security.oauth.CustomOAuth2UserService;
+import com.requestrealpiano.songrequest.domain.account.AccountRepository;
+import lombok.RequiredArgsConstructor;
+import org.springframework.boot.autoconfigure.security.servlet.PathRequest;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.http.HttpMethod;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.annotation.web.builders.WebSecurity;
+import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
+import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
+import org.springframework.security.config.http.SessionCreationPolicy;
+import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
+import org.springframework.security.web.csrf.CsrfFilter;
+import org.springframework.web.cors.CorsConfiguration;
+import org.springframework.web.cors.CorsConfigurationSource;
+import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
+import org.springframework.web.filter.CharacterEncodingFilter;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+import static org.springframework.security.config.Customizer.withDefaults;
+
+@RequiredArgsConstructor
+@Configuration
+@EnableWebSecurity
+public class SecurityConfig extends WebSecurityConfigurerAdapter {
+
+ private final CustomOAuth2UserService customOAuth2UserService;
+ private final CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;
+ private final CustomAuthenticationEntryPoint customAuthenticationEntryPoint;
+ private final CustomAccessDeniedHandler customAccessDeniedHandler;
+ private final AccountRepository accountRepository;
+ private final JwtTokenProvider jwtTokenProvider;
+ private final ObjectMapper objectMapper;
+
+ @Override
+ public void configure(WebSecurity web) throws Exception {
+ web.ignoring().requestMatchers(PathRequest.toStaticResources().atCommonLocations());
+
+ web.ignoring().antMatchers(HttpMethod.GET, "/api/accounts/auth")
+ .antMatchers(HttpMethod.GET, "/api/letters/**")
+ ;
+ }
+
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http.cors(withDefaults());
+
+ http.csrf().disable()
+ .httpBasic().disable();
+
+ http.authorizeRequests()
+// .antMatchers("/**").permitAll()
+ .antMatchers("/api/letters").hasAnyRole(Role.MEMBER.getKey(), Role.ADMIN.getKey())
+ .antMatchers("/api/songs").hasAnyRole(Role.MEMBER.getKey(), Role.ADMIN.getKey())
+ .anyRequest().authenticated();
+
+ http.sessionManagement()
+ .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
+
+ http.addFilterBefore(characterEncodingFilter(), CsrfFilter.class)
+ .addFilterBefore(JwtAuthorizationFilter.of(accountRepository, jwtTokenProvider, objectMapper), UsernamePasswordAuthenticationFilter.class);
+
+ http.oauth2Login()
+ .userInfoEndpoint()
+ .userService(customOAuth2UserService)
+ .and()
+ .successHandler(customAuthenticationSuccessHandler);
+
+ http.exceptionHandling()
+ .authenticationEntryPoint(customAuthenticationEntryPoint)
+ .accessDeniedHandler(customAccessDeniedHandler);
+ }
+
+ public CharacterEncodingFilter characterEncodingFilter() {
+ CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
+ encodingFilter.setEncoding("UTF-8");
+ encodingFilter.setForceEncoding(true);
+ return encodingFilter;
+ }
+
+ @Bean
+ CorsConfigurationSource corsConfigurationSource() {
+ CorsConfiguration configuration = new CorsConfiguration();
+ configuration.setAllowedOrigins(Collections.singletonList("*"));
+ configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
+ configuration.setAllowedHeaders(Collections.singletonList("*"));
+ configuration.setExposedHeaders(Collections.singletonList("Authorization"));
+ configuration.setAllowCredentials(true);
+ UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
+ source.registerCorsConfiguration("/**", configuration);
+ return source;
+ }
+} | Java | `WebConfig`์์๋ CORS ์๋ฌ์ ๋ํ ๋๋น์ฑ
์ ์ค์ ํ์
จ๋๋ฐ ์ฌ๊ธฐ์๋ ์ค์ ํ ์ด์ ๊ฐ ๊ถ๊ธํฉ๋๋ค. |
@@ -0,0 +1,115 @@
+package com.requestrealpiano.songrequest.security.jwt;
+
+import com.requestrealpiano.songrequest.domain.account.Account;
+import com.requestrealpiano.songrequest.global.error.exception.jwt.JwtExpirationException;
+import com.requestrealpiano.songrequest.global.error.exception.jwt.JwtInvalidTokenException;
+import com.requestrealpiano.songrequest.global.error.exception.jwt.JwtRequiredException;
+import com.requestrealpiano.songrequest.security.jwt.claims.AccountClaims;
+import io.jsonwebtoken.*;
+import lombok.RequiredArgsConstructor;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.stereotype.Component;
+
+import java.util.Date;
+
+@RequiredArgsConstructor
+@Component
+public class JwtTokenProvider {
+
+ private final JwtProperties jwtProperties;
+
+ private final String ID = "id";
+ private final String EMAIL = "email";
+ private final String NAME = "name";
+ private final String AVATAR_URL = "avatarUrl";
+ private final String ROLE = "role";
+
+ public String createGenerationKey(String email) {
+ Date now = new Date();
+ return Jwts.builder()
+ .setHeaderParam(Header.TYPE, Header.JWT_TYPE)
+ .setIssuedAt(now)
+ .setExpiration(new Date(now.getTime() + Long.parseLong(jwtProperties.getGenerationKeyExpiration())))
+ .claim(EMAIL, email)
+ .signWith(SignatureAlgorithm.HS256, jwtProperties.getGenerationKeySecret())
+ .compact();
+ }
+
+ public String parseGenerationKey(String authorization) {
+ String generationKey = extractToken(authorization);
+ try {
+ Jws<Claims> claims = Jwts.parser()
+ .setSigningKey(jwtProperties.getGenerationKeySecret())
+ .parseClaimsJws(generationKey);
+ return claims.getBody()
+ .get(EMAIL, String.class);
+ } catch (ExpiredJwtException exception) {
+ throw new JwtExpirationException();
+ } catch (JwtException exception) {
+ throw new JwtInvalidTokenException();
+ }
+ }
+
+ public String createJwtToken(Account account) {
+ Date now = new Date();
+ String jwtToken = Jwts.builder()
+ .setHeaderParam(Header.TYPE, Header.JWT_TYPE)
+ .setIssuedAt(now)
+ .setExpiration(new Date(now.getTime() + Long.parseLong(jwtProperties.getTokenExpiration())))
+ .claim(ID, account.getId())
+ .claim(EMAIL, account.getEmail())
+ .claim(NAME, account.getName())
+ .claim(AVATAR_URL, account.getAvatarUrl())
+ .claim(ROLE, account.getRoleKey())
+ .signWith(SignatureAlgorithm.HS256, jwtProperties.getTokenSecret())
+ .compact();
+ return jwtProperties.getHeaderPrefix() + jwtToken;
+ }
+
+ public boolean validateJwtToken(String authorization) {
+ String jwtToken = extractToken(authorization);
+ try {
+ Jws<Claims> claims = Jwts.parser()
+ .setSigningKey(jwtProperties.getTokenSecret())
+ .parseClaimsJws(jwtToken);
+ return claims.getBody()
+ .getExpiration()
+ .after(new Date());
+ } catch (ExpiredJwtException exception) {
+ throw new JwtExpirationException();
+ } catch (JwtException exception) {
+ throw new JwtInvalidTokenException();
+ }
+ }
+
+ public AccountClaims parseJwtToken(String jwtToken) {
+ try {
+ Jws<Claims> claims = Jwts.parser()
+ .setSigningKey(jwtProperties.getTokenSecret())
+ .parseClaimsJws(jwtToken);
+ Claims body = claims.getBody();
+
+ return AccountClaims.from(body);
+ } catch (ExpiredJwtException exception) {
+ throw new JwtExpirationException();
+ } catch (JwtException exception) {
+ throw new JwtInvalidTokenException();
+ }
+ }
+
+ public String extractToken(String authorizationHeader) {
+ if (isTokenContained(authorizationHeader)) {
+ int tokenBeginIndex = jwtProperties.getHeaderPrefix().length();
+ return StringUtils.substring(authorizationHeader, tokenBeginIndex);
+ }
+ throw new JwtRequiredException();
+ }
+
+ private boolean isTokenContained(String authorization) {
+ if (StringUtils.isEmpty(authorization)) {
+ return false;
+ }
+
+ return authorization.startsWith(jwtProperties.getHeaderPrefix());
+ }
+} | Java | Date ํ์
์ ์ฐ์
จ๋๋ฐ LocalDate ํ์
์ด ์๋ ์ด์ ๊ฐ ๋ฌด์์ธ๊ฐ์? |
@@ -0,0 +1,21 @@
+package com.requestrealpiano.songrequest.security.jwt;
+
+import lombok.Getter;
+import lombok.RequiredArgsConstructor;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.boot.context.properties.ConstructorBinding;
+
+@RequiredArgsConstructor
+@Getter
+@ConstructorBinding
+@ConfigurationProperties(prefix = "jwt")
+public class JwtProperties {
+
+ private final String tokenSecret;
+ private final String tokenExpiration;
+ private final String header;
+ private final String headerPrefix;
+ private final String tokenUrl;
+ private final String generationKeySecret;
+ private final String generationKeyExpiration;
+} | Java | ์์ฑ์๊ฐ ํ์ํ๊ฐ์? ๋ถํ์ํ ์์ฑ์๊ฐ์์ |
@@ -0,0 +1,33 @@
+package com.requestrealpiano.songrequest.security.oauth;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.requestrealpiano.songrequest.global.error.response.ErrorCode;
+import com.requestrealpiano.songrequest.global.error.response.ErrorResponse;
+import lombok.RequiredArgsConstructor;
+import org.springframework.http.MediaType;
+import org.springframework.security.access.AccessDeniedException;
+import org.springframework.security.web.access.AccessDeniedHandler;
+import org.springframework.stereotype.Component;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+@RequiredArgsConstructor
+@Component
+public class CustomAccessDeniedHandler implements AccessDeniedHandler {
+
+ private final ObjectMapper objectMapper;
+
+ @Override
+ public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
+ ErrorCode accessDeniedError = ErrorCode.ACCESS_DENIED_ERROR;
+ String errorResponse = objectMapper.writeValueAsString(ErrorResponse.from(accessDeniedError));
+ response.getWriter().print(errorResponse);
+ response.setContentType(MediaType.APPLICATION_JSON_VALUE);
+ response.setStatus(accessDeniedError.getStatusCode());
+ response.getWriter().flush();
+ response.getWriter().close();
+ }
+} | Java | ์ด์ ๋ ๊ธธ์ด์ง๋ฉด throws๋ถํฐ ํ์นธ ๋ด๋ ค์ ๋ณด๊ธฐ ์ฝ๊ฒ ํด์ฃผ์ธ์ฉ |
@@ -0,0 +1,33 @@
+package com.requestrealpiano.songrequest.security.oauth;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.requestrealpiano.songrequest.global.error.response.ErrorCode;
+import com.requestrealpiano.songrequest.global.error.response.ErrorResponse;
+import lombok.RequiredArgsConstructor;
+import org.springframework.http.MediaType;
+import org.springframework.security.access.AccessDeniedException;
+import org.springframework.security.web.access.AccessDeniedHandler;
+import org.springframework.stereotype.Component;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+@RequiredArgsConstructor
+@Component
+public class CustomAccessDeniedHandler implements AccessDeniedHandler {
+
+ private final ObjectMapper objectMapper;
+
+ @Override
+ public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
+ ErrorCode accessDeniedError = ErrorCode.ACCESS_DENIED_ERROR;
+ String errorResponse = objectMapper.writeValueAsString(ErrorResponse.from(accessDeniedError));
+ response.getWriter().print(errorResponse);
+ response.setContentType(MediaType.APPLICATION_JSON_VALUE);
+ response.setStatus(accessDeniedError.getStatusCode());
+ response.getWriter().flush();
+ response.getWriter().close();
+ }
+} | Java | ์ฌ๊ธฐ์ ๊ถ๊ธํ๊ฒ ์ด๋๋ก ์ฌ์ฉํ์ ๋ ์๋ฌ์ฒ๋ฆฌ๋ ๋ฐ์์ด ์ ๋๊ฒ ์ผ๋ ์คํ๋ง ๋ก๊ทธ์๋ ์ฐํ๋ ์ง ๊ถ๊ธํฉ๋๋ค.
์ ๊ฐ ์ด์ ์ฝ๋์ค์ฟผ๋ ๋์๊ด ํ๋ก์ ํธ์์๋ ์ด๋ฐ์์ผ๋ก ์ฒ๋ฆฌํ์ ๋ ๋ก๊ทธ์ ์ฐํ์ง ์๋ ์ฌ์ํ ๋ฌธ์ ์ ์ด ์๊ฒผ์ต๋๋ค. |
@@ -0,0 +1,33 @@
+package com.requestrealpiano.songrequest.security.oauth;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.requestrealpiano.songrequest.global.error.response.ErrorCode;
+import com.requestrealpiano.songrequest.global.error.response.ErrorResponse;
+import lombok.RequiredArgsConstructor;
+import org.springframework.http.MediaType;
+import org.springframework.security.access.AccessDeniedException;
+import org.springframework.security.web.access.AccessDeniedHandler;
+import org.springframework.stereotype.Component;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+@RequiredArgsConstructor
+@Component
+public class CustomAccessDeniedHandler implements AccessDeniedHandler {
+
+ private final ObjectMapper objectMapper;
+
+ @Override
+ public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
+ ErrorCode accessDeniedError = ErrorCode.ACCESS_DENIED_ERROR;
+ String errorResponse = objectMapper.writeValueAsString(ErrorResponse.from(accessDeniedError));
+ response.getWriter().print(errorResponse);
+ response.setContentType(MediaType.APPLICATION_JSON_VALUE);
+ response.setStatus(accessDeniedError.getStatusCode());
+ response.getWriter().flush();
+ response.getWriter().close();
+ }
+} | Java | ๊ทธ๋์ ์๊ฐํด๋ธ ๊ฒ์ด `AccessDeniedException`์ ๋ฐ๋ ์๋ฌํด๋์ค๋ฅผ ๋ง๋ค๊ณ ํด๋น ์๋ฌ๋ฅผ ์์๋ฐ์ ์ฌ๊ธฐ์ ์๋ฌ๊ฐ ๋ฐ์ํ๋ฉด ํด๋น ํด๋์ค๋ฅผ ํธ์ถํ๋ ๋ฐฉ์์ ์ฌ์ฉํ์ฌ ๋ค๋ฅธ exceptionHandler์ฒ๋ผ ํ๋ฒ์ ๊ด๋ฆฌํ๊ธฐ๋ ํธํ๊ณ ๋ก๊ทธ๋ ์ฐํ ์ ์๋ค๊ณ ์๊ฐํ์ต๋๋ค.
```java
@Component("restAuthenticationEntryPoint")
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Autowired
private HandlerExceptionResolver resolver;
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
resolver.resolveException(request, response, null, exception);
}
}
``` |
@@ -0,0 +1,14 @@
+package com.requestrealpiano.songrequest.security.oauth;
+
+import org.springframework.security.core.annotation.AuthenticationPrincipal;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Target(ElementType.PARAMETER)
+@Retention(RetentionPolicy.RUNTIME)
+@AuthenticationPrincipal
+public @interface LoginAccount {
+} | Java | ์ด๊ฒ๋ง ๋ฌ์๋ GlobalAdvice ์ค์ ์ ํ ํ์๊ฐ ์์ด์ ์ข์ฃ ! |
@@ -0,0 +1,24 @@
+package com.requestrealpiano.songrequest.controller;
+
+import com.requestrealpiano.songrequest.service.AccountService;
+import lombok.RequiredArgsConstructor;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.*;
+
+@RequiredArgsConstructor
+@RestController
+@RequestMapping("/api/accounts")
+public class AccountController {
+
+ private final AccountService accountService;
+
+ @GetMapping("/auth")
+ public ResponseEntity<Void> generateToken(@RequestHeader HttpHeaders httpHeaders) {
+ String jwtToken = accountService.generateJwtToken(httpHeaders.getFirst(HttpHeaders.AUTHORIZATION));
+ HttpHeaders responseHeaders = new HttpHeaders();
+ responseHeaders.add(HttpHeaders.AUTHORIZATION, jwtToken);
+ return new ResponseEntity<>(responseHeaders, HttpStatus.NO_CONTENT);
+ }
+} | Java | ๋ถ๋ช
๋ชจ๋ ์ปจํธ๋กค๋ฌ๋ฅผ ๋์์ ์์ ์ ํ์ํ
๋ฐ ์ฌ๊ธฐ๋ ์ํ์ฝ๋๋ง ๋ฐ๊พธ๊ณ ํ์์ ์ด๋ ๊ฒ ๋จ๊ฒจ ๋์์๋ค์.
ํต์ผ์ฑ์ ์ํด ์์ ํ๊ฒ ์ต๋๋คใ
ใ
|
@@ -2,18 +2,18 @@
import com.requestrealpiano.songrequest.domain.song.searchapi.response.SearchApiResponse;
import com.requestrealpiano.songrequest.global.response.ApiResponse;
+import com.requestrealpiano.songrequest.global.response.StatusCode;
import com.requestrealpiano.songrequest.service.SongService;
import lombok.RequiredArgsConstructor;
+import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.bind.annotation.*;
import javax.validation.constraints.Size;
import static com.requestrealpiano.songrequest.global.constant.ValidationCondition.*;
-import static com.requestrealpiano.songrequest.global.response.ApiResponse.OK;
+import static com.requestrealpiano.songrequest.global.response.ApiResponse.SUCCESS;
+import static com.requestrealpiano.songrequest.global.response.StatusCode.OK;
@RequiredArgsConstructor
@Validated
@@ -23,12 +23,13 @@ public class SongController {
private final SongService songService;
+ @ResponseStatus(HttpStatus.OK)
@GetMapping
public ApiResponse<SearchApiResponse> search(@RequestParam(defaultValue = "artist") @Size(max = ARTIST_MAX)
String artist,
@RequestParam(defaultValue = "title") @Size(max = TITLE_MAX)
String title) {
SearchApiResponse searchApiResponse = songService.searchSong(artist, title);
- return OK(searchApiResponse);
+ return SUCCESS(OK, searchApiResponse);
}
} | Java | ์ง๋๋ฒ ๋ฆฌ๋ทฐ์ ๊ฐ์ ์๊ฒฌ์ ์ฃผ์
์ ๋ณ๊ฒฝ์ ๊ณ ๋ ค ํด๋ดค์๋๋ฐ์.
์ฌ๊ธฐ ์ด ๋ ๊ฐ์ ๋น ๊ฐ์ผ๋ก ์์ฒญ์ด ์์ ๋ `NotEmpty` ์ ๊ฐ์ ์ฒ๋ฆฌ๋ก ์๋ฌ๋ฅผ ๋ฐํํ ๊ฒ ์๋๋ผ default value๋ก ๊ฒ์์ ๊ณ์ ์งํ ์ํฌ ์๊ฐ ์
๋๋ค. ๋ง์ฝ `@ModelAttribute` DTO๋ก ๋ฐ์ ๊ฒฝ์ฐ์๋ setter๋ก ๊ฐ์ ๋ฐ์ธ๋ฉ ํด์ผ ํ๋ ๊ฒ์ผ๋ก ์๊ณ ์๋๋ฐ์.
๊ทธ๋ ๋ค๋ฉด setter์์ ๋น ๊ฐ์ผ ๊ฒฝ์ฐ ๊ธฐ๋ณธ ๊ฐ์ ์ฃผ๋ ๋ก์ง์ด ํ์ํ ๋ฏ ๋ณด์ด๋๋ฐ,
๊ฐ๋ฅํ๋ค๋ฉด `@RequestParam` ์ฒ๋ผ `@Something(defaultValue = "Default value")` ์ด๋ฐ์์ผ๋ก ์ ๋
ธํ
์ด์
๊ธฐ๋ฐ์ผ๋ก ์์ ํ๊ณ ์ถ์๋ฐ ์๋ ์คํ์ ์๋๊ฑด์ง ์ ๊ฐ ๋ชป ์ฐพ๋๊ฑด์ง...ใ
ใ
setter์์ ์ง์ ์ฒ๋ฆฌํ๋ ๊ฒ ๋ง๊ณ ํน์ ์๊ณ ๊ณ์๋ ๋ ์ข์ ๋ฐฉ๋ฒ์ด ์์๊น์? |
@@ -1,5 +1,6 @@
package com.requestrealpiano.songrequest.domain.account;
+import com.requestrealpiano.songrequest.security.oauth.OAuthAttributes;
import com.requestrealpiano.songrequest.domain.base.BaseTimeEntity;
import com.requestrealpiano.songrequest.domain.letter.Letter;
import lombok.AccessLevel;
@@ -8,9 +9,6 @@
import lombok.NoArgsConstructor;
import javax.persistence.*;
-import java.time.LocalDate;
-import java.time.LocalDateTime;
-import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
@@ -25,7 +23,7 @@ public class Account extends BaseTimeEntity {
private Long id;
@Column(name = "google_oauth_id")
- private Long googleOauthId;
+ private String googleOauthId;
private String name;
@@ -44,12 +42,36 @@ public class Account extends BaseTimeEntity {
private List<Letter> letters = new ArrayList<>();
@Builder
- private Account(Long googleOauthId, String name, String email, Role role, String avatarUrl, Integer requestCount) {
+ private Account(String googleOauthId, String name, String email, Role role, String avatarUrl, Integer requestCount) {
this.googleOauthId = googleOauthId;
this.name = name;
this.email = email;
this.role = role;
this.avatarUrl = avatarUrl;
this.requestCount = requestCount;
}
+
+ public String getRoleKey() { return role.getKey(); }
+
+ public String getRoleValue() {
+ return role.getValue();
+ }
+
+ public Account updateProfile(OAuthAttributes attributes) {
+ this.name = attributes.getName();
+ this.email = attributes.getEmail();
+ this.avatarUrl = attributes.getAvatarUrl();
+ return this;
+ }
+
+ public static Account from(OAuthAttributes oAuthAttributes) {
+ return Account.builder()
+ .googleOauthId(oAuthAttributes.getGoogleOauthId())
+ .name(oAuthAttributes.getName())
+ .email(oAuthAttributes.getEmail())
+ .role(Role.MEMBER)
+ .avatarUrl(oAuthAttributes.getAvatarUrl())
+ .requestCount(0)
+ .build();
+ }
} | Java | ๊ณ์ ์ ์ต์ด ์์ฑ ํ์ ๋์ ๊ธฐ๋ณธ ๊ฐ (์ ์ฒญ๊ณก ๋ฑ๋ก ์) ์
๋๋ค. ์ด์ ๋ฆฌ๋ทฐ์์ ์ด๋ ๊ฒ ์ง๊ด์ ์ผ๋ก ์ดํดํ ์ ์๋ ์ด๋ฐ ๊ฐ์ ๋ณ์๋ก ๋นผ์ง ์์๋ ๋ ๊ฑฐ ๊ฐ๋ค๋ ํผ๋๋ฐฑ์ ๋ฐ์์๋๋ฐ, ๊ทธ๊ฑธ ๋ฐ์ํด์ ์ฝ๋ ์์ฑ์ ํ๋ ๋ฏ ์ถ์ต๋๋ค.
์ฐ์ ์ด ์ฝ๋๋ ์ปฌ๋ผ์ ๊ธฐ๋ณธ ๊ฐ์ ์ถ๊ฐ ํ ์์ ์ด๊ธฐ ๋๋ฌธ์ ์์ด์ง ์ฝ๋๊ฐ ๋ ๋ฏ ํฉ๋๋ค.
๊ทธ๋ฐ๋ฐ ํน์ ์จ๋๋ ๋งค์ง๋๋ฒ๋ฅผ ์ง์ ํ๋ ๊ฒ์ ๋ํ ์ด๋ค ๊ธฐ์ค์ด ์์ผ์ค๊น์?
์์ ์ ํ ํ๋ก์ ํธ ํ ๋๋ ๋งค์ง ๋๋ฒ ์ฌ์ฉ์ ๋ฌด์กฐ๊ฑด ํผํ๋ ค๊ณ ๋ชจ๋ ๋ณ์๋ก ์ง์ ํ๋ค๊ฐ ์คํ๋ ค ์๋ฏธ ํด์์ด ์ด๋ ค์์ก๋ค๋ ํผ๋๋ฐฑ์ ๋ฆฌ๋ทฐ์ด ๋ถ๊ป ๋ฐ์์ ์ด ์์์ต๋๋ค. ์ด๋ฐ ๊ฒฝ์ฐ์๋ ๊ทธ๋ฅ ์ซ์ ๊ฐ์ ์ฌ์ฉํ๊ณ ์ฃผ์์ผ๋ก ๋ถ๊ฐ ์ค๋ช
์ ์ ๋ ๊ฒ๋ ๊ด์ฐฎ๋ค๊ณ ํ์๋๋ผ๊ตฌ์.
์จ๋๋ ์ด๋ค ๊ธฐ์ค์ ๊ฐ์ง๊ณ ๊ณ์๋์ง ๊ถ๊ธํฉ๋๋ค. |
@@ -1,5 +1,6 @@
package com.requestrealpiano.songrequest.domain.account;
+import com.requestrealpiano.songrequest.security.oauth.OAuthAttributes;
import com.requestrealpiano.songrequest.domain.base.BaseTimeEntity;
import com.requestrealpiano.songrequest.domain.letter.Letter;
import lombok.AccessLevel;
@@ -8,9 +9,6 @@
import lombok.NoArgsConstructor;
import javax.persistence.*;
-import java.time.LocalDate;
-import java.time.LocalDateTime;
-import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
@@ -25,7 +23,7 @@ public class Account extends BaseTimeEntity {
private Long id;
@Column(name = "google_oauth_id")
- private Long googleOauthId;
+ private String googleOauthId;
private String name;
@@ -44,12 +42,36 @@ public class Account extends BaseTimeEntity {
private List<Letter> letters = new ArrayList<>();
@Builder
- private Account(Long googleOauthId, String name, String email, Role role, String avatarUrl, Integer requestCount) {
+ private Account(String googleOauthId, String name, String email, Role role, String avatarUrl, Integer requestCount) {
this.googleOauthId = googleOauthId;
this.name = name;
this.email = email;
this.role = role;
this.avatarUrl = avatarUrl;
this.requestCount = requestCount;
}
+
+ public String getRoleKey() { return role.getKey(); }
+
+ public String getRoleValue() {
+ return role.getValue();
+ }
+
+ public Account updateProfile(OAuthAttributes attributes) {
+ this.name = attributes.getName();
+ this.email = attributes.getEmail();
+ this.avatarUrl = attributes.getAvatarUrl();
+ return this;
+ }
+
+ public static Account from(OAuthAttributes oAuthAttributes) {
+ return Account.builder()
+ .googleOauthId(oAuthAttributes.getGoogleOauthId())
+ .name(oAuthAttributes.getName())
+ .email(oAuthAttributes.getEmail())
+ .role(Role.MEMBER)
+ .avatarUrl(oAuthAttributes.getAvatarUrl())
+ .requestCount(0)
+ .build();
+ }
} | Java | ์ ๋ ๋ถ๊ฐ์ ์ค๋ช
์ผ๋ก ์ฃผ์๋ฃ๋๊ฒ๋ ๊ด์ฐฎ๋ค๊ณ ์๊ฐํด์ ๊ทธ๋ฌ๋ ๋ง์ฝ ํ
์คํธ ์ฝ๋์์ ์ฌ๋ฌ๋ฒ ์ค๋ณต๋์๋๋ ๋ฐ๋ก ๊ด๋ฆฌํ๋๊ฒ ๋ซ๊ฒ ๋ค์ |
@@ -11,6 +11,12 @@ public enum ErrorCode {
METHOD_NOT_ALLOWED(405, "์ง์ํ์ง ์๋ ์์ฒญ ๋ฉ์๋ ์
๋๋ค."),
INTERNAL_SERVER_ERROR(500, "์๋ฒ์์ ์์ฒญ์ ์ฒ๋ฆฌํ์ง ๋ชปํ์ต๋๋ค."),
+ // Auth
+ UNAUTHENTICATED_ERROR(401, "์ธ์ฆ์ด ํ์ํฉ๋๋ค. ๋ก๊ทธ์ธ ์ดํ ๋ค์ ์๋ ํด์ฃผ์ธ์."),
+ JWT_INVALID_ERROR(400, "์ฌ๋ฐ๋ฅธ ์ธ์ฆ ์ ๋ณด๊ฐ ์๋๋๋ค. ๋ค์ ๋ก๊ทธ์ธ ํด์ฃผ์ธ์."),
+ JWT_EXPIRATION_ERROR(401, "์ธ์ฆ ์ ๋ณด๊ฐ ๋ง๋ฃ ๋์์ต๋๋ค. ๋ค์ ๋ก๊ทธ์ธ ํด์ฃผ์ธ์."),
+ ACCESS_DENIED_ERROR(403, "ํด๋น ์์ฒญ์ ๋ํ ์ ๊ทผ ๊ถํ์ด ์์ต๋๋ค."),
+
// Account
ACCOUNT_NOT_FOUND(404, "ํด๋น ๊ณ์ ์ด ์กด์ฌํ์ง ์์ต๋๋ค."),
| Java | JWT ๊ด๋ จ ์์ธ๋ฅผ ๊ตฌ์ํ ๋ ์๋์ ๋ค๊ฐ์ง ์์ธ๊ฐ ๋งจ ์ฒ์ ๊ณ ๋ คํ๋ JWT ๊ด๋ จ ์์ธ์์ต๋๋ค.
1. ExpiredJwtException : ์ ํจ๊ธฐ๊ฐ์ด ์ง๋ Token์ผ๋ก ์์ฒญ
2. InvalidClaimException : Claim ํ์ฑ ์คํจ๋ก ์ธํ ์์ธ
3. MalformedJwtException : ๊ตฌ์กฐ์ ๋ฌธ์ ๊ฐ ์๋ JWT ํ ํฐ์ผ๋ก ์ธํ ์์ธ
4. SignatureException : ์ฌ๋ฐ๋ฅด์ง ์์ JWT ์๊ทธ๋์ฒ๋ก ์ธํ ๊ฒ์ฆ ์คํจ
์ด ๋ 1๋ฒ '์ ํจ๊ธฐ๊ฐ ๋ง๋ฃ' ์ 2, 3, 4์ ํด๋นํ๋ 'JWT ๊ฒ์ฆ ์คํจ'
๋๊ฐ์ง ์ ํ์ผ๋ก๋ง ๋๋์ด์ ์ฒ๋ฆฌ๋ฅผ ํ ๋ค ํด๋ผ์ด์ธํธ์ ์๋ ค์ฃผ๋ฉด ๋ ๊ฑฐ๋ผ ์๊ฐํ๊ณ ๋ค์์ ๋๊ฐ์ง๋ก ์ฒ๋ฆฌ ํ๋๋ก ๊ตฌํํ์์ต๋๋ค.
`JWT_INVALID_ERROR(400, "์ฌ๋ฐ๋ฅธ ์ธ์ฆ ์ ๋ณด๊ฐ ์๋๋๋ค. ๋ค์ ๋ก๊ทธ์ธ ํด์ฃผ์ธ์.") - JwtException`
`JWT_EXPIRATION_ERROR(401, "์ธ์ฆ ์ ๋ณด๊ฐ ๋ง๋ฃ ๋์์ต๋๋ค. ๋ค์ ๋ก๊ทธ์ธ ํด์ฃผ์ธ์.") - ExpiredJwtException`
๋ง์ํ์ `JWT๊ฐ ์๋ Token ์ฌ์ฉ์ผ๋ก ์ธํ ์๋ฌ`์ `JWT ์ด์ง๋ง ์ฌ๋ฐ๋ฅด์ง ์์ JWT๋ฅผ ์ฌ์ฉ` ๋ ๊ฐ์ง ๊ฒฝ์ฐ๋ฅผ ๊ตฌ๋ถ ํ ๋ ์ด๋ค ๋ถ๋ถ์์ ์ฅ์ ์ด ์๋ ๊ฒ์ธ์ง ๊ถ๊ธํฉ๋๋คใ
ใ
๋ฌผ๋ก ์ด๋ฐ ์ธ์ฆ๊ณผ ๋ณด์์ ๋ํ ๊ฒ์ ์ต๋ํ ๊ฒฌ๊ณ ํ๊ฒ ํ๋ ๊ฒ์ด ์ข๋ค๋ ์๊ฐ์ ๊ฐ์ง๊ณ ์๋๋ฐ์.
ํน์ ์ด ๋์ ๊ตฌ๋ถํ์ง ์์์ ๋ ์ด๋ค ํฐ ๋ฌธ์ ๊ฐ ์๊ธธ ์ฌ์ง๊ฐ ์์๊น์?
์ ๊ฐ ๋ชจ๋ฅด๊ณ ์ง๋์น๊ณ ์๋ ๊ฒ์ด ์๋์ง์ ๋ํ ์ฐ๋ ค์ ์จ๋์ ์๊ฒฌ์ด ๊ถ๊ธํด์ ์ฌ์ญ์ด ๋ด
๋๋ค! |
@@ -0,0 +1,63 @@
+language: java
+jdk:
+ - openjdk11
+
+branches:
+ only:
+ - main
+
+cache:
+ directories:
+ - '$HOME/.m2/repository'
+ - '$HOME/.gradle'
+
+script: "./gradlew clean build"
+
+before_deploy:
+ - mkdir -p before-deploy
+ - cp scripts/*.sh before-deploy/
+ - cp appspec.yml before-deploy/
+ - cp build/libs/*.jar before-deploy
+ - cd before-deploy && zip -r before-deploy *
+ - cd ../ && mkdir -p deploy
+ - mv before-deploy/before-deploy.zip deploy/songrequest-backend.zip
+
+deploy:
+ - provider: s3
+ access_key_id: $AWS_ACCESS_KEY
+ secret_access_key: $AWS_SECRET_KEY
+
+ bucket: songrequest-backend-build
+ region: ap-northeast-2
+
+ skip_cleanup: true
+ acl: private
+ local_dir: deploy
+
+ wait-until-deployed: true
+
+ on:
+ all_branches: true
+
+ - provider: codedeploy
+ access_key_id: $AWS_ACCESS_KEY
+ secret_access_key: $AWS_SECRET_KEY
+
+ bucket: songrequest-backend-build
+ key: songrequest-backend.zip
+
+ bundle_type: zip
+ application: songrequest-backend
+
+ deployment_group: songrequest-backend-group
+
+ region: ap-northeast-2
+ wait-until-deployed: true
+
+ on:
+ all_branches: true
+
+notifications:
+ email:
+ recipients:
+ - museopkim0214@gmail.com | Unknown | travis CI ์ด๊ตฐ์. ์ ๋ ์จ๋ดค์ง๋ง Github Actions๋ณด๋ค ๋๋ฆฌ๊ณ ๋๋ฒ๊น
ํ๋๋ฐ ๋ถํธํด์ ์ ์ฐ๋ค๊ฐ ๋ฐ๊ฟจ์ต๋๋ค.
ํ์ฌ๋ Github Actions + AWS CodeBuild๋ฅผ ๋ณํฉํด์ ์ฌ์ฉํ๊ณ ์๋๋ฐ CIํด ์ค travis ci๋ฅผ ์ฌ์ฉํ์ ์ด์ ๊ฐ ๊ถ๊ธํฉ๋๋ค. |
@@ -0,0 +1,18 @@
+version: 0.0
+os: linux
+files:
+ - source: /
+ destination: /home/ubuntu/app/songrequest/zip/
+ overwrite: yes
+
+permissions:
+ - object: /
+ pattern: "**"
+ owner: ubuntu
+ group: ubuntu
+
+hooks:
+ ApplicationStart:
+ - location: deploy.sh
+ timeout: 60
+ runas: ubuntu | Unknown | ์ฌ๊ธฐ์ ์์
์ผํ ๊ฑด ๋ง์ฝ blue/green ๋ฐฐํฌ๋ฅผ ํ์ค ๊ฒฝ์ฐ overwrite๊ฐ ๋จน์ง ์์ต๋๋ค. ๊ทธ๋์ beforeInstall ์์คํฌ๋ฆฝํธ๋ฅผ ์์ฑํ์
์ ํ์ผ ์ญ์ ํ๋ ์คํฌ๋ฆฝํธ๋ฅผ ์ง์
์ผํฉ๋๋ค. ์ด ๋ด์ฉ์ ์ธ์ ๊ฐ ์ ๋ธ๋ก๊ทธ์ ์ ์ ์์ ์ด๋ ๊ถ๊ธํ์๋ฉด ๋ณด์ธ์ฉ |
@@ -0,0 +1,18 @@
+version: 0.0
+os: linux
+files:
+ - source: /
+ destination: /home/ubuntu/app/songrequest/zip/
+ overwrite: yes
+
+permissions:
+ - object: /
+ pattern: "**"
+ owner: ubuntu
+ group: ubuntu
+
+hooks:
+ ApplicationStart:
+ - location: deploy.sh
+ timeout: 60
+ runas: ubuntu | Unknown | ๋ง์ฝ ๋ณธ์ธ์ด blue/green ๋ฌด์ค๋จ ๋ฐฐํฌ๋ฅผ ํ์ค๊ฒฝ์ฐ ์ฌ๊ธฐ์ BeforeInstall ์์คํฌ๋ฆฝํธ ๋ฃ์ผ์
์ ์ด์ ๋น๋๋ํ์ผ ์ญ์ ํ์๋ ์์คํฌ๋ฆฝํธ๋ฅผ ๋ฃ์ด์ผ ์ ์์ ์ผ๋ก ์๋๋๋ ๊ผญ ๊ธฐ์ตํ์ธ์ |
@@ -23,13 +23,33 @@ ext {
set('snippetsDir', file("build/generated-snippets"))
}
+bootJar {
+ dependsOn asciidoctor
+ from("${asciidoctor.outputDir}/html5") {
+ into 'static/docs'
+ }
+}
+
+test {
+ outputs.dir snippetsDir
+ useJUnitPlatform()
+}
+
+asciidoctor {
+ inputs.dir snippetsDir
+ dependsOn test
+ attributes 'snippets': snippetsDir
+}
+
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-web'
- compile 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.11.1'
- compile 'org.apache.commons:commons-lang3:3.11'
+ implementation 'javax.validation:validation-api:2.0.1.Final'
+ implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.11.1'
+ implementation 'org.hibernate.validator:hibernate-validator:6.1.7.Final'
+ implementation 'org.apache.commons:commons-lang3:3.11'
compileOnly 'org.projectlombok:lombok'
runtimeOnly 'com.h2database:h2'
runtimeOnly 'mysql:mysql-connector-java' | Unknown | ์ด๊ฒ๋ ์ข์ง๋ง DTO <-> Entity์ญํ ์ ํ๋ ๊ธฐ์กด์ modelmapper๋ ์ข์ง๋ง Mapstruct๋ ํจ์ฌ ์ฑ๋ฅ๋ ์ข์ต๋๋ค. ์ค๋ฌด์์๋ ์ฌ์ฉํ๋ ์ค์
๋๋ค.
https://huisam.tistory.com/entry/mapStruct |
@@ -0,0 +1,38 @@
+#!/bin/bash
+
+REPOSITORY=/home/ubuntu/app/songrequest
+PROJECT_NAME=song-request
+
+echo "> Build ํ์ผ ๋ณต์ฌ"
+
+cp $REPOSITORY/zip/*.jar $REPOSITORY/
+
+echo "> ํ์ฌ ๊ตฌ๋ ์ค์ธ ์ ํ๋ฆฌ์ผ์ด์
pid ํ์ธ"
+
+CURRENT_PID=$(pgrep -fl song-request | grep jar | awk '{print $1}')
+
+echo "ํ์ฌ ๊ตฌ๋ ์ค์ธ ์ ํ๋ฆฌ์ผ์ด์
pid : $CURRENT_PID"
+
+if [ -z "$CURRENT_PID" ]; then
+ echo "> ํ์ฌ ๊ตฌ๋ ์ค์ธ ์ ํ๋ฆฌ์ผ์ด์
์ด ์์ผ๋ฏ๋ก ์ข
๋ฃํ์ง ์์ต๋๋ค."
+else
+ echo "> kill -15 $CURRENT_PID"
+ kill -15 $CURRENT_PID
+ sleep 5
+fi
+
+echo "> ์ ์ ํ๋ฆฌ์ผ์ด์
๋ฐฐํฌ"
+
+JAR_NAME=$(ls -tr $REPOSITORY/*.jar | tail -n 1)
+
+echo "> JAR Name : $JAR_NAME"
+
+echo "> $JAR_NAME์ ์คํ ๊ถํ ์ถ๊ฐ"
+
+chmod +x $JAR_NAME
+
+echo "> $JAR_NAME ์คํ"
+
+nohup java -jar \
+ -Dspring.profiles.active=prod \
+ $JAR_NAME > $REPOSITORY/nohup.out 2>&1 & | Unknown | home์ ๊ทธ๋๋ก ๋ฐฐํฌํ๋ ๊ฒ๋ณด๋ค ํด๋๋ฅผ ์์ฑํด์ ๊ด๋ฆฌํ๋ ๊ฒ ์ข์ต๋๋ค. ์ ์ ์ฉํ์
จ๋ค์ |
@@ -9,14 +9,16 @@
import javax.annotation.PostConstruct;
import java.util.TimeZone;
+import static com.requestrealpiano.songrequest.global.constant.JpaProperties.ASIA_SEOUL;
+
@EnableConfigurationProperties(value = {ManiaDbProperties.class, LastFmProperties.class})
@SpringBootApplication
public class SongRequestApplication {
@PostConstruct
public void setTimeZone() {
- String SEOUL = "Asia/Seoul";
- TimeZone.setDefault(TimeZone.getTimeZone(SEOUL));
+ TimeZone KST = TimeZone.getTimeZone(ASIA_SEOUL);
+ TimeZone.setDefault(KST);
}
public static void main(String[] args) { | Java | ```suggestion
Timezone.setDefault(TimeZone.getTimeZone(ASIA_SEOUL));
```
์ผ๋ก ๋ฐ๊พธ๋ฉด ์ด๋ป๊ฒ ๋๋์? |
@@ -1,27 +1,33 @@
package com.requestrealpiano.songrequest.controller;
-import com.fasterxml.jackson.core.JsonProcessingException;
import com.requestrealpiano.songrequest.domain.song.searchapi.response.SearchApiResponse;
import com.requestrealpiano.songrequest.global.response.ApiResponse;
import com.requestrealpiano.songrequest.service.SongService;
import lombok.RequiredArgsConstructor;
+import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
+import javax.validation.constraints.Size;
+
+import static com.requestrealpiano.songrequest.global.constant.ValidationCondition.*;
import static com.requestrealpiano.songrequest.global.response.ApiResponse.OK;
@RequiredArgsConstructor
+@Validated
@RestController
-@RequestMapping("/songs")
+@RequestMapping("/api/songs")
public class SongController {
private final SongService songService;
@GetMapping
- public ApiResponse<SearchApiResponse> search(@RequestParam String artist,
- @RequestParam String title) throws JsonProcessingException {
+ public ApiResponse<SearchApiResponse> search(@RequestParam(defaultValue = "artist") @Size(max = ARTIST_MAX)
+ String artist,
+ @RequestParam(defaultValue = "title") @Size(max = TITLE_MAX)
+ String title) {
SearchApiResponse searchApiResponse = songService.searchSong(artist, title);
return OK(searchApiResponse);
} | Java | RequestParam๋ ์ข์ง๋ง artist, title๋ ํ๋ฒ์ ๊ด๋ฆฌํ๋ DTO๋ฅผ ๋ง๋ค๋ฉด ์ด๋ค๊ฐ์? ์์ฃผ ์ฐ์ผ์ง ๋ชจ๋ฅด๋ DTO๋ฅผ ๋ง๋ค๊ณ ๊ฑฐ๊ธฐ์ Validation์ฒ๋ฆฌํด๋ ๊ด์ฐฎ์ ๋ณด์
๋๋ค. |
@@ -0,0 +1,32 @@
+package com.requestrealpiano.songrequest.domain.letter.request.inner;
+
+import lombok.AccessLevel;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+
+import javax.validation.constraints.NotEmpty;
+import javax.validation.constraints.Size;
+
+import static com.requestrealpiano.songrequest.global.constant.ValidationCondition.*;
+
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+@Getter
+public class SongRequest {
+
+ @NotEmpty(message = NOT_EMPTY_MESSAGE)
+ @Size(min = TITLE_MIN, max = TITLE_MAX, message = TITLE_MESSAGE)
+ private String title;
+
+ @NotEmpty(message = NOT_EMPTY_MESSAGE)
+ @Size(min = ARTIST_MIN, max = ARTIST_MAX, message = ARTIST_MESSAGE)
+ private String artist;
+
+ @Size(max = IMAGE_MAX, message = IMAGE_MESSAGE)
+ private String imageUrl;
+
+ SongRequest(String title, String artist, String imageUrl) {
+ this.title = title;
+ this.artist = artist;
+ this.imageUrl = imageUrl;
+ }
+} | Java | validation ๊ด์ฐฎ๋ค์ |
@@ -0,0 +1,25 @@
+package com.requestrealpiano.songrequest.global.constant;
+
+public interface ValidationCondition {
+
+ // Common
+ String NOT_EMPTY_MESSAGE = "ํ์ ์
๋ ฅ ์ ๋ณด ์
๋๋ค.";
+
+ // Artist
+ String ARTIST_MESSAGE = "์ํฐ์คํธ๋ 30์ ๋ฏธ๋ง ์
๋๋ค.";
+ int ARTIST_MAX = 30;
+ int ARTIST_MIN = 1;
+
+ // Title
+ String TITLE_MESSAGE = "์ ๋ชฉ์ 30์ ๋ฏธ๋ง ์
๋๋ค.";
+ int TITLE_MAX = 30;
+ int TITLE_MIN = 1;
+
+ // Image URL
+ String IMAGE_MESSAGE = "์ ํจํ ์ด๋ฏธ์ง ์ ๋ณด๊ฐ ์๋๋๋ค.";
+ int IMAGE_MAX = 100;
+
+ // Song Story
+ String SONG_STORY_MESSAGE = "์ฌ์ฐ์ 500์ ๋ฏธ๋ง์ด์ด์ผ ํฉ๋๋ค.";
+ int SONG_STORY_MAX = 500;
+} | Java | interface์ ๊ทธ๋๋ก value๊ฐ์ ์ง์ ํ๋ฉด ์ข์ง์์ต๋๋ค. ์ดํํฐ๋ธ ์๋ฐ์์ ๋ณธ ๊ฑฐ๊ฐ์๋ฐ ๋ด์ฉ์ด ์ ํํ๊ฒ ๊ธฐ์ต์ ์๋์ง๋ง ์ด๋ ๊ฒ ํ์ง๋ง๋ผ๊ณ ๊ฐํ๊ฒ ๊ฒฝ๊ณ ํ๋ ๊ธฐ์ต์ด ๋๋ค์.
๊ทธ๋ฆฌ๊ณ ๋ด์ฉ์ interface๋ณด๋จ enum์ ์ด์ธ๋ฆฌ๋๋ฐ enum์ ์ด๋ค๊ฐ์? |
@@ -0,0 +1,64 @@
+package com.requestrealpiano.songrequest.global.error;
+
+import com.requestrealpiano.songrequest.global.error.exception.BusinessException;
+import com.requestrealpiano.songrequest.global.error.exception.ParsingFailedException;
+import com.requestrealpiano.songrequest.global.error.response.ErrorCode;
+import com.requestrealpiano.songrequest.global.error.response.ErrorResponse;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.HttpRequestMethodNotSupportedException;
+import org.springframework.web.bind.MethodArgumentNotValidException;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.RestControllerAdvice;
+
+import javax.validation.ConstraintViolationException;
+
+@Slf4j
+@RestControllerAdvice
+public class GlobalExceptionHandler {
+
+ @ExceptionHandler(ConstraintViolationException.class)
+ protected ResponseEntity<ErrorResponse> handleConstraintViolationException(ConstraintViolationException exception) {
+ log.error("handleConstraintViolationException", exception);
+ ErrorResponse errorResponse = ErrorResponse.from(ErrorCode.INVALID_INPUT_VALUE);
+ return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
+ }
+
+ @ExceptionHandler(MethodArgumentNotValidException.class)
+ protected ResponseEntity<ErrorResponse> handleMethodArgumentNotValidException(MethodArgumentNotValidException exception){
+ log.error("handleMethodArgumentNotValidException", exception);
+ ErrorResponse errorResponse = ErrorResponse.of(ErrorCode.INVALID_INPUT_VALUE, exception.getBindingResult());
+ return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
+ }
+
+ @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
+ protected ResponseEntity<ErrorResponse> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException exception) {
+ log.error("handleHttpRequestMethodNotSupportedException", exception);
+ ErrorResponse errorResponse = ErrorResponse.from(ErrorCode.METHOD_NOT_ALLOWED);
+ return new ResponseEntity<>(errorResponse, HttpStatus.METHOD_NOT_ALLOWED);
+ }
+
+ @ExceptionHandler(ParsingFailedException.class)
+ protected ResponseEntity<ErrorResponse> handleParsingFailedException(ParsingFailedException exception) {
+ log.error("handleJsonProcessingException", exception);
+ ErrorCode errorCode = exception.getErrorCode();
+ ErrorResponse errorResponse = ErrorResponse.from(errorCode);
+ return new ResponseEntity<>(errorResponse, HttpStatus.valueOf(errorResponse.getStatusCode()));
+ }
+
+ @ExceptionHandler(BusinessException.class)
+ protected ResponseEntity<ErrorResponse> handleBusinessException(BusinessException exception) {
+ log.error("handleBusinessException", exception);
+ ErrorCode errorCode = exception.getErrorCode();
+ ErrorResponse errorResponse = ErrorResponse.from(errorCode);
+ return new ResponseEntity<>(errorResponse, HttpStatus.valueOf(errorCode.getStatusCode()));
+ }
+
+ @ExceptionHandler(Exception.class)
+ protected ResponseEntity<ErrorResponse> handleException(Exception exception) {
+ log.error("handleException", exception);
+ ErrorResponse errorResponse = ErrorResponse.from(ErrorCode.INTERNAL_SERVER_ERROR);
+ return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
+ }
+} | Java | ์ด ์ฝ๋๊ฐ validation ์์ธ์ฒ๋ฆฌ๋ก ์๊ณ ์์ต๋๋ค. ์๋์ด ์๋๋์? ํ๋ฒ ํ
์คํธ์ฝ๋์์ ํ์ธํด๋ณด๊ฒ ์ต๋๋ค. |
@@ -0,0 +1,38 @@
+#!/bin/bash
+
+REPOSITORY=/home/ubuntu/app/songrequest
+PROJECT_NAME=song-request
+
+echo "> Build ํ์ผ ๋ณต์ฌ"
+
+cp $REPOSITORY/zip/*.jar $REPOSITORY/
+
+echo "> ํ์ฌ ๊ตฌ๋ ์ค์ธ ์ ํ๋ฆฌ์ผ์ด์
pid ํ์ธ"
+
+CURRENT_PID=$(pgrep -fl song-request | grep jar | awk '{print $1}')
+
+echo "ํ์ฌ ๊ตฌ๋ ์ค์ธ ์ ํ๋ฆฌ์ผ์ด์
pid : $CURRENT_PID"
+
+if [ -z "$CURRENT_PID" ]; then
+ echo "> ํ์ฌ ๊ตฌ๋ ์ค์ธ ์ ํ๋ฆฌ์ผ์ด์
์ด ์์ผ๋ฏ๋ก ์ข
๋ฃํ์ง ์์ต๋๋ค."
+else
+ echo "> kill -15 $CURRENT_PID"
+ kill -15 $CURRENT_PID
+ sleep 5
+fi
+
+echo "> ์ ์ ํ๋ฆฌ์ผ์ด์
๋ฐฐํฌ"
+
+JAR_NAME=$(ls -tr $REPOSITORY/*.jar | tail -n 1)
+
+echo "> JAR Name : $JAR_NAME"
+
+echo "> $JAR_NAME์ ์คํ ๊ถํ ์ถ๊ฐ"
+
+chmod +x $JAR_NAME
+
+echo "> $JAR_NAME ์คํ"
+
+nohup java -jar \
+ -Dspring.profiles.active=prod \
+ $JAR_NAME > $REPOSITORY/nohup.out 2>&1 & | Unknown | p4 : ์๋ ๋ฐฐํฌ ์คํฌ๋ฆฝํธ ๊ตฐ์ ๐
๊ฐ๋จํ ํ์ด์ง๋ง.. ์ฌ๊ธฐ์ ์ฌ์ฉํ๊ณ ์๋ `tail`, `grep`๋ฑ๋ฑ ์ ๋ํ ๊ธฐ๋ณธ์ ์ธ ์ดํด ์ ๋๋ ์์ผ์๋ฉด ์ข์๋ฏ ํฉ๋๋ค! |
@@ -0,0 +1,25 @@
+package com.requestrealpiano.songrequest.global.constant;
+
+public interface ValidationCondition {
+
+ // Common
+ String NOT_EMPTY_MESSAGE = "ํ์ ์
๋ ฅ ์ ๋ณด ์
๋๋ค.";
+
+ // Artist
+ String ARTIST_MESSAGE = "์ํฐ์คํธ๋ 30์ ๋ฏธ๋ง ์
๋๋ค.";
+ int ARTIST_MAX = 30;
+ int ARTIST_MIN = 1;
+
+ // Title
+ String TITLE_MESSAGE = "์ ๋ชฉ์ 30์ ๋ฏธ๋ง ์
๋๋ค.";
+ int TITLE_MAX = 30;
+ int TITLE_MIN = 1;
+
+ // Image URL
+ String IMAGE_MESSAGE = "์ ํจํ ์ด๋ฏธ์ง ์ ๋ณด๊ฐ ์๋๋๋ค.";
+ int IMAGE_MAX = 100;
+
+ // Song Story
+ String SONG_STORY_MESSAGE = "์ฌ์ฐ์ 500์ ๋ฏธ๋ง์ด์ด์ผ ํฉ๋๋ค.";
+ int SONG_STORY_MAX = 500;
+} | Java | p3: ์ ๋ enum์ด๋ ๋ค๋ฅธ class์ผ๋ก ๊ด๋ฆฌํ์๋ ๊ฒ ์ข๋ค๊ณ ์๊ฐ๋๋ค์! |
@@ -0,0 +1,63 @@
+language: java
+jdk:
+ - openjdk11
+
+branches:
+ only:
+ - main
+
+cache:
+ directories:
+ - '$HOME/.m2/repository'
+ - '$HOME/.gradle'
+
+script: "./gradlew clean build"
+
+before_deploy:
+ - mkdir -p before-deploy
+ - cp scripts/*.sh before-deploy/
+ - cp appspec.yml before-deploy/
+ - cp build/libs/*.jar before-deploy
+ - cd before-deploy && zip -r before-deploy *
+ - cd ../ && mkdir -p deploy
+ - mv before-deploy/before-deploy.zip deploy/songrequest-backend.zip
+
+deploy:
+ - provider: s3
+ access_key_id: $AWS_ACCESS_KEY
+ secret_access_key: $AWS_SECRET_KEY
+
+ bucket: songrequest-backend-build
+ region: ap-northeast-2
+
+ skip_cleanup: true
+ acl: private
+ local_dir: deploy
+
+ wait-until-deployed: true
+
+ on:
+ all_branches: true
+
+ - provider: codedeploy
+ access_key_id: $AWS_ACCESS_KEY
+ secret_access_key: $AWS_SECRET_KEY
+
+ bucket: songrequest-backend-build
+ key: songrequest-backend.zip
+
+ bundle_type: zip
+ application: songrequest-backend
+
+ deployment_group: songrequest-backend-group
+
+ region: ap-northeast-2
+ wait-until-deployed: true
+
+ on:
+ all_branches: true
+
+notifications:
+ email:
+ recipients:
+ - museopkim0214@gmail.com | Unknown | travis CI๋ฅผ ์ฌ์ฉํ ๊ธฐ์ ์ ์ธ ์ด์ ๋ ์์์ต๋๋คใ
ใ
CI / CD๋ฅผ ๋ค์ํ ํด๋ก ๊ฒฝํ ํด๋ณด๊ณ ์ถ์ด์ ๋ฐฑ์๋๋ travis CI, ํ๋ก ํธ๋ Github Actions๋ก ๋ฐฐํฌ ํ๊ฒฝ์ ๊ตฌ์ฑ ํ์ต๋๋ค.
travis CI๋ฅผ ์จ๋ณด๊ณ ๋๋ ๊ฒ์... ๋๋ฒ๊น
๊ณผ์ ์์ ๋ถํธํจ์ ์์๊ณ , ๋ค๋ง ๋ง์ ํ์ ๊ฒ์ฒ๋ผ ์กฐ๊ธ ๋๋ฆฐ ๊ฒ์ด ์ฝ๊ฐ ๋ถํธ ํ์ต๋๋ค.
ํ๋ก ํธ์ ๋น๋ ๊ณผ์ ์ด ๋ค๋ฅด๊ธฐ ๋๋ฌธ์ ์ ๋์ ์ธ ๋น๊ต๋ ๋ถ๊ฐ ํ์ง๋ง ์ ๋ Github Actions๊ฐ ์ฝ๊ฐ ๋ ๋น ๋ฅธ ๋๋์ด์๋ค์. |
@@ -0,0 +1,18 @@
+version: 0.0
+os: linux
+files:
+ - source: /
+ destination: /home/ubuntu/app/songrequest/zip/
+ overwrite: yes
+
+permissions:
+ - object: /
+ pattern: "**"
+ owner: ubuntu
+ group: ubuntu
+
+hooks:
+ ApplicationStart:
+ - location: deploy.sh
+ timeout: 60
+ runas: ubuntu | Unknown | ๋ง์ฝ ๊ฐ์ธ ํ๋ก์ ํธ๋ก blue / green ๋ฐฐํฌ๊น์ง ํ๊ฒ ๋๋ค๋ฉด ๋งค์ฐ ํฐ ์ฑ๊ณผ๊ฒ ๋ค์ใ
ใ
์จ๋ ๋ธ๋ก๊ทธ์ ์ ๋ณด๊ณ ์์ต๋๋ค. ๐ ์ข์ ํ ๊ฐ์ฌํฉ๋๋ค. |
@@ -1,27 +1,33 @@
package com.requestrealpiano.songrequest.controller;
-import com.fasterxml.jackson.core.JsonProcessingException;
import com.requestrealpiano.songrequest.domain.song.searchapi.response.SearchApiResponse;
import com.requestrealpiano.songrequest.global.response.ApiResponse;
import com.requestrealpiano.songrequest.service.SongService;
import lombok.RequiredArgsConstructor;
+import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
+import javax.validation.constraints.Size;
+
+import static com.requestrealpiano.songrequest.global.constant.ValidationCondition.*;
import static com.requestrealpiano.songrequest.global.response.ApiResponse.OK;
@RequiredArgsConstructor
+@Validated
@RestController
-@RequestMapping("/songs")
+@RequestMapping("/api/songs")
public class SongController {
private final SongService songService;
@GetMapping
- public ApiResponse<SearchApiResponse> search(@RequestParam String artist,
- @RequestParam String title) throws JsonProcessingException {
+ public ApiResponse<SearchApiResponse> search(@RequestParam(defaultValue = "artist") @Size(max = ARTIST_MAX)
+ String artist,
+ @RequestParam(defaultValue = "title") @Size(max = TITLE_MAX)
+ String title) {
SearchApiResponse searchApiResponse = songService.searchSong(artist, title);
return OK(searchApiResponse);
} | Java | ์์ง์ ์ฌ๊ธฐ์ ๋ฐ์ ์ฐ์ด์ง ์๋๋ฐ ์ฌ์ฉ ๋๋ ๊ณณ์ด ๋ ๋ง์์ง๋ฉด `@ModelAttribute` ๊ฐ์ฒด๋ก ํ๋ฒ ๊ด๋ฆฌ ํด๋ณผ๊ฒ์! |
@@ -0,0 +1,25 @@
+package com.requestrealpiano.songrequest.global.constant;
+
+public interface ValidationCondition {
+
+ // Common
+ String NOT_EMPTY_MESSAGE = "ํ์ ์
๋ ฅ ์ ๋ณด ์
๋๋ค.";
+
+ // Artist
+ String ARTIST_MESSAGE = "์ํฐ์คํธ๋ 30์ ๋ฏธ๋ง ์
๋๋ค.";
+ int ARTIST_MAX = 30;
+ int ARTIST_MIN = 1;
+
+ // Title
+ String TITLE_MESSAGE = "์ ๋ชฉ์ 30์ ๋ฏธ๋ง ์
๋๋ค.";
+ int TITLE_MAX = 30;
+ int TITLE_MIN = 1;
+
+ // Image URL
+ String IMAGE_MESSAGE = "์ ํจํ ์ด๋ฏธ์ง ์ ๋ณด๊ฐ ์๋๋๋ค.";
+ int IMAGE_MAX = 100;
+
+ // Song Story
+ String SONG_STORY_MESSAGE = "์ฌ์ฐ์ 500์ ๋ฏธ๋ง์ด์ด์ผ ํฉ๋๋ค.";
+ int SONG_STORY_MAX = 500;
+} | Java | ์ธํฐํ์ด์ค๊ฐ static ์์์ ์ถ์ ๋ฉ์๋๋ง ์ ๊ทผ ๊ฐ๋ฅํด์ ์ด๋ ๊ฒ ์ ์ฉ ํด๋ดค์๋๋ฐ, ๋ค์ ๋ณด๋ Enum์ผ๋ก ๊ด๋ฆฌ ํ๋๊ฒ ๋ ์ ํฉ ํ ๊ฑฐ ๊ฐ์ต๋๋ค.
(+) ์ธ๊ธํ์ ์ดํํฐ๋ธ ์๋ฐ์ ๋ด์ฉ์ (3rd edition ๊ธฐ์ค) `Item 22` ์ ์๋ค์! |
@@ -0,0 +1,38 @@
+#!/bin/bash
+
+REPOSITORY=/home/ubuntu/app/songrequest
+PROJECT_NAME=song-request
+
+echo "> Build ํ์ผ ๋ณต์ฌ"
+
+cp $REPOSITORY/zip/*.jar $REPOSITORY/
+
+echo "> ํ์ฌ ๊ตฌ๋ ์ค์ธ ์ ํ๋ฆฌ์ผ์ด์
pid ํ์ธ"
+
+CURRENT_PID=$(pgrep -fl song-request | grep jar | awk '{print $1}')
+
+echo "ํ์ฌ ๊ตฌ๋ ์ค์ธ ์ ํ๋ฆฌ์ผ์ด์
pid : $CURRENT_PID"
+
+if [ -z "$CURRENT_PID" ]; then
+ echo "> ํ์ฌ ๊ตฌ๋ ์ค์ธ ์ ํ๋ฆฌ์ผ์ด์
์ด ์์ผ๋ฏ๋ก ์ข
๋ฃํ์ง ์์ต๋๋ค."
+else
+ echo "> kill -15 $CURRENT_PID"
+ kill -15 $CURRENT_PID
+ sleep 5
+fi
+
+echo "> ์ ์ ํ๋ฆฌ์ผ์ด์
๋ฐฐํฌ"
+
+JAR_NAME=$(ls -tr $REPOSITORY/*.jar | tail -n 1)
+
+echo "> JAR Name : $JAR_NAME"
+
+echo "> $JAR_NAME์ ์คํ ๊ถํ ์ถ๊ฐ"
+
+chmod +x $JAR_NAME
+
+echo "> $JAR_NAME ์คํ"
+
+nohup java -jar \
+ -Dspring.profiles.active=prod \
+ $JAR_NAME > $REPOSITORY/nohup.out 2>&1 & | Unknown | ๋ง์ ํ์ ๊ฒ์ฒ๋ผ EC2์ Nginx๋ฅผ ์ค์ ํ๊ณ ๋ฐฐํฌ ํ๊ฒฝ์ ๊ตฌ์ฑํ๋ ๊ณผ์ ์์ ๋ฆฌ๋
์ค ๋ช
๋ น์ด๊ฐ ๋ง์ด ๋ถ์กฑํ๋ค๋ ๊ฒ์ ๋๊ผ์ต๋๋ค.
๊ทธ๋์ ๋ณ๋๋ก ์กฐ๊ธ์ฉ ๊ณต๋ถ๋ฅผ ํ๊ณ ์์ด์ใ
ใ
์กฐ์ธ ํด์ฃผ์
์ ๊ฐ์ฌํฉ๋๋ค! ๐ |
@@ -0,0 +1,271 @@
+var Domclass = require('../util/Domclass');
+var Eventutil = require('../util/Eventutil');
+var snippet = require('tui-code-snippet');
+
+var KEY_ENTER = 13;
+
+var todoObjects = []; // ๋ชจ๋ todoData
+var completeTodoObjects = []; // isChecked๊ฐ true์ธ ๊ฐ
+var incompleteTodoObjects = []; // isChecked๊ฐ false์ธ ๊ฐ
+
+var todoListWrapElement;
+var completeListElement;
+var incompleteListElement;
+var leftItemNumElement;
+var completeItemsNumElement;
+
+var _initElement = function() {
+ todoListWrapElement = document.getElementById('todoListWrap');
+ completeListElement = document.getElementById('completeList');
+ incompleteListElement = document.getElementById('incompleteList');
+ leftItemNumElement = document.getElementById('leftItemsNum');
+ completeItemsNumElement = document.getElementById('completeItemsNum');
+};
+
+var _forEach = function(arr, func) {
+ var i = 0;
+ var arrLength = arr.length;
+ for (; i < arrLength; i += 1) {
+ func.call(this, i, arr[i]);
+ }
+};
+
+/**
+ * ๊ฐ์ฒด๊ฐ ๋ฑ๋ก๋ ์๊ฐ์ ๊ธฐ์ค์ผ๋ก ๋ด๋ฆผ์ฐจ์์ผ๋ก ์ ๋ ฌ ํ๋ ํจ์
+ * @param {array} arr ๋ ์ ๋ ฌํ๊ณ ์ถ์ ๋ฐฐ์ด
+ */
+function _sortRegDateOfTodoObject(arr) {
+ arr.sort(function(a, b) {
+ if (a.regDate < b.regDate) {
+ return 1;
+ } else if (a.regDate > b.regDate) {
+ return -1;
+ }
+
+ return 0;
+ });
+}
+
+/**
+ * ์ธ์๋ก ๋ฐ์ ๋ฐ์ดํฐ ์ ๋ณด๋ฅผ todoObjects์ ๋ด๊ณ , isChecked = false์ธ๊ฒ์ incompleteTodoObjects,
+ * isChecked = true์ธ๊ฒ์ completeTodoObjects ๋ฐฐ์ด์ ๋ด์ ๋ค ์ค๋ฆ์ฐจ์ ์ ๋ ฌ
+ * @param {array} todoData ๋ todo ๋ฐ์ดํฐ ์ ๋ณด
+ */
+function _loadTodoData(todoData) {
+ todoObjects = todoData;
+
+ completeTodoObjects = snippet.filter(todoObjects, function(value) {
+ return value.isChecked;
+ });
+
+ _sortRegDateOfTodoObject(completeTodoObjects);
+
+ incompleteTodoObjects = snippet.filter(todoObjects, function(value) {
+ return !value.isChecked;
+ });
+
+ _sortRegDateOfTodoObject(incompleteTodoObjects);
+}
+
+/**
+ * completeList๋ฅผ ๋ ๋๋งํด์ฃผ๋ ํจ์
+ */
+function _renderCompleteTodoList() {
+ var htmlLi = '';
+ var todoId, todoTitle;
+
+ _forEach(completeTodoObjects, function(index, value) {
+ todoId = value.id;
+ todoTitle = value.title;
+ htmlLi += '<li class="todo" data-id="' + todoId + '"><input type="checkbox" class="todoChk" checked/><p class="todoTitle">' + todoTitle + '</p></li>';
+ });
+
+ completeListElement.innerHTML = htmlLi;
+}
+
+/**
+ * incompleteList๋ฅผ ๋ ๋๋งํด์ฃผ๋ ํจ์
+ */
+function _renderIncompleteTodoList() {
+ var htmlLi = '';
+ var todoId, todoTitle;
+
+ _forEach(incompleteTodoObjects, function(index, value) {
+ todoId = value.id;
+ todoTitle = value.title;
+ htmlLi += '<li class="todo" data-id="' + todoId + '"><input type="checkbox" class="todoChk"/><p class="todoTitle">' + todoTitle + '</p></li>';
+ });
+
+ incompleteListElement.innerHTML = htmlLi;
+}
+
+/**
+ * _renderCompleteTodoList, _renderIncompleteTodoList ํจ์ ํธ์ถ
+ */
+function _renderTodoList() {
+ _renderCompleteTodoList();
+ _renderIncompleteTodoList();
+}
+
+/**
+ * infoList๋ฅผ ๋ ๋๋ง ํด์ฃผ๋ ํจ์
+ */
+function _renderInfoList() {
+ leftItemNumElement.innerText = incompleteTodoObjects.length;
+ completeItemsNumElement.innerText = completeTodoObjects.length;
+}
+
+/**
+ * _renderTodoList, _renderInfoList ํจ์ ํธ์ถ
+ */
+function _renderView() {
+ _renderTodoList();
+ _renderInfoList();
+}
+
+/**
+ * ํ
์คํธ๋ฐ์ค์์ ๋ฐ์ ๊ฐ์ ๊ฐ์ง๊ณ ์๋ก์ด todo ๊ฐ์ฒด๋ฅผ ๋ง๋ค๊ณ todoObjects์ ๋ฃ์ด ๋๋ค ์ฌ ๋ ๋๋ง
+ * @param {object} target ๋ inputTxt ๊ฐ์ฒด
+ */
+function _addTodoObject(target) {
+ var objTodo = {
+ id: 'todo' + snippet.stamp({}),
+ title: target.value,
+ isChecked: false,
+ regDate: snippet.timestamp()
+ };
+ todoObjects.push(objTodo);
+ target.value = '';
+
+ _loadTodoData(todoObjects);
+ _renderView();
+}
+
+/**
+ * keypress์ด๋ฒคํธ๊ฐ ๋ฐ์ํ๋ฉด ์ด๋ฒคํธ ๊ฐ์ฒด๋ฅผ ๋ฐ์์ targetId๊ฐ์ ๋ฐ๋ผ ํด๋น ํจ์ ํธ์ถ
+ * @param {object} event ๋ ์ด๋ฒคํธ ๊ฐ์ฒด
+ */
+function _keypressEvent(event) {
+ var target, key, targetId;
+ target = event.target || event.srcElement;
+ key = event.keyCode;
+ targetId = target.getAttribute('id');
+
+ if (!target.value) {
+ return;
+ }
+
+ if (key === KEY_ENTER && targetId === 'todoInputTxt') {
+ _addTodoObject(target);
+ }
+}
+
+/**
+ * ํด๋น todo์ checkbox๋ฅผ ํด๋ฆญํ๋ฉด isChecked์ ๊ฐ์ ๋ณ๊ฒฝํ ๋ค ์ฌ ๋ ๋๋ง
+ * @param {string} idTodo ๋ todo์ id๊ฐ
+ * @param {object} isCheckedTarget ๋ ํด๋ฆญ๋ checkbox์ isChecked๊ฐ
+ */
+function _toggleTodo(idTodo, isCheckedTarget) {
+ _forEach(todoObjects, function(index, value) {
+ if (value.id === idTodo) {
+ value.isChecked = (!!isCheckedTarget);
+ }
+ });
+ _loadTodoData(todoObjects);
+ _renderView();
+}
+
+/**
+ * ์๋ฃ๋ ๋ชจ๋ todoํญ๋ชฉ๋ค์ ์ ๊ฑฐ ํ๋ ํจ์
+ */
+function _removeComplteList() {
+ if (completeTodoObjects.length === 0) {
+ return;
+ }
+ completeTodoObjects = [];
+ todoObjects = snippet.filter(todoObjects, function(value) {
+ return (value.isChecked === false);
+ });
+ _renderView();
+}
+
+/**
+ * completeList, incompleteList ์๋ฆฌ๋ฉํธ์ hide ํด๋์ค ์ ๊ฑฐ
+ */
+function _removeClassHideOfList() {
+ Domclass.removeClass(completeListElement, 'hide');
+ Domclass.removeClass(incompleteListElement, 'hide');
+}
+
+/**
+ * filter Button ์ค์ ํ๋๋ฅผ ํด๋ฆญํ๋ฉด ํด๋น ๋์์ ๋ง๊ฒ hideํด๋์ค๋ฅผ ์ถ๊ฐํ์ฌ List์ ์์ฑ๊ฐ display:none์ผ๋ก ๋ณ๊ฒฝ
+ * @param {object} target ๋ filter Button ๊ฐ์ฒด ์ค ํ๋
+ */
+function _clickFilterBtn(target) {
+ if (target.id === 'btnAllList') {
+ _removeClassHideOfList();
+ } else if (target.id === 'btnActiveList') {
+ _removeClassHideOfList();
+ Domclass.addClass(completeListElement, 'hide');
+ } else if (target.id === 'btnCompleteList') {
+ _removeClassHideOfList();
+ Domclass.addClass(incompleteListElement, 'hide');
+ }
+}
+
+/**
+ * click ์ด๋ฒคํธ๊ฐ ๋ฐ์ํ๋ฉด ์ด๋ฒคํธ ๊ฐ์ฒด๋ฅผ ๋ฐ์์ target ๊ฐ์ ๋ฐ๋ผ ํด๋น ํจ์ ํธ์ถ
+ * @param {object} event ๋ ์ด๋ฒคํธ ๊ฐ์ฒด
+ */
+function _clickEvent(event) {
+ var target;
+ var todoElement;
+ var todoId;
+ target = event.target || event.srcElement;
+ todoElement = target.parentElement;
+
+ if (target.type === 'checkbox' && Domclass.hasClass(todoElement, 'todo')) {
+ todoId = todoElement.getAttribute('data-id');
+ _toggleTodo(todoId, target.checked);
+ } else if (target.id === 'btnDelCompleteList') {
+ _removeComplteList();
+ } else if (target.id === 'btnAllList' || target.id === 'btnActiveList' || target.id === 'btnCompleteList') {
+ _clickFilterBtn(target);
+ }
+}
+
+/**
+ * keypress, click ์ด๋ฒคํธ ๋ฐ์ธ๋ฉ
+ */
+function _bindEvent() {
+ Eventutil.addHandler(todoListWrapElement, 'keypress', _keypressEvent);
+ Eventutil.addHandler(todoListWrapElement, 'click', _clickEvent);
+}
+
+/**
+ * ๊ฐ์ข
ํจ์ ์ด๊ธฐํ
+ * @param {object} todoData todoList์ ๋ํ ๋ฐ์ดํฐ ์ ๋ณด
+ */
+function init(todoData) {
+ _initElement();
+ _loadTodoData(todoData);
+ _renderView();
+ _bindEvent();
+}
+
+/**
+ * @returns {Object} ํ์ฌ ๊ฐ์ง๊ณ ์๋ todo ๊ฐ์ฒด ๋ฐํ
+ */
+function getTodoObjects() {
+ return todoObjects;
+}
+
+module.exports = {
+ init: init,
+ // test์์ ์ฌ์ฉํ๊ธฐ ์ํด ํจ์๋ฅผ ๋
ธ์ถ์์ผ๋์์ต๋๋ค.
+ _clickFilterBtn: _clickFilterBtn,
+ _removeComplteList: _removeComplteList,
+ _toggleTodo: _toggleTodo,
+ _addTodoObject: _addTodoObject,
+ getTodoObjects: getTodoObjects
+}; | JavaScript | ํ์ผ์ด ํ๋ ๋์ด๋๋.. ์ด๋ฐ ๋ฐฐ์ด ์ฐ์ฐ์ ๋ํ ๋ก์ง๋ค์ ์ ํธ๋ก ๋นผ๋๊ฒ ์ข์ต๋๋ค~ |
@@ -0,0 +1,271 @@
+var Domclass = require('../util/Domclass');
+var Eventutil = require('../util/Eventutil');
+var snippet = require('tui-code-snippet');
+
+var KEY_ENTER = 13;
+
+var todoObjects = []; // ๋ชจ๋ todoData
+var completeTodoObjects = []; // isChecked๊ฐ true์ธ ๊ฐ
+var incompleteTodoObjects = []; // isChecked๊ฐ false์ธ ๊ฐ
+
+var todoListWrapElement;
+var completeListElement;
+var incompleteListElement;
+var leftItemNumElement;
+var completeItemsNumElement;
+
+var _initElement = function() {
+ todoListWrapElement = document.getElementById('todoListWrap');
+ completeListElement = document.getElementById('completeList');
+ incompleteListElement = document.getElementById('incompleteList');
+ leftItemNumElement = document.getElementById('leftItemsNum');
+ completeItemsNumElement = document.getElementById('completeItemsNum');
+};
+
+var _forEach = function(arr, func) {
+ var i = 0;
+ var arrLength = arr.length;
+ for (; i < arrLength; i += 1) {
+ func.call(this, i, arr[i]);
+ }
+};
+
+/**
+ * ๊ฐ์ฒด๊ฐ ๋ฑ๋ก๋ ์๊ฐ์ ๊ธฐ์ค์ผ๋ก ๋ด๋ฆผ์ฐจ์์ผ๋ก ์ ๋ ฌ ํ๋ ํจ์
+ * @param {array} arr ๋ ์ ๋ ฌํ๊ณ ์ถ์ ๋ฐฐ์ด
+ */
+function _sortRegDateOfTodoObject(arr) {
+ arr.sort(function(a, b) {
+ if (a.regDate < b.regDate) {
+ return 1;
+ } else if (a.regDate > b.regDate) {
+ return -1;
+ }
+
+ return 0;
+ });
+}
+
+/**
+ * ์ธ์๋ก ๋ฐ์ ๋ฐ์ดํฐ ์ ๋ณด๋ฅผ todoObjects์ ๋ด๊ณ , isChecked = false์ธ๊ฒ์ incompleteTodoObjects,
+ * isChecked = true์ธ๊ฒ์ completeTodoObjects ๋ฐฐ์ด์ ๋ด์ ๋ค ์ค๋ฆ์ฐจ์ ์ ๋ ฌ
+ * @param {array} todoData ๋ todo ๋ฐ์ดํฐ ์ ๋ณด
+ */
+function _loadTodoData(todoData) {
+ todoObjects = todoData;
+
+ completeTodoObjects = snippet.filter(todoObjects, function(value) {
+ return value.isChecked;
+ });
+
+ _sortRegDateOfTodoObject(completeTodoObjects);
+
+ incompleteTodoObjects = snippet.filter(todoObjects, function(value) {
+ return !value.isChecked;
+ });
+
+ _sortRegDateOfTodoObject(incompleteTodoObjects);
+}
+
+/**
+ * completeList๋ฅผ ๋ ๋๋งํด์ฃผ๋ ํจ์
+ */
+function _renderCompleteTodoList() {
+ var htmlLi = '';
+ var todoId, todoTitle;
+
+ _forEach(completeTodoObjects, function(index, value) {
+ todoId = value.id;
+ todoTitle = value.title;
+ htmlLi += '<li class="todo" data-id="' + todoId + '"><input type="checkbox" class="todoChk" checked/><p class="todoTitle">' + todoTitle + '</p></li>';
+ });
+
+ completeListElement.innerHTML = htmlLi;
+}
+
+/**
+ * incompleteList๋ฅผ ๋ ๋๋งํด์ฃผ๋ ํจ์
+ */
+function _renderIncompleteTodoList() {
+ var htmlLi = '';
+ var todoId, todoTitle;
+
+ _forEach(incompleteTodoObjects, function(index, value) {
+ todoId = value.id;
+ todoTitle = value.title;
+ htmlLi += '<li class="todo" data-id="' + todoId + '"><input type="checkbox" class="todoChk"/><p class="todoTitle">' + todoTitle + '</p></li>';
+ });
+
+ incompleteListElement.innerHTML = htmlLi;
+}
+
+/**
+ * _renderCompleteTodoList, _renderIncompleteTodoList ํจ์ ํธ์ถ
+ */
+function _renderTodoList() {
+ _renderCompleteTodoList();
+ _renderIncompleteTodoList();
+}
+
+/**
+ * infoList๋ฅผ ๋ ๋๋ง ํด์ฃผ๋ ํจ์
+ */
+function _renderInfoList() {
+ leftItemNumElement.innerText = incompleteTodoObjects.length;
+ completeItemsNumElement.innerText = completeTodoObjects.length;
+}
+
+/**
+ * _renderTodoList, _renderInfoList ํจ์ ํธ์ถ
+ */
+function _renderView() {
+ _renderTodoList();
+ _renderInfoList();
+}
+
+/**
+ * ํ
์คํธ๋ฐ์ค์์ ๋ฐ์ ๊ฐ์ ๊ฐ์ง๊ณ ์๋ก์ด todo ๊ฐ์ฒด๋ฅผ ๋ง๋ค๊ณ todoObjects์ ๋ฃ์ด ๋๋ค ์ฌ ๋ ๋๋ง
+ * @param {object} target ๋ inputTxt ๊ฐ์ฒด
+ */
+function _addTodoObject(target) {
+ var objTodo = {
+ id: 'todo' + snippet.stamp({}),
+ title: target.value,
+ isChecked: false,
+ regDate: snippet.timestamp()
+ };
+ todoObjects.push(objTodo);
+ target.value = '';
+
+ _loadTodoData(todoObjects);
+ _renderView();
+}
+
+/**
+ * keypress์ด๋ฒคํธ๊ฐ ๋ฐ์ํ๋ฉด ์ด๋ฒคํธ ๊ฐ์ฒด๋ฅผ ๋ฐ์์ targetId๊ฐ์ ๋ฐ๋ผ ํด๋น ํจ์ ํธ์ถ
+ * @param {object} event ๋ ์ด๋ฒคํธ ๊ฐ์ฒด
+ */
+function _keypressEvent(event) {
+ var target, key, targetId;
+ target = event.target || event.srcElement;
+ key = event.keyCode;
+ targetId = target.getAttribute('id');
+
+ if (!target.value) {
+ return;
+ }
+
+ if (key === KEY_ENTER && targetId === 'todoInputTxt') {
+ _addTodoObject(target);
+ }
+}
+
+/**
+ * ํด๋น todo์ checkbox๋ฅผ ํด๋ฆญํ๋ฉด isChecked์ ๊ฐ์ ๋ณ๊ฒฝํ ๋ค ์ฌ ๋ ๋๋ง
+ * @param {string} idTodo ๋ todo์ id๊ฐ
+ * @param {object} isCheckedTarget ๋ ํด๋ฆญ๋ checkbox์ isChecked๊ฐ
+ */
+function _toggleTodo(idTodo, isCheckedTarget) {
+ _forEach(todoObjects, function(index, value) {
+ if (value.id === idTodo) {
+ value.isChecked = (!!isCheckedTarget);
+ }
+ });
+ _loadTodoData(todoObjects);
+ _renderView();
+}
+
+/**
+ * ์๋ฃ๋ ๋ชจ๋ todoํญ๋ชฉ๋ค์ ์ ๊ฑฐ ํ๋ ํจ์
+ */
+function _removeComplteList() {
+ if (completeTodoObjects.length === 0) {
+ return;
+ }
+ completeTodoObjects = [];
+ todoObjects = snippet.filter(todoObjects, function(value) {
+ return (value.isChecked === false);
+ });
+ _renderView();
+}
+
+/**
+ * completeList, incompleteList ์๋ฆฌ๋ฉํธ์ hide ํด๋์ค ์ ๊ฑฐ
+ */
+function _removeClassHideOfList() {
+ Domclass.removeClass(completeListElement, 'hide');
+ Domclass.removeClass(incompleteListElement, 'hide');
+}
+
+/**
+ * filter Button ์ค์ ํ๋๋ฅผ ํด๋ฆญํ๋ฉด ํด๋น ๋์์ ๋ง๊ฒ hideํด๋์ค๋ฅผ ์ถ๊ฐํ์ฌ List์ ์์ฑ๊ฐ display:none์ผ๋ก ๋ณ๊ฒฝ
+ * @param {object} target ๋ filter Button ๊ฐ์ฒด ์ค ํ๋
+ */
+function _clickFilterBtn(target) {
+ if (target.id === 'btnAllList') {
+ _removeClassHideOfList();
+ } else if (target.id === 'btnActiveList') {
+ _removeClassHideOfList();
+ Domclass.addClass(completeListElement, 'hide');
+ } else if (target.id === 'btnCompleteList') {
+ _removeClassHideOfList();
+ Domclass.addClass(incompleteListElement, 'hide');
+ }
+}
+
+/**
+ * click ์ด๋ฒคํธ๊ฐ ๋ฐ์ํ๋ฉด ์ด๋ฒคํธ ๊ฐ์ฒด๋ฅผ ๋ฐ์์ target ๊ฐ์ ๋ฐ๋ผ ํด๋น ํจ์ ํธ์ถ
+ * @param {object} event ๋ ์ด๋ฒคํธ ๊ฐ์ฒด
+ */
+function _clickEvent(event) {
+ var target;
+ var todoElement;
+ var todoId;
+ target = event.target || event.srcElement;
+ todoElement = target.parentElement;
+
+ if (target.type === 'checkbox' && Domclass.hasClass(todoElement, 'todo')) {
+ todoId = todoElement.getAttribute('data-id');
+ _toggleTodo(todoId, target.checked);
+ } else if (target.id === 'btnDelCompleteList') {
+ _removeComplteList();
+ } else if (target.id === 'btnAllList' || target.id === 'btnActiveList' || target.id === 'btnCompleteList') {
+ _clickFilterBtn(target);
+ }
+}
+
+/**
+ * keypress, click ์ด๋ฒคํธ ๋ฐ์ธ๋ฉ
+ */
+function _bindEvent() {
+ Eventutil.addHandler(todoListWrapElement, 'keypress', _keypressEvent);
+ Eventutil.addHandler(todoListWrapElement, 'click', _clickEvent);
+}
+
+/**
+ * ๊ฐ์ข
ํจ์ ์ด๊ธฐํ
+ * @param {object} todoData todoList์ ๋ํ ๋ฐ์ดํฐ ์ ๋ณด
+ */
+function init(todoData) {
+ _initElement();
+ _loadTodoData(todoData);
+ _renderView();
+ _bindEvent();
+}
+
+/**
+ * @returns {Object} ํ์ฌ ๊ฐ์ง๊ณ ์๋ todo ๊ฐ์ฒด ๋ฐํ
+ */
+function getTodoObjects() {
+ return todoObjects;
+}
+
+module.exports = {
+ init: init,
+ // test์์ ์ฌ์ฉํ๊ธฐ ์ํด ํจ์๋ฅผ ๋
ธ์ถ์์ผ๋์์ต๋๋ค.
+ _clickFilterBtn: _clickFilterBtn,
+ _removeComplteList: _removeComplteList,
+ _toggleTodo: _toggleTodo,
+ _addTodoObject: _addTodoObject,
+ getTodoObjects: getTodoObjects
+}; | JavaScript | ์. ์ด๋ฒ ๊ณผ์ ์์ ์ฝ๋ ์ค๋ํซ์ ์ฌ์ฉํ ๊ฒ์ผ๋ก ๋ณด์..
`snippet.forEach` API๋ฅผ ์ฌ์ฉํ ์ ์๊ฒ ๊ตฐ์~ |
@@ -0,0 +1,271 @@
+var Domclass = require('../util/Domclass');
+var Eventutil = require('../util/Eventutil');
+var snippet = require('tui-code-snippet');
+
+var KEY_ENTER = 13;
+
+var todoObjects = []; // ๋ชจ๋ todoData
+var completeTodoObjects = []; // isChecked๊ฐ true์ธ ๊ฐ
+var incompleteTodoObjects = []; // isChecked๊ฐ false์ธ ๊ฐ
+
+var todoListWrapElement;
+var completeListElement;
+var incompleteListElement;
+var leftItemNumElement;
+var completeItemsNumElement;
+
+var _initElement = function() {
+ todoListWrapElement = document.getElementById('todoListWrap');
+ completeListElement = document.getElementById('completeList');
+ incompleteListElement = document.getElementById('incompleteList');
+ leftItemNumElement = document.getElementById('leftItemsNum');
+ completeItemsNumElement = document.getElementById('completeItemsNum');
+};
+
+var _forEach = function(arr, func) {
+ var i = 0;
+ var arrLength = arr.length;
+ for (; i < arrLength; i += 1) {
+ func.call(this, i, arr[i]);
+ }
+};
+
+/**
+ * ๊ฐ์ฒด๊ฐ ๋ฑ๋ก๋ ์๊ฐ์ ๊ธฐ์ค์ผ๋ก ๋ด๋ฆผ์ฐจ์์ผ๋ก ์ ๋ ฌ ํ๋ ํจ์
+ * @param {array} arr ๋ ์ ๋ ฌํ๊ณ ์ถ์ ๋ฐฐ์ด
+ */
+function _sortRegDateOfTodoObject(arr) {
+ arr.sort(function(a, b) {
+ if (a.regDate < b.regDate) {
+ return 1;
+ } else if (a.regDate > b.regDate) {
+ return -1;
+ }
+
+ return 0;
+ });
+}
+
+/**
+ * ์ธ์๋ก ๋ฐ์ ๋ฐ์ดํฐ ์ ๋ณด๋ฅผ todoObjects์ ๋ด๊ณ , isChecked = false์ธ๊ฒ์ incompleteTodoObjects,
+ * isChecked = true์ธ๊ฒ์ completeTodoObjects ๋ฐฐ์ด์ ๋ด์ ๋ค ์ค๋ฆ์ฐจ์ ์ ๋ ฌ
+ * @param {array} todoData ๋ todo ๋ฐ์ดํฐ ์ ๋ณด
+ */
+function _loadTodoData(todoData) {
+ todoObjects = todoData;
+
+ completeTodoObjects = snippet.filter(todoObjects, function(value) {
+ return value.isChecked;
+ });
+
+ _sortRegDateOfTodoObject(completeTodoObjects);
+
+ incompleteTodoObjects = snippet.filter(todoObjects, function(value) {
+ return !value.isChecked;
+ });
+
+ _sortRegDateOfTodoObject(incompleteTodoObjects);
+}
+
+/**
+ * completeList๋ฅผ ๋ ๋๋งํด์ฃผ๋ ํจ์
+ */
+function _renderCompleteTodoList() {
+ var htmlLi = '';
+ var todoId, todoTitle;
+
+ _forEach(completeTodoObjects, function(index, value) {
+ todoId = value.id;
+ todoTitle = value.title;
+ htmlLi += '<li class="todo" data-id="' + todoId + '"><input type="checkbox" class="todoChk" checked/><p class="todoTitle">' + todoTitle + '</p></li>';
+ });
+
+ completeListElement.innerHTML = htmlLi;
+}
+
+/**
+ * incompleteList๋ฅผ ๋ ๋๋งํด์ฃผ๋ ํจ์
+ */
+function _renderIncompleteTodoList() {
+ var htmlLi = '';
+ var todoId, todoTitle;
+
+ _forEach(incompleteTodoObjects, function(index, value) {
+ todoId = value.id;
+ todoTitle = value.title;
+ htmlLi += '<li class="todo" data-id="' + todoId + '"><input type="checkbox" class="todoChk"/><p class="todoTitle">' + todoTitle + '</p></li>';
+ });
+
+ incompleteListElement.innerHTML = htmlLi;
+}
+
+/**
+ * _renderCompleteTodoList, _renderIncompleteTodoList ํจ์ ํธ์ถ
+ */
+function _renderTodoList() {
+ _renderCompleteTodoList();
+ _renderIncompleteTodoList();
+}
+
+/**
+ * infoList๋ฅผ ๋ ๋๋ง ํด์ฃผ๋ ํจ์
+ */
+function _renderInfoList() {
+ leftItemNumElement.innerText = incompleteTodoObjects.length;
+ completeItemsNumElement.innerText = completeTodoObjects.length;
+}
+
+/**
+ * _renderTodoList, _renderInfoList ํจ์ ํธ์ถ
+ */
+function _renderView() {
+ _renderTodoList();
+ _renderInfoList();
+}
+
+/**
+ * ํ
์คํธ๋ฐ์ค์์ ๋ฐ์ ๊ฐ์ ๊ฐ์ง๊ณ ์๋ก์ด todo ๊ฐ์ฒด๋ฅผ ๋ง๋ค๊ณ todoObjects์ ๋ฃ์ด ๋๋ค ์ฌ ๋ ๋๋ง
+ * @param {object} target ๋ inputTxt ๊ฐ์ฒด
+ */
+function _addTodoObject(target) {
+ var objTodo = {
+ id: 'todo' + snippet.stamp({}),
+ title: target.value,
+ isChecked: false,
+ regDate: snippet.timestamp()
+ };
+ todoObjects.push(objTodo);
+ target.value = '';
+
+ _loadTodoData(todoObjects);
+ _renderView();
+}
+
+/**
+ * keypress์ด๋ฒคํธ๊ฐ ๋ฐ์ํ๋ฉด ์ด๋ฒคํธ ๊ฐ์ฒด๋ฅผ ๋ฐ์์ targetId๊ฐ์ ๋ฐ๋ผ ํด๋น ํจ์ ํธ์ถ
+ * @param {object} event ๋ ์ด๋ฒคํธ ๊ฐ์ฒด
+ */
+function _keypressEvent(event) {
+ var target, key, targetId;
+ target = event.target || event.srcElement;
+ key = event.keyCode;
+ targetId = target.getAttribute('id');
+
+ if (!target.value) {
+ return;
+ }
+
+ if (key === KEY_ENTER && targetId === 'todoInputTxt') {
+ _addTodoObject(target);
+ }
+}
+
+/**
+ * ํด๋น todo์ checkbox๋ฅผ ํด๋ฆญํ๋ฉด isChecked์ ๊ฐ์ ๋ณ๊ฒฝํ ๋ค ์ฌ ๋ ๋๋ง
+ * @param {string} idTodo ๋ todo์ id๊ฐ
+ * @param {object} isCheckedTarget ๋ ํด๋ฆญ๋ checkbox์ isChecked๊ฐ
+ */
+function _toggleTodo(idTodo, isCheckedTarget) {
+ _forEach(todoObjects, function(index, value) {
+ if (value.id === idTodo) {
+ value.isChecked = (!!isCheckedTarget);
+ }
+ });
+ _loadTodoData(todoObjects);
+ _renderView();
+}
+
+/**
+ * ์๋ฃ๋ ๋ชจ๋ todoํญ๋ชฉ๋ค์ ์ ๊ฑฐ ํ๋ ํจ์
+ */
+function _removeComplteList() {
+ if (completeTodoObjects.length === 0) {
+ return;
+ }
+ completeTodoObjects = [];
+ todoObjects = snippet.filter(todoObjects, function(value) {
+ return (value.isChecked === false);
+ });
+ _renderView();
+}
+
+/**
+ * completeList, incompleteList ์๋ฆฌ๋ฉํธ์ hide ํด๋์ค ์ ๊ฑฐ
+ */
+function _removeClassHideOfList() {
+ Domclass.removeClass(completeListElement, 'hide');
+ Domclass.removeClass(incompleteListElement, 'hide');
+}
+
+/**
+ * filter Button ์ค์ ํ๋๋ฅผ ํด๋ฆญํ๋ฉด ํด๋น ๋์์ ๋ง๊ฒ hideํด๋์ค๋ฅผ ์ถ๊ฐํ์ฌ List์ ์์ฑ๊ฐ display:none์ผ๋ก ๋ณ๊ฒฝ
+ * @param {object} target ๋ filter Button ๊ฐ์ฒด ์ค ํ๋
+ */
+function _clickFilterBtn(target) {
+ if (target.id === 'btnAllList') {
+ _removeClassHideOfList();
+ } else if (target.id === 'btnActiveList') {
+ _removeClassHideOfList();
+ Domclass.addClass(completeListElement, 'hide');
+ } else if (target.id === 'btnCompleteList') {
+ _removeClassHideOfList();
+ Domclass.addClass(incompleteListElement, 'hide');
+ }
+}
+
+/**
+ * click ์ด๋ฒคํธ๊ฐ ๋ฐ์ํ๋ฉด ์ด๋ฒคํธ ๊ฐ์ฒด๋ฅผ ๋ฐ์์ target ๊ฐ์ ๋ฐ๋ผ ํด๋น ํจ์ ํธ์ถ
+ * @param {object} event ๋ ์ด๋ฒคํธ ๊ฐ์ฒด
+ */
+function _clickEvent(event) {
+ var target;
+ var todoElement;
+ var todoId;
+ target = event.target || event.srcElement;
+ todoElement = target.parentElement;
+
+ if (target.type === 'checkbox' && Domclass.hasClass(todoElement, 'todo')) {
+ todoId = todoElement.getAttribute('data-id');
+ _toggleTodo(todoId, target.checked);
+ } else if (target.id === 'btnDelCompleteList') {
+ _removeComplteList();
+ } else if (target.id === 'btnAllList' || target.id === 'btnActiveList' || target.id === 'btnCompleteList') {
+ _clickFilterBtn(target);
+ }
+}
+
+/**
+ * keypress, click ์ด๋ฒคํธ ๋ฐ์ธ๋ฉ
+ */
+function _bindEvent() {
+ Eventutil.addHandler(todoListWrapElement, 'keypress', _keypressEvent);
+ Eventutil.addHandler(todoListWrapElement, 'click', _clickEvent);
+}
+
+/**
+ * ๊ฐ์ข
ํจ์ ์ด๊ธฐํ
+ * @param {object} todoData todoList์ ๋ํ ๋ฐ์ดํฐ ์ ๋ณด
+ */
+function init(todoData) {
+ _initElement();
+ _loadTodoData(todoData);
+ _renderView();
+ _bindEvent();
+}
+
+/**
+ * @returns {Object} ํ์ฌ ๊ฐ์ง๊ณ ์๋ todo ๊ฐ์ฒด ๋ฐํ
+ */
+function getTodoObjects() {
+ return todoObjects;
+}
+
+module.exports = {
+ init: init,
+ // test์์ ์ฌ์ฉํ๊ธฐ ์ํด ํจ์๋ฅผ ๋
ธ์ถ์์ผ๋์์ต๋๋ค.
+ _clickFilterBtn: _clickFilterBtn,
+ _removeComplteList: _removeComplteList,
+ _toggleTodo: _toggleTodo,
+ _addTodoObject: _addTodoObject,
+ getTodoObjects: getTodoObjects
+}; | JavaScript | ์ ํธ๋ฆฌํฐ์ ๊ด๋ จ๋ ํจ์๋ ํ์ผ๋ก ๋ถ๋ฆฌํ์ฌ ๊ด๋ฆฌํ๋๋ก ํ๊ฒ ์ต๋๋ค. |
@@ -0,0 +1,271 @@
+var Domclass = require('../util/Domclass');
+var Eventutil = require('../util/Eventutil');
+var snippet = require('tui-code-snippet');
+
+var KEY_ENTER = 13;
+
+var todoObjects = []; // ๋ชจ๋ todoData
+var completeTodoObjects = []; // isChecked๊ฐ true์ธ ๊ฐ
+var incompleteTodoObjects = []; // isChecked๊ฐ false์ธ ๊ฐ
+
+var todoListWrapElement;
+var completeListElement;
+var incompleteListElement;
+var leftItemNumElement;
+var completeItemsNumElement;
+
+var _initElement = function() {
+ todoListWrapElement = document.getElementById('todoListWrap');
+ completeListElement = document.getElementById('completeList');
+ incompleteListElement = document.getElementById('incompleteList');
+ leftItemNumElement = document.getElementById('leftItemsNum');
+ completeItemsNumElement = document.getElementById('completeItemsNum');
+};
+
+var _forEach = function(arr, func) {
+ var i = 0;
+ var arrLength = arr.length;
+ for (; i < arrLength; i += 1) {
+ func.call(this, i, arr[i]);
+ }
+};
+
+/**
+ * ๊ฐ์ฒด๊ฐ ๋ฑ๋ก๋ ์๊ฐ์ ๊ธฐ์ค์ผ๋ก ๋ด๋ฆผ์ฐจ์์ผ๋ก ์ ๋ ฌ ํ๋ ํจ์
+ * @param {array} arr ๋ ์ ๋ ฌํ๊ณ ์ถ์ ๋ฐฐ์ด
+ */
+function _sortRegDateOfTodoObject(arr) {
+ arr.sort(function(a, b) {
+ if (a.regDate < b.regDate) {
+ return 1;
+ } else if (a.regDate > b.regDate) {
+ return -1;
+ }
+
+ return 0;
+ });
+}
+
+/**
+ * ์ธ์๋ก ๋ฐ์ ๋ฐ์ดํฐ ์ ๋ณด๋ฅผ todoObjects์ ๋ด๊ณ , isChecked = false์ธ๊ฒ์ incompleteTodoObjects,
+ * isChecked = true์ธ๊ฒ์ completeTodoObjects ๋ฐฐ์ด์ ๋ด์ ๋ค ์ค๋ฆ์ฐจ์ ์ ๋ ฌ
+ * @param {array} todoData ๋ todo ๋ฐ์ดํฐ ์ ๋ณด
+ */
+function _loadTodoData(todoData) {
+ todoObjects = todoData;
+
+ completeTodoObjects = snippet.filter(todoObjects, function(value) {
+ return value.isChecked;
+ });
+
+ _sortRegDateOfTodoObject(completeTodoObjects);
+
+ incompleteTodoObjects = snippet.filter(todoObjects, function(value) {
+ return !value.isChecked;
+ });
+
+ _sortRegDateOfTodoObject(incompleteTodoObjects);
+}
+
+/**
+ * completeList๋ฅผ ๋ ๋๋งํด์ฃผ๋ ํจ์
+ */
+function _renderCompleteTodoList() {
+ var htmlLi = '';
+ var todoId, todoTitle;
+
+ _forEach(completeTodoObjects, function(index, value) {
+ todoId = value.id;
+ todoTitle = value.title;
+ htmlLi += '<li class="todo" data-id="' + todoId + '"><input type="checkbox" class="todoChk" checked/><p class="todoTitle">' + todoTitle + '</p></li>';
+ });
+
+ completeListElement.innerHTML = htmlLi;
+}
+
+/**
+ * incompleteList๋ฅผ ๋ ๋๋งํด์ฃผ๋ ํจ์
+ */
+function _renderIncompleteTodoList() {
+ var htmlLi = '';
+ var todoId, todoTitle;
+
+ _forEach(incompleteTodoObjects, function(index, value) {
+ todoId = value.id;
+ todoTitle = value.title;
+ htmlLi += '<li class="todo" data-id="' + todoId + '"><input type="checkbox" class="todoChk"/><p class="todoTitle">' + todoTitle + '</p></li>';
+ });
+
+ incompleteListElement.innerHTML = htmlLi;
+}
+
+/**
+ * _renderCompleteTodoList, _renderIncompleteTodoList ํจ์ ํธ์ถ
+ */
+function _renderTodoList() {
+ _renderCompleteTodoList();
+ _renderIncompleteTodoList();
+}
+
+/**
+ * infoList๋ฅผ ๋ ๋๋ง ํด์ฃผ๋ ํจ์
+ */
+function _renderInfoList() {
+ leftItemNumElement.innerText = incompleteTodoObjects.length;
+ completeItemsNumElement.innerText = completeTodoObjects.length;
+}
+
+/**
+ * _renderTodoList, _renderInfoList ํจ์ ํธ์ถ
+ */
+function _renderView() {
+ _renderTodoList();
+ _renderInfoList();
+}
+
+/**
+ * ํ
์คํธ๋ฐ์ค์์ ๋ฐ์ ๊ฐ์ ๊ฐ์ง๊ณ ์๋ก์ด todo ๊ฐ์ฒด๋ฅผ ๋ง๋ค๊ณ todoObjects์ ๋ฃ์ด ๋๋ค ์ฌ ๋ ๋๋ง
+ * @param {object} target ๋ inputTxt ๊ฐ์ฒด
+ */
+function _addTodoObject(target) {
+ var objTodo = {
+ id: 'todo' + snippet.stamp({}),
+ title: target.value,
+ isChecked: false,
+ regDate: snippet.timestamp()
+ };
+ todoObjects.push(objTodo);
+ target.value = '';
+
+ _loadTodoData(todoObjects);
+ _renderView();
+}
+
+/**
+ * keypress์ด๋ฒคํธ๊ฐ ๋ฐ์ํ๋ฉด ์ด๋ฒคํธ ๊ฐ์ฒด๋ฅผ ๋ฐ์์ targetId๊ฐ์ ๋ฐ๋ผ ํด๋น ํจ์ ํธ์ถ
+ * @param {object} event ๋ ์ด๋ฒคํธ ๊ฐ์ฒด
+ */
+function _keypressEvent(event) {
+ var target, key, targetId;
+ target = event.target || event.srcElement;
+ key = event.keyCode;
+ targetId = target.getAttribute('id');
+
+ if (!target.value) {
+ return;
+ }
+
+ if (key === KEY_ENTER && targetId === 'todoInputTxt') {
+ _addTodoObject(target);
+ }
+}
+
+/**
+ * ํด๋น todo์ checkbox๋ฅผ ํด๋ฆญํ๋ฉด isChecked์ ๊ฐ์ ๋ณ๊ฒฝํ ๋ค ์ฌ ๋ ๋๋ง
+ * @param {string} idTodo ๋ todo์ id๊ฐ
+ * @param {object} isCheckedTarget ๋ ํด๋ฆญ๋ checkbox์ isChecked๊ฐ
+ */
+function _toggleTodo(idTodo, isCheckedTarget) {
+ _forEach(todoObjects, function(index, value) {
+ if (value.id === idTodo) {
+ value.isChecked = (!!isCheckedTarget);
+ }
+ });
+ _loadTodoData(todoObjects);
+ _renderView();
+}
+
+/**
+ * ์๋ฃ๋ ๋ชจ๋ todoํญ๋ชฉ๋ค์ ์ ๊ฑฐ ํ๋ ํจ์
+ */
+function _removeComplteList() {
+ if (completeTodoObjects.length === 0) {
+ return;
+ }
+ completeTodoObjects = [];
+ todoObjects = snippet.filter(todoObjects, function(value) {
+ return (value.isChecked === false);
+ });
+ _renderView();
+}
+
+/**
+ * completeList, incompleteList ์๋ฆฌ๋ฉํธ์ hide ํด๋์ค ์ ๊ฑฐ
+ */
+function _removeClassHideOfList() {
+ Domclass.removeClass(completeListElement, 'hide');
+ Domclass.removeClass(incompleteListElement, 'hide');
+}
+
+/**
+ * filter Button ์ค์ ํ๋๋ฅผ ํด๋ฆญํ๋ฉด ํด๋น ๋์์ ๋ง๊ฒ hideํด๋์ค๋ฅผ ์ถ๊ฐํ์ฌ List์ ์์ฑ๊ฐ display:none์ผ๋ก ๋ณ๊ฒฝ
+ * @param {object} target ๋ filter Button ๊ฐ์ฒด ์ค ํ๋
+ */
+function _clickFilterBtn(target) {
+ if (target.id === 'btnAllList') {
+ _removeClassHideOfList();
+ } else if (target.id === 'btnActiveList') {
+ _removeClassHideOfList();
+ Domclass.addClass(completeListElement, 'hide');
+ } else if (target.id === 'btnCompleteList') {
+ _removeClassHideOfList();
+ Domclass.addClass(incompleteListElement, 'hide');
+ }
+}
+
+/**
+ * click ์ด๋ฒคํธ๊ฐ ๋ฐ์ํ๋ฉด ์ด๋ฒคํธ ๊ฐ์ฒด๋ฅผ ๋ฐ์์ target ๊ฐ์ ๋ฐ๋ผ ํด๋น ํจ์ ํธ์ถ
+ * @param {object} event ๋ ์ด๋ฒคํธ ๊ฐ์ฒด
+ */
+function _clickEvent(event) {
+ var target;
+ var todoElement;
+ var todoId;
+ target = event.target || event.srcElement;
+ todoElement = target.parentElement;
+
+ if (target.type === 'checkbox' && Domclass.hasClass(todoElement, 'todo')) {
+ todoId = todoElement.getAttribute('data-id');
+ _toggleTodo(todoId, target.checked);
+ } else if (target.id === 'btnDelCompleteList') {
+ _removeComplteList();
+ } else if (target.id === 'btnAllList' || target.id === 'btnActiveList' || target.id === 'btnCompleteList') {
+ _clickFilterBtn(target);
+ }
+}
+
+/**
+ * keypress, click ์ด๋ฒคํธ ๋ฐ์ธ๋ฉ
+ */
+function _bindEvent() {
+ Eventutil.addHandler(todoListWrapElement, 'keypress', _keypressEvent);
+ Eventutil.addHandler(todoListWrapElement, 'click', _clickEvent);
+}
+
+/**
+ * ๊ฐ์ข
ํจ์ ์ด๊ธฐํ
+ * @param {object} todoData todoList์ ๋ํ ๋ฐ์ดํฐ ์ ๋ณด
+ */
+function init(todoData) {
+ _initElement();
+ _loadTodoData(todoData);
+ _renderView();
+ _bindEvent();
+}
+
+/**
+ * @returns {Object} ํ์ฌ ๊ฐ์ง๊ณ ์๋ todo ๊ฐ์ฒด ๋ฐํ
+ */
+function getTodoObjects() {
+ return todoObjects;
+}
+
+module.exports = {
+ init: init,
+ // test์์ ์ฌ์ฉํ๊ธฐ ์ํด ํจ์๋ฅผ ๋
ธ์ถ์์ผ๋์์ต๋๋ค.
+ _clickFilterBtn: _clickFilterBtn,
+ _removeComplteList: _removeComplteList,
+ _toggleTodo: _toggleTodo,
+ _addTodoObject: _addTodoObject,
+ getTodoObjects: getTodoObjects
+}; | JavaScript | ์์ฑ์์ ๊ฒฝ์ฐ๋ ๋๋ฌธ์๋ก ์์, ๊ทธ ์ธ ์ ํธ๋ฆฌํฐ ๋ฑ ํฉํ ๋ฆฌ ํจ์๋ ์๋ฌธ์๋ก ์์ํ๋ผ๊ณ ํฉ๋๋ค. |
@@ -0,0 +1,271 @@
+var Domclass = require('../util/Domclass');
+var Eventutil = require('../util/Eventutil');
+var snippet = require('tui-code-snippet');
+
+var KEY_ENTER = 13;
+
+var todoObjects = []; // ๋ชจ๋ todoData
+var completeTodoObjects = []; // isChecked๊ฐ true์ธ ๊ฐ
+var incompleteTodoObjects = []; // isChecked๊ฐ false์ธ ๊ฐ
+
+var todoListWrapElement;
+var completeListElement;
+var incompleteListElement;
+var leftItemNumElement;
+var completeItemsNumElement;
+
+var _initElement = function() {
+ todoListWrapElement = document.getElementById('todoListWrap');
+ completeListElement = document.getElementById('completeList');
+ incompleteListElement = document.getElementById('incompleteList');
+ leftItemNumElement = document.getElementById('leftItemsNum');
+ completeItemsNumElement = document.getElementById('completeItemsNum');
+};
+
+var _forEach = function(arr, func) {
+ var i = 0;
+ var arrLength = arr.length;
+ for (; i < arrLength; i += 1) {
+ func.call(this, i, arr[i]);
+ }
+};
+
+/**
+ * ๊ฐ์ฒด๊ฐ ๋ฑ๋ก๋ ์๊ฐ์ ๊ธฐ์ค์ผ๋ก ๋ด๋ฆผ์ฐจ์์ผ๋ก ์ ๋ ฌ ํ๋ ํจ์
+ * @param {array} arr ๋ ์ ๋ ฌํ๊ณ ์ถ์ ๋ฐฐ์ด
+ */
+function _sortRegDateOfTodoObject(arr) {
+ arr.sort(function(a, b) {
+ if (a.regDate < b.regDate) {
+ return 1;
+ } else if (a.regDate > b.regDate) {
+ return -1;
+ }
+
+ return 0;
+ });
+}
+
+/**
+ * ์ธ์๋ก ๋ฐ์ ๋ฐ์ดํฐ ์ ๋ณด๋ฅผ todoObjects์ ๋ด๊ณ , isChecked = false์ธ๊ฒ์ incompleteTodoObjects,
+ * isChecked = true์ธ๊ฒ์ completeTodoObjects ๋ฐฐ์ด์ ๋ด์ ๋ค ์ค๋ฆ์ฐจ์ ์ ๋ ฌ
+ * @param {array} todoData ๋ todo ๋ฐ์ดํฐ ์ ๋ณด
+ */
+function _loadTodoData(todoData) {
+ todoObjects = todoData;
+
+ completeTodoObjects = snippet.filter(todoObjects, function(value) {
+ return value.isChecked;
+ });
+
+ _sortRegDateOfTodoObject(completeTodoObjects);
+
+ incompleteTodoObjects = snippet.filter(todoObjects, function(value) {
+ return !value.isChecked;
+ });
+
+ _sortRegDateOfTodoObject(incompleteTodoObjects);
+}
+
+/**
+ * completeList๋ฅผ ๋ ๋๋งํด์ฃผ๋ ํจ์
+ */
+function _renderCompleteTodoList() {
+ var htmlLi = '';
+ var todoId, todoTitle;
+
+ _forEach(completeTodoObjects, function(index, value) {
+ todoId = value.id;
+ todoTitle = value.title;
+ htmlLi += '<li class="todo" data-id="' + todoId + '"><input type="checkbox" class="todoChk" checked/><p class="todoTitle">' + todoTitle + '</p></li>';
+ });
+
+ completeListElement.innerHTML = htmlLi;
+}
+
+/**
+ * incompleteList๋ฅผ ๋ ๋๋งํด์ฃผ๋ ํจ์
+ */
+function _renderIncompleteTodoList() {
+ var htmlLi = '';
+ var todoId, todoTitle;
+
+ _forEach(incompleteTodoObjects, function(index, value) {
+ todoId = value.id;
+ todoTitle = value.title;
+ htmlLi += '<li class="todo" data-id="' + todoId + '"><input type="checkbox" class="todoChk"/><p class="todoTitle">' + todoTitle + '</p></li>';
+ });
+
+ incompleteListElement.innerHTML = htmlLi;
+}
+
+/**
+ * _renderCompleteTodoList, _renderIncompleteTodoList ํจ์ ํธ์ถ
+ */
+function _renderTodoList() {
+ _renderCompleteTodoList();
+ _renderIncompleteTodoList();
+}
+
+/**
+ * infoList๋ฅผ ๋ ๋๋ง ํด์ฃผ๋ ํจ์
+ */
+function _renderInfoList() {
+ leftItemNumElement.innerText = incompleteTodoObjects.length;
+ completeItemsNumElement.innerText = completeTodoObjects.length;
+}
+
+/**
+ * _renderTodoList, _renderInfoList ํจ์ ํธ์ถ
+ */
+function _renderView() {
+ _renderTodoList();
+ _renderInfoList();
+}
+
+/**
+ * ํ
์คํธ๋ฐ์ค์์ ๋ฐ์ ๊ฐ์ ๊ฐ์ง๊ณ ์๋ก์ด todo ๊ฐ์ฒด๋ฅผ ๋ง๋ค๊ณ todoObjects์ ๋ฃ์ด ๋๋ค ์ฌ ๋ ๋๋ง
+ * @param {object} target ๋ inputTxt ๊ฐ์ฒด
+ */
+function _addTodoObject(target) {
+ var objTodo = {
+ id: 'todo' + snippet.stamp({}),
+ title: target.value,
+ isChecked: false,
+ regDate: snippet.timestamp()
+ };
+ todoObjects.push(objTodo);
+ target.value = '';
+
+ _loadTodoData(todoObjects);
+ _renderView();
+}
+
+/**
+ * keypress์ด๋ฒคํธ๊ฐ ๋ฐ์ํ๋ฉด ์ด๋ฒคํธ ๊ฐ์ฒด๋ฅผ ๋ฐ์์ targetId๊ฐ์ ๋ฐ๋ผ ํด๋น ํจ์ ํธ์ถ
+ * @param {object} event ๋ ์ด๋ฒคํธ ๊ฐ์ฒด
+ */
+function _keypressEvent(event) {
+ var target, key, targetId;
+ target = event.target || event.srcElement;
+ key = event.keyCode;
+ targetId = target.getAttribute('id');
+
+ if (!target.value) {
+ return;
+ }
+
+ if (key === KEY_ENTER && targetId === 'todoInputTxt') {
+ _addTodoObject(target);
+ }
+}
+
+/**
+ * ํด๋น todo์ checkbox๋ฅผ ํด๋ฆญํ๋ฉด isChecked์ ๊ฐ์ ๋ณ๊ฒฝํ ๋ค ์ฌ ๋ ๋๋ง
+ * @param {string} idTodo ๋ todo์ id๊ฐ
+ * @param {object} isCheckedTarget ๋ ํด๋ฆญ๋ checkbox์ isChecked๊ฐ
+ */
+function _toggleTodo(idTodo, isCheckedTarget) {
+ _forEach(todoObjects, function(index, value) {
+ if (value.id === idTodo) {
+ value.isChecked = (!!isCheckedTarget);
+ }
+ });
+ _loadTodoData(todoObjects);
+ _renderView();
+}
+
+/**
+ * ์๋ฃ๋ ๋ชจ๋ todoํญ๋ชฉ๋ค์ ์ ๊ฑฐ ํ๋ ํจ์
+ */
+function _removeComplteList() {
+ if (completeTodoObjects.length === 0) {
+ return;
+ }
+ completeTodoObjects = [];
+ todoObjects = snippet.filter(todoObjects, function(value) {
+ return (value.isChecked === false);
+ });
+ _renderView();
+}
+
+/**
+ * completeList, incompleteList ์๋ฆฌ๋ฉํธ์ hide ํด๋์ค ์ ๊ฑฐ
+ */
+function _removeClassHideOfList() {
+ Domclass.removeClass(completeListElement, 'hide');
+ Domclass.removeClass(incompleteListElement, 'hide');
+}
+
+/**
+ * filter Button ์ค์ ํ๋๋ฅผ ํด๋ฆญํ๋ฉด ํด๋น ๋์์ ๋ง๊ฒ hideํด๋์ค๋ฅผ ์ถ๊ฐํ์ฌ List์ ์์ฑ๊ฐ display:none์ผ๋ก ๋ณ๊ฒฝ
+ * @param {object} target ๋ filter Button ๊ฐ์ฒด ์ค ํ๋
+ */
+function _clickFilterBtn(target) {
+ if (target.id === 'btnAllList') {
+ _removeClassHideOfList();
+ } else if (target.id === 'btnActiveList') {
+ _removeClassHideOfList();
+ Domclass.addClass(completeListElement, 'hide');
+ } else if (target.id === 'btnCompleteList') {
+ _removeClassHideOfList();
+ Domclass.addClass(incompleteListElement, 'hide');
+ }
+}
+
+/**
+ * click ์ด๋ฒคํธ๊ฐ ๋ฐ์ํ๋ฉด ์ด๋ฒคํธ ๊ฐ์ฒด๋ฅผ ๋ฐ์์ target ๊ฐ์ ๋ฐ๋ผ ํด๋น ํจ์ ํธ์ถ
+ * @param {object} event ๋ ์ด๋ฒคํธ ๊ฐ์ฒด
+ */
+function _clickEvent(event) {
+ var target;
+ var todoElement;
+ var todoId;
+ target = event.target || event.srcElement;
+ todoElement = target.parentElement;
+
+ if (target.type === 'checkbox' && Domclass.hasClass(todoElement, 'todo')) {
+ todoId = todoElement.getAttribute('data-id');
+ _toggleTodo(todoId, target.checked);
+ } else if (target.id === 'btnDelCompleteList') {
+ _removeComplteList();
+ } else if (target.id === 'btnAllList' || target.id === 'btnActiveList' || target.id === 'btnCompleteList') {
+ _clickFilterBtn(target);
+ }
+}
+
+/**
+ * keypress, click ์ด๋ฒคํธ ๋ฐ์ธ๋ฉ
+ */
+function _bindEvent() {
+ Eventutil.addHandler(todoListWrapElement, 'keypress', _keypressEvent);
+ Eventutil.addHandler(todoListWrapElement, 'click', _clickEvent);
+}
+
+/**
+ * ๊ฐ์ข
ํจ์ ์ด๊ธฐํ
+ * @param {object} todoData todoList์ ๋ํ ๋ฐ์ดํฐ ์ ๋ณด
+ */
+function init(todoData) {
+ _initElement();
+ _loadTodoData(todoData);
+ _renderView();
+ _bindEvent();
+}
+
+/**
+ * @returns {Object} ํ์ฌ ๊ฐ์ง๊ณ ์๋ todo ๊ฐ์ฒด ๋ฐํ
+ */
+function getTodoObjects() {
+ return todoObjects;
+}
+
+module.exports = {
+ init: init,
+ // test์์ ์ฌ์ฉํ๊ธฐ ์ํด ํจ์๋ฅผ ๋
ธ์ถ์์ผ๋์์ต๋๋ค.
+ _clickFilterBtn: _clickFilterBtn,
+ _removeComplteList: _removeComplteList,
+ _toggleTodo: _toggleTodo,
+ _addTodoObject: _addTodoObject,
+ getTodoObjects: getTodoObjects
+}; | JavaScript | ๊ตณ์ด ์ด์ฌ์ธํ ํ์๊ฐ ์์ด๋ณด์
๋๋ค. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.