code stringlengths 41 34.3k | lang stringclasses 8
values | review stringlengths 1 4.74k |
|---|---|---|
@@ -0,0 +1,23 @@
+package christmas.domain;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+class MenuTest {
+ @DisplayName("์ฃผ์ด์ง ์ด๋ฆ์ ํ ๋๋ก ๋ฉ๋ด๋ฅผ ํ๋จํ ์ ์๋ค.")
+ @Test
+ void decideMenu() {
+ String inputTapas = "ํํ์ค";
+ String inputSeafoodPasta = "ํด์ฐ๋ฌผํ์คํ";
+ String inputRedWine = "๋ ๋์์ธ";
+ Menu inputTapasResult = Menu.decideMenu(inputTapas);
+ Menu inputSeafoodPastaResult = Menu.decideMenu(inputSeafoodPasta);
+ Menu inputRedWineResult = Menu.decideMenu(inputRedWine);
+
+ assertThat(inputTapasResult).isEqualTo(Menu.TAPAS);
+ assertThat(inputSeafoodPastaResult).isEqualTo(Menu.SEAFOOD_PASTA);
+ assertThat(inputRedWineResult).isEqualTo(Menu.RED_WINE);
+ }
+}
\ No newline at end of file | Java | ๋ง์์ ๊ฐ์ธ์ ์ผ๋ก ๊ฐ์ฅ ์์ฌ์ด ๋ถ๋ถ์ธ๋ฐ์,, ๊ตฌํํ๊ณ ๋ฆฌํฉํฐ๋ง์ ํ๋ ๋ง์ด ํด์ ์๊ฐ์ด ๋งค์ฐ ์ด๋ฐํ๋ค๋,, ใ
ใ
|
@@ -0,0 +1,39 @@
+package christmas.domain;
+
+import java.util.Arrays;
+import java.util.List;
+
+public enum MenuType {
+ APPETIZER("์ ํผํ์ด์ ", Arrays.asList(Menu.MUSHROOM_SOUP, Menu.TAPAS, Menu.CAESAR_SALAD)),
+ MAIN("๋ฉ์ธ", Arrays.asList(Menu.T_BONE_STAKE, Menu.BARBECUE_LIP, Menu.SEAFOOD_PASTA, Menu.CHRISTMAS_PASTA)),
+ DESSERT("๋์ ํธ", Arrays.asList(Menu.CHOCOLATE_CAKE, Menu.ICE_CREAM)),
+ BEVERAGE("์๋ฃ", Arrays.asList(Menu.ZERO_COKE, Menu.RED_WINE, Menu.CHAMPAGNE));
+
+ private final String name;
+ private final List<Menu> menus;
+
+ MenuType(String name, List<Menu> menus) {
+ this.name = name;
+ this.menus = menus;
+ }
+
+ public static MenuType decideMenuType(Menu menu) {
+ MenuType[] menuTypes = values();
+
+ for (MenuType menuType : menuTypes) {
+ if (menuType.getMenus().contains(menu)) {
+ return menuType;
+ }
+ }
+
+ return null;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public List<Menu> getMenus() {
+ return menus;
+ }
+}
\ No newline at end of file | Java | ์ ํํ
๋จ๊ฒจ์ฃผ์
จ๋ ์ฝ๋ ๋ฆฌ๋ทฐ์์ ์ธ๊ธํ์ ํจํด์ด๋ค์! ์ข์ ๊ณต๋ถ๊ฐ ๋ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,21 @@
+package christmas.domain;
+
+public enum OrderResultType {
+ ORDER_MENU("<์ฃผ๋ฌธ ๋ฉ๋ด>"),
+ TOTAL_ORDER_PRICE("<ํ ์ธ ์ ์ด์ฃผ๋ฌธ ๊ธ์ก>"),
+ GIFT_MENU("<์ฆ์ ๋ฉ๋ด>"),
+ BENEFIT_STATISTICS("<ํํ ๋ด์ญ>"),
+ TOTAL_BENEFIT_AMOUNT("<์ดํํ ๊ธ์ก>"),
+ ESTIMATED_PAYMENT("<ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก>"),
+ EVENT_BADGE("<12์ ์ด๋ฒคํธ ๋ฐฐ์ง>");
+
+ private final String name;
+
+ OrderResultType(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+} | Java | ๐ค `OrderResultType`์ ์ ๋ชฉ์ ๊ทธ๋ ๋ค ์ณ๋, < > ๊ฐ์ character ๋ค์ View์ ์ฑ
์์ ๊ฐ๊น์ ๋ณด์ฌ์.
View์์`"<%s>"` ์ ๊ฐ์ ๋ฐฉ๋ฒ์ผ๋ก ์ฑ
์์ ๋ถ๋ฆฌํ๊ณ formatting์ ์ด์ฉํด ์ถ๋ ฅํ๋ ๋ฐฉ๋ฒ์ด ๋ ๋ณ๊ฒฝ์ ๊ฐํ ์ค๊ณ ์๋๊น์? |
@@ -0,0 +1,45 @@
+package christmas.domain;
+
+public class OrderedMenu {
+ public static final String ORDER_RE_READ_REQUEST_MESSAGE = "์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.";
+ private static final int AMOUNT_MINIMUM_QUANTITY = 1;
+
+ private final String menuName;
+ private final int quantity;
+
+ public OrderedMenu(String menuName, int quantity) {
+ validateOrderNameExistInMenu(menuName);
+ validateOrderAmountQuantity(quantity);
+
+ this.menuName = menuName;
+ this.quantity = quantity;
+ }
+
+ private void validateOrderNameExistInMenu(String name) {
+ if (Menu.decideMenu(name) == Menu.NONE) {
+ throw new IllegalArgumentException(ORDER_RE_READ_REQUEST_MESSAGE);
+ }
+ }
+
+ private void validateOrderAmountQuantity(int amount) {
+ if (amount < AMOUNT_MINIMUM_QUANTITY) {
+ throw new IllegalArgumentException(ORDER_RE_READ_REQUEST_MESSAGE);
+ }
+ }
+
+ public boolean isBeverage() {
+ return MenuType.decideMenuType(Menu.decideMenu(menuName)) == MenuType.BEVERAGE;
+ }
+
+ public int calculatePrice() {
+ return Menu.decideMenu(menuName).getPrice() * quantity;
+ }
+
+ public String getMenuName() {
+ return menuName;
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+}
\ No newline at end of file | Java | `Menu` ์ ์ํ๋ ๊ฒ์ผ๋ก ๊ฒ์ฆ์ด ๋์๋ค๋ฉด, field๋ฅผ `String`์ด ์๋ `Menu`๋ก ์ ์ฅํ๋๊ฒ ๋ ์ข์์ ๊ฒ ๊ฐ์์.
enum ์ฌ์ฉ์ ์๋ฏธ๊ฐ ์ฝ๊ฐ ํด์๋์ง ์์๋ ์ถ๋ค์! |
@@ -0,0 +1,52 @@
+package christmas.ui;
+
+import static christmas.domain.Date.DATE_RE_READ_REQUEST_MESSAGE;
+import static christmas.domain.OrderedMenu.ORDER_RE_READ_REQUEST_MESSAGE;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class Converter {
+ private static final String ORDER_DELIMITER = ",";
+ private static final String NAME_AND_AMOUNT_DELIMITER = "-";
+
+ public static int convertDateNumeric(String Input) {
+ try {
+ return Integer.parseInt(Input);
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException(DATE_RE_READ_REQUEST_MESSAGE);
+ }
+ }
+
+ public static List<String> separateOrder(String order) {
+ return new ArrayList<>(List.of(order.split(ORDER_DELIMITER)));
+ }
+
+ public static List<String> separateNameAndAmount(String orderedMenu) {
+ validateAppropriateDelimiter(orderedMenu);
+ List<String> separatedNameAndAmount = new ArrayList<>(List.of(orderedMenu.split(NAME_AND_AMOUNT_DELIMITER)));
+ validateAppropriateForm(separatedNameAndAmount);
+
+ return separatedNameAndAmount;
+ }
+
+ private static void validateAppropriateDelimiter(String orderedMenu) {
+ if (!orderedMenu.contains(NAME_AND_AMOUNT_DELIMITER)) {
+ throw new IllegalArgumentException(ORDER_RE_READ_REQUEST_MESSAGE);
+ }
+ }
+
+ private static void validateAppropriateForm(List<String> separatedNameAndAmount) {
+ if (separatedNameAndAmount.size() != 2) {
+ throw new IllegalArgumentException(ORDER_RE_READ_REQUEST_MESSAGE);
+ }
+ }
+
+ public static int convertAmountNumeric(String input) {
+ try {
+ return Integer.parseInt(input);
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException(ORDER_RE_READ_REQUEST_MESSAGE);
+ }
+ }
+}
\ No newline at end of file | Java | String์ ์ค๋ธ์ ํธ๋ก ๋ฐ๊พธ๋ ํด๋์ค๋ `Parser`๋ผ๊ณ ์ด๋ฆ ์ง๋ ๊ฒ์ด ๋ convention์ ๊ฐ๊น์ธ ๊ฒ ๊ฐ์๋ฐ, ์ด๋ป๊ฒ ์๊ฐํ์๋์? |
@@ -0,0 +1,63 @@
+package christmas.ui;
+
+import camp.nextstep.edu.missionutils.Console;
+import christmas.domain.Date;
+import christmas.domain.Order;
+import christmas.domain.OrderedMenu;
+import java.util.ArrayList;
+import java.util.List;
+
+public class InputView {
+ private static final String OPENING_MESSAGE = "์๋
ํ์ธ์! ์ฐํ
์ฝ ์๋น 12์ ์ด๋ฒคํธ ํ๋๋์
๋๋ค.";
+ private static final String DATE_REQUEST_MESSAGE = "12์ ์ค ์๋น ์์ ๋ฐฉ๋ฌธ ๋ ์ง๋ ์ธ์ ์ธ๊ฐ์? (์ซ์๋ง ์
๋ ฅํด ์ฃผ์ธ์!)";
+ private static final String ORDER_REQUEST_MESSAGE
+ = "์ฃผ๋ฌธํ์ค ๋ฉ๋ด๋ฅผ ๋ฉ๋ด์ ๊ฐ์๋ฅผ ์๋ ค ์ฃผ์ธ์. (e.g. ํด์ฐ๋ฌผํ์คํ-2,๋ ๋์์ธ-1,์ด์ฝ์ผ์ดํฌ-1)";
+
+ public static void notifyProgramStarted() {
+ System.out.println(OPENING_MESSAGE);
+ }
+
+ public static Date inputDate() {
+ try {
+ return readDate();
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorMessage(e);
+ return inputDate();
+ }
+ }
+
+ private static Date readDate() {
+ System.out.println(DATE_REQUEST_MESSAGE);
+
+ String input = Console.readLine();
+ int dayNumber = Converter.convertDateNumeric(input);
+
+ return new Date(dayNumber);
+ }
+
+ public static Order inputOrder() {
+ try {
+ return new Order(readOrder());
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorMessage(e);
+ return inputOrder();
+ }
+ }
+
+ private static List<OrderedMenu> readOrder() {
+ System.out.println(ORDER_REQUEST_MESSAGE);
+
+ String input = Console.readLine();
+ List<String> separatedOrder = Converter.separateOrder(input);
+ List<OrderedMenu> order = new ArrayList<>();
+
+ for (String orderedMenu : separatedOrder) {
+ List<String> separatedNameAndAmount = Converter.separateNameAndAmount(orderedMenu);
+ String name = separatedNameAndAmount.get(0);
+ int amount = Converter.convertAmountNumeric(separatedNameAndAmount.get(1));
+ order.add(new OrderedMenu(name, amount));
+ }
+
+ return order;
+ }
+}
\ No newline at end of file | Java | Supplier์ ํํ๋ก handling ํ๋ ๋ฐฉ๋ฒ๋ ์์ด์. inputDate์ inputOrder์ ํํ๊ฐ ๊ต์ฅํ ๋ฎ์์์ด์, ์ฌ์ฌ์ฉ์ฑ์ ๋์ด๋ ๋ฐฉ๋ฒ์ผ๋ก ์ ์ฉ ๊ฐ๋ฅํ ๊ฒ ๊ฐ์ผ๋ ์ด ์๋ฃ ํ๋ฒ ์ฝ์ด๋ณด์๊ธธ ์ถ์ฒํฉ๋๋ค.
https://hwan33.tistory.com/17 |
@@ -0,0 +1,85 @@
+package christmas.domain;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+public class EventResult {
+ private static final String NON_BADGE = "์์";
+ private static final String STAR_BADGE = "๋ณ";
+ private static final String TREE_BADGE = "ํธ๋ฆฌ";
+ private static final String SANTA_BADGE = "์ฐํ";
+ private static final int STAR_BADGE_MINIMUM_AMOUNT = 5000;
+ private static final int STAR_BADGE_MAXIMUM_AMOUNT = 10000;
+ private static final int TREE_BADGE_MINIMUM_AMOUNT = 10000;
+ private static final int TREE_BADGE_MAXIMUM_AMOUNT = 20000;
+ private static final int SANTA_BADGE_MINIMUM_AMOUNT = 20000;
+
+ private final Map<BenefitType, Integer> allBenefit;
+
+ public EventResult(Map<BenefitType, Integer> allBenefit) {
+ this.allBenefit = allBenefit;
+ }
+
+ public int calculateTotalBenefitAmount() {
+ int totalBenefitAmount = 0;
+ List<BenefitType> benefitTypes = List.of(BenefitType.values());
+
+ for (BenefitType benefitType : benefitTypes) {
+ totalBenefitAmount += allBenefit.get(benefitType);
+ }
+
+ return totalBenefitAmount;
+ }
+
+ public int calculateTotalDiscountAmount() {
+ int totalDiscountAmount = 0;
+ List<BenefitType> benefitTypes = List.of(BenefitType.values());
+
+ for (BenefitType benefitType : benefitTypes) {
+ totalDiscountAmount += allBenefit.get(benefitType);
+ }
+ if (allBenefit.get(BenefitType.GIFT) == Menu.CHAMPAGNE.getPrice()) {
+ totalDiscountAmount -= Menu.CHAMPAGNE.getPrice();
+ }
+
+ return totalDiscountAmount;
+ }
+
+ public boolean isReceivedGiftBenefit() {
+ return allBenefit.get(BenefitType.GIFT) == Menu.CHAMPAGNE.getPrice();
+ }
+
+ public List<BenefitType> checkWhichBenefitExist() {
+ List<BenefitType> existingBenefit = new ArrayList<>();
+ BenefitType[] benefitTypes = BenefitType.values();
+
+ for (BenefitType benefitType : benefitTypes) {
+ if (allBenefit.get(benefitType) != 0) {
+ existingBenefit.add(benefitType);
+ }
+ }
+
+ return existingBenefit;
+ }
+
+ public String decideEventBadge() {
+ int totalBenefitAmount = calculateTotalBenefitAmount();
+
+ if ((totalBenefitAmount >= STAR_BADGE_MINIMUM_AMOUNT) && (totalBenefitAmount < STAR_BADGE_MAXIMUM_AMOUNT)) {
+ return STAR_BADGE;
+ }
+ if ((totalBenefitAmount >= TREE_BADGE_MINIMUM_AMOUNT) && (totalBenefitAmount < TREE_BADGE_MAXIMUM_AMOUNT)) {
+ return TREE_BADGE;
+ }
+ if ((totalBenefitAmount >= SANTA_BADGE_MINIMUM_AMOUNT)) {
+ return SANTA_BADGE;
+ }
+ return NON_BADGE;
+ }
+
+ public Map<BenefitType, Integer> getAllBenefit() {
+ return Collections.unmodifiableMap(allBenefit);
+ }
+}
\ No newline at end of file | Java | Early return์ ์ฌ์ฉํ์
จ๋๋ฐ, ๊ตณ์ด ๋ฒ์๋ฅผ max, min์ ์ด์ฉํด ์ผ์ผ์ด ์ค๋ช
ํ์ง ์์๋ ๋ ๊ฒ ๊ฐ์์.
๊ผญ maximum_amount๊ฐ ํ์ํ์๊น์?
(๊ทธ๋ฆฌ๊ณ ๋ณ์๋ช
์ maximum์ด๋ผ๊ณ ๋ณด๊ธฐ์ ํด๋น ๋ถ๋ถ์ ํฌํจํ์ง ์์์ ํผ๋์ด ์์ ์ ์์ ๊ฒ ๊ฐ์ต๋๋ค.
์ฐจ๋ผ๋ฆฌ `STAR_BADGE_MAXIMUM_AMOUNT = 9999`์ ๊ฐ์ ๋ฐฉ์์ด์๋ค๋ฉด...)
```suggestion
if (totalBenefitAmount >= STAR_BADGE_MINIMUM_AMOUNT) {
return STAR_BADGE;
}
if (totalBenefitAmount >= TREE_BADGE_MINIMUM_AMOUNT) {
return TREE_BADGE;
}
if ((totalBenefitAmount >= SANTA_BADGE_MINIMUM_AMOUNT)) {
return SANTA_BADGE;
}
return NON_BADGE;
``` |
@@ -0,0 +1,85 @@
+package christmas.domain;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+public class EventResult {
+ private static final String NON_BADGE = "์์";
+ private static final String STAR_BADGE = "๋ณ";
+ private static final String TREE_BADGE = "ํธ๋ฆฌ";
+ private static final String SANTA_BADGE = "์ฐํ";
+ private static final int STAR_BADGE_MINIMUM_AMOUNT = 5000;
+ private static final int STAR_BADGE_MAXIMUM_AMOUNT = 10000;
+ private static final int TREE_BADGE_MINIMUM_AMOUNT = 10000;
+ private static final int TREE_BADGE_MAXIMUM_AMOUNT = 20000;
+ private static final int SANTA_BADGE_MINIMUM_AMOUNT = 20000;
+
+ private final Map<BenefitType, Integer> allBenefit;
+
+ public EventResult(Map<BenefitType, Integer> allBenefit) {
+ this.allBenefit = allBenefit;
+ }
+
+ public int calculateTotalBenefitAmount() {
+ int totalBenefitAmount = 0;
+ List<BenefitType> benefitTypes = List.of(BenefitType.values());
+
+ for (BenefitType benefitType : benefitTypes) {
+ totalBenefitAmount += allBenefit.get(benefitType);
+ }
+
+ return totalBenefitAmount;
+ }
+
+ public int calculateTotalDiscountAmount() {
+ int totalDiscountAmount = 0;
+ List<BenefitType> benefitTypes = List.of(BenefitType.values());
+
+ for (BenefitType benefitType : benefitTypes) {
+ totalDiscountAmount += allBenefit.get(benefitType);
+ }
+ if (allBenefit.get(BenefitType.GIFT) == Menu.CHAMPAGNE.getPrice()) {
+ totalDiscountAmount -= Menu.CHAMPAGNE.getPrice();
+ }
+
+ return totalDiscountAmount;
+ }
+
+ public boolean isReceivedGiftBenefit() {
+ return allBenefit.get(BenefitType.GIFT) == Menu.CHAMPAGNE.getPrice();
+ }
+
+ public List<BenefitType> checkWhichBenefitExist() {
+ List<BenefitType> existingBenefit = new ArrayList<>();
+ BenefitType[] benefitTypes = BenefitType.values();
+
+ for (BenefitType benefitType : benefitTypes) {
+ if (allBenefit.get(benefitType) != 0) {
+ existingBenefit.add(benefitType);
+ }
+ }
+
+ return existingBenefit;
+ }
+
+ public String decideEventBadge() {
+ int totalBenefitAmount = calculateTotalBenefitAmount();
+
+ if ((totalBenefitAmount >= STAR_BADGE_MINIMUM_AMOUNT) && (totalBenefitAmount < STAR_BADGE_MAXIMUM_AMOUNT)) {
+ return STAR_BADGE;
+ }
+ if ((totalBenefitAmount >= TREE_BADGE_MINIMUM_AMOUNT) && (totalBenefitAmount < TREE_BADGE_MAXIMUM_AMOUNT)) {
+ return TREE_BADGE;
+ }
+ if ((totalBenefitAmount >= SANTA_BADGE_MINIMUM_AMOUNT)) {
+ return SANTA_BADGE;
+ }
+ return NON_BADGE;
+ }
+
+ public Map<BenefitType, Integer> getAllBenefit() {
+ return Collections.unmodifiableMap(allBenefit);
+ }
+}
\ No newline at end of file | Java | ์ถ๊ฐ) NON_BADGE๋ ๋ณ์๋ช
ํต์ผ์ฑ์ ์ํด NONE_BADGE๋ก ์์ฑํ์
จ๋ค๋ฉด ๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,39 @@
+package christmas.domain;
+
+import java.util.Arrays;
+import java.util.List;
+
+public enum MenuType {
+ APPETIZER("์ ํผํ์ด์ ", Arrays.asList(Menu.MUSHROOM_SOUP, Menu.TAPAS, Menu.CAESAR_SALAD)),
+ MAIN("๋ฉ์ธ", Arrays.asList(Menu.T_BONE_STAKE, Menu.BARBECUE_LIP, Menu.SEAFOOD_PASTA, Menu.CHRISTMAS_PASTA)),
+ DESSERT("๋์ ํธ", Arrays.asList(Menu.CHOCOLATE_CAKE, Menu.ICE_CREAM)),
+ BEVERAGE("์๋ฃ", Arrays.asList(Menu.ZERO_COKE, Menu.RED_WINE, Menu.CHAMPAGNE));
+
+ private final String name;
+ private final List<Menu> menus;
+
+ MenuType(String name, List<Menu> menus) {
+ this.name = name;
+ this.menus = menus;
+ }
+
+ public static MenuType decideMenuType(Menu menu) {
+ MenuType[] menuTypes = values();
+
+ for (MenuType menuType : menuTypes) {
+ if (menuType.getMenus().contains(menu)) {
+ return menuType;
+ }
+ }
+
+ return null;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public List<Menu> getMenus() {
+ return menus;
+ }
+}
\ No newline at end of file | Java | ๋ง์์ ๋ค์ ๋ฌผ์ด๋ณด์
จ์ด์ ๋๊ธ์ ์ ๋ณด๋ฅผ ์ป์ ๋งํฌ ๋จ๊ฒจ๋๋ ธ์๋๋ฐ์ ๋ชป ๋ณด์ ๊ฒ ๊ฐ์ ๋ค์ ๋จ๊ฒจ๋๋ ค์..!!
https://techblog.woowahan.com/2527/
@Uniaut |
@@ -0,0 +1,21 @@
+package christmas.domain;
+
+public enum OrderResultType {
+ ORDER_MENU("<์ฃผ๋ฌธ ๋ฉ๋ด>"),
+ TOTAL_ORDER_PRICE("<ํ ์ธ ์ ์ด์ฃผ๋ฌธ ๊ธ์ก>"),
+ GIFT_MENU("<์ฆ์ ๋ฉ๋ด>"),
+ BENEFIT_STATISTICS("<ํํ ๋ด์ญ>"),
+ TOTAL_BENEFIT_AMOUNT("<์ดํํ ๊ธ์ก>"),
+ ESTIMATED_PAYMENT("<ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก>"),
+ EVENT_BADGE("<12์ ์ด๋ฒคํธ ๋ฐฐ์ง>");
+
+ private final String name;
+
+ OrderResultType(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+} | Java | ๋ ์ข์ ๋ฐฉ๋ฒ์ธ๊ฒ ๊ฐ๋ค์!! ์ข์ ์๊ฒฌ ๊ฐ์ฌํฉ๋๋ค |
@@ -0,0 +1,45 @@
+package christmas.domain;
+
+public class OrderedMenu {
+ public static final String ORDER_RE_READ_REQUEST_MESSAGE = "์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.";
+ private static final int AMOUNT_MINIMUM_QUANTITY = 1;
+
+ private final String menuName;
+ private final int quantity;
+
+ public OrderedMenu(String menuName, int quantity) {
+ validateOrderNameExistInMenu(menuName);
+ validateOrderAmountQuantity(quantity);
+
+ this.menuName = menuName;
+ this.quantity = quantity;
+ }
+
+ private void validateOrderNameExistInMenu(String name) {
+ if (Menu.decideMenu(name) == Menu.NONE) {
+ throw new IllegalArgumentException(ORDER_RE_READ_REQUEST_MESSAGE);
+ }
+ }
+
+ private void validateOrderAmountQuantity(int amount) {
+ if (amount < AMOUNT_MINIMUM_QUANTITY) {
+ throw new IllegalArgumentException(ORDER_RE_READ_REQUEST_MESSAGE);
+ }
+ }
+
+ public boolean isBeverage() {
+ return MenuType.decideMenuType(Menu.decideMenu(menuName)) == MenuType.BEVERAGE;
+ }
+
+ public int calculatePrice() {
+ return Menu.decideMenu(menuName).getPrice() * quantity;
+ }
+
+ public String getMenuName() {
+ return menuName;
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+}
\ No newline at end of file | Java | ๋ง๋ค์..! ์ข์ ์๊ฒฌ ๊ฐ์ฌํฉ๋๋ค!! Menu์ด๊ฑฐ์์ ๋ฉ๋ด์ ์ํ์ง ์๋ ์
๋ ฅ์ ์ฒ๋ฆฌํ๊ธฐ ์ํด "์์"์ ๋ง๋ค์์๋๋ฐ, ๋ง์ฝ null๋ก ์ฒ๋ฆฌํ์๋ค๋ฉด Menu์ ์ํ๋ ๊ฒ์ผ๋ก ์์ง ๊ฒ์ฆ์ด ์๋์๋ ๊ฑฐ๋๊น ์ง๊ธ์ฒ๋ผ String์ผ๋ก ํ๋ ๊ฒ์ด ๋ง์๊น์? ์ ๊ฐ ์ดํดํ ๊ฒ์ด ๋ง๋์ง ๊ถ๊ธํด์ @Uniaut |
@@ -0,0 +1,58 @@
+package christmas.domain;
+
+import java.time.DayOfWeek;
+import java.time.LocalDate;
+
+public class Date {
+ public static final String DATE_RE_READ_REQUEST_MESSAGE = "์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.";
+ private static final LocalDate CHRISTMAS_DAY = LocalDate.of(2023, 12, 25);
+ private static final int YEAR = 2023;
+ private static final int MONTH = 12;
+ private static final int DATE_MIN_NUMBER = 1;
+ private static final int DATE_MAX_NUMBER = 31;
+
+ private final int dayNumber;
+
+ public Date(int dayNumber) {
+ validateRange(dayNumber);
+ this.dayNumber = dayNumber;
+ }
+
+ private void validateRange(int dayNumber) {
+ if ((dayNumber < DATE_MIN_NUMBER) || (dayNumber > DATE_MAX_NUMBER)) {
+ throw new IllegalArgumentException(DATE_RE_READ_REQUEST_MESSAGE);
+ }
+ }
+
+ public boolean isDDayDiscountActive() {
+ LocalDate localDate = LocalDate.of(YEAR, MONTH, dayNumber);
+
+ return localDate.isBefore(CHRISTMAS_DAY.plusDays(1));
+ }
+
+ public boolean isWeekdayDiscountActive() {
+ LocalDate localDate = LocalDate.of(YEAR, MONTH, dayNumber);
+ DayOfWeek day = localDate.getDayOfWeek();
+
+ return (day.equals(DayOfWeek.MONDAY) || day.equals(DayOfWeek.TUESDAY) || day.equals(DayOfWeek.WEDNESDAY)
+ || day.equals(DayOfWeek.THURSDAY) || day.equals(DayOfWeek.SUNDAY));
+ }
+
+ public boolean isWeekendDiscountActive() {
+ LocalDate localDate = LocalDate.of(YEAR, MONTH, dayNumber);
+ DayOfWeek day = localDate.getDayOfWeek();
+
+ return (day.equals(DayOfWeek.FRIDAY) || day.equals(DayOfWeek.SATURDAY));
+ }
+
+ public boolean isSpecialDiscountActive() {
+ LocalDate localDate = LocalDate.of(YEAR, MONTH, dayNumber);
+ DayOfWeek day = localDate.getDayOfWeek();
+
+ return (day.equals(DayOfWeek.SUNDAY) || localDate.equals(CHRISTMAS_DAY));
+ }
+
+ public int getDayNumber() {
+ return dayNumber;
+ }
+}
\ No newline at end of file | Java | @JaeHongDev
์ ๋ ์๋กญ๊ฒ ๋ฐฐ์๊ฐ๋๋ค..! |
@@ -0,0 +1,85 @@
+package christmas.domain;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+public class EventResult {
+ private static final String NON_BADGE = "์์";
+ private static final String STAR_BADGE = "๋ณ";
+ private static final String TREE_BADGE = "ํธ๋ฆฌ";
+ private static final String SANTA_BADGE = "์ฐํ";
+ private static final int STAR_BADGE_MINIMUM_AMOUNT = 5000;
+ private static final int STAR_BADGE_MAXIMUM_AMOUNT = 10000;
+ private static final int TREE_BADGE_MINIMUM_AMOUNT = 10000;
+ private static final int TREE_BADGE_MAXIMUM_AMOUNT = 20000;
+ private static final int SANTA_BADGE_MINIMUM_AMOUNT = 20000;
+
+ private final Map<BenefitType, Integer> allBenefit;
+
+ public EventResult(Map<BenefitType, Integer> allBenefit) {
+ this.allBenefit = allBenefit;
+ }
+
+ public int calculateTotalBenefitAmount() {
+ int totalBenefitAmount = 0;
+ List<BenefitType> benefitTypes = List.of(BenefitType.values());
+
+ for (BenefitType benefitType : benefitTypes) {
+ totalBenefitAmount += allBenefit.get(benefitType);
+ }
+
+ return totalBenefitAmount;
+ }
+
+ public int calculateTotalDiscountAmount() {
+ int totalDiscountAmount = 0;
+ List<BenefitType> benefitTypes = List.of(BenefitType.values());
+
+ for (BenefitType benefitType : benefitTypes) {
+ totalDiscountAmount += allBenefit.get(benefitType);
+ }
+ if (allBenefit.get(BenefitType.GIFT) == Menu.CHAMPAGNE.getPrice()) {
+ totalDiscountAmount -= Menu.CHAMPAGNE.getPrice();
+ }
+
+ return totalDiscountAmount;
+ }
+
+ public boolean isReceivedGiftBenefit() {
+ return allBenefit.get(BenefitType.GIFT) == Menu.CHAMPAGNE.getPrice();
+ }
+
+ public List<BenefitType> checkWhichBenefitExist() {
+ List<BenefitType> existingBenefit = new ArrayList<>();
+ BenefitType[] benefitTypes = BenefitType.values();
+
+ for (BenefitType benefitType : benefitTypes) {
+ if (allBenefit.get(benefitType) != 0) {
+ existingBenefit.add(benefitType);
+ }
+ }
+
+ return existingBenefit;
+ }
+
+ public String decideEventBadge() {
+ int totalBenefitAmount = calculateTotalBenefitAmount();
+
+ if ((totalBenefitAmount >= STAR_BADGE_MINIMUM_AMOUNT) && (totalBenefitAmount < STAR_BADGE_MAXIMUM_AMOUNT)) {
+ return STAR_BADGE;
+ }
+ if ((totalBenefitAmount >= TREE_BADGE_MINIMUM_AMOUNT) && (totalBenefitAmount < TREE_BADGE_MAXIMUM_AMOUNT)) {
+ return TREE_BADGE;
+ }
+ if ((totalBenefitAmount >= SANTA_BADGE_MINIMUM_AMOUNT)) {
+ return SANTA_BADGE;
+ }
+ return NON_BADGE;
+ }
+
+ public Map<BenefitType, Integer> getAllBenefit() {
+ return Collections.unmodifiableMap(allBenefit);
+ }
+}
\ No newline at end of file | Java | ๋ง์์!! ์ ๋ ๊ฐ์ธ์ ์ผ๋ก ์ด ๋ฉ์๋์ ๋ก์ง์ ๋ง๋ค์๋ ๋ฐฉ์์ด ์์ฌ์ ๋๋ฐ์ ,, ๋ง์ํด ์ฃผ์ ๋ฐฉ๋ฒ์ด ํจ์ฌ ๊น๋ํ ๊ฒ ๊ฐ์์ ๋์
if ((totalBenefitAmount >= SANTA_BADGE_MINIMUM_AMOUNT)) {
return SANTA_BADGE;
}
if (totalBenefitAmount >= TREE_BADGE_MINIMUM_AMOUNT) {
return TREE_BADGE;
}
if (totalBenefitAmount >= STAR_BADGE_MINIMUM_AMOUNT) {
return STAR_BADGE;
}
return NON_BADGE;
์ด๋ฐ์์ผ๋ก ์ฐํ ๋ฐฐ์ง๊ฐ ์ ์ผ ์๋ก ๊ฐ์ผ 30000์์ผ ๋ ๋ณ ๋ฐฐ์ง๋ฅผ ๋ฆฌํดํ์ง ์๊ณ ์ฐํ ๋ฐฐ์ง๋ฅผ ๋ฆฌํด ํ ๊ฒ ๊ฐ์์
์ ๊ฐ ์ดํดํ๊ฒ ๋ง๋์ง ๊ถ๊ธํฉ๋๋ค @Uniaut
Maximum์ด๋ผ๋ ํํ์ ํด๋น ๊ฐ์ ํฌํจํ๋ ํํ์ด๋ ๊ฒ์ ๋์ณค๋ ๊ฒ ๊ฐ๋ค์!! ๋ ์นด๋ก์ด ์ง์ ๊ฐ์ฌํฉ๋๋ค |
@@ -0,0 +1,85 @@
+package christmas.domain;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+public class EventResult {
+ private static final String NON_BADGE = "์์";
+ private static final String STAR_BADGE = "๋ณ";
+ private static final String TREE_BADGE = "ํธ๋ฆฌ";
+ private static final String SANTA_BADGE = "์ฐํ";
+ private static final int STAR_BADGE_MINIMUM_AMOUNT = 5000;
+ private static final int STAR_BADGE_MAXIMUM_AMOUNT = 10000;
+ private static final int TREE_BADGE_MINIMUM_AMOUNT = 10000;
+ private static final int TREE_BADGE_MAXIMUM_AMOUNT = 20000;
+ private static final int SANTA_BADGE_MINIMUM_AMOUNT = 20000;
+
+ private final Map<BenefitType, Integer> allBenefit;
+
+ public EventResult(Map<BenefitType, Integer> allBenefit) {
+ this.allBenefit = allBenefit;
+ }
+
+ public int calculateTotalBenefitAmount() {
+ int totalBenefitAmount = 0;
+ List<BenefitType> benefitTypes = List.of(BenefitType.values());
+
+ for (BenefitType benefitType : benefitTypes) {
+ totalBenefitAmount += allBenefit.get(benefitType);
+ }
+
+ return totalBenefitAmount;
+ }
+
+ public int calculateTotalDiscountAmount() {
+ int totalDiscountAmount = 0;
+ List<BenefitType> benefitTypes = List.of(BenefitType.values());
+
+ for (BenefitType benefitType : benefitTypes) {
+ totalDiscountAmount += allBenefit.get(benefitType);
+ }
+ if (allBenefit.get(BenefitType.GIFT) == Menu.CHAMPAGNE.getPrice()) {
+ totalDiscountAmount -= Menu.CHAMPAGNE.getPrice();
+ }
+
+ return totalDiscountAmount;
+ }
+
+ public boolean isReceivedGiftBenefit() {
+ return allBenefit.get(BenefitType.GIFT) == Menu.CHAMPAGNE.getPrice();
+ }
+
+ public List<BenefitType> checkWhichBenefitExist() {
+ List<BenefitType> existingBenefit = new ArrayList<>();
+ BenefitType[] benefitTypes = BenefitType.values();
+
+ for (BenefitType benefitType : benefitTypes) {
+ if (allBenefit.get(benefitType) != 0) {
+ existingBenefit.add(benefitType);
+ }
+ }
+
+ return existingBenefit;
+ }
+
+ public String decideEventBadge() {
+ int totalBenefitAmount = calculateTotalBenefitAmount();
+
+ if ((totalBenefitAmount >= STAR_BADGE_MINIMUM_AMOUNT) && (totalBenefitAmount < STAR_BADGE_MAXIMUM_AMOUNT)) {
+ return STAR_BADGE;
+ }
+ if ((totalBenefitAmount >= TREE_BADGE_MINIMUM_AMOUNT) && (totalBenefitAmount < TREE_BADGE_MAXIMUM_AMOUNT)) {
+ return TREE_BADGE;
+ }
+ if ((totalBenefitAmount >= SANTA_BADGE_MINIMUM_AMOUNT)) {
+ return SANTA_BADGE;
+ }
+ return NON_BADGE;
+ }
+
+ public Map<BenefitType, Integer> getAllBenefit() {
+ return Collections.unmodifiableMap(allBenefit);
+ }
+}
\ No newline at end of file | Java | if๋ฌธ ์ ๊น์ง๊ฐ calculateTotalBenefitAmount๋ ๊ฐ์์ ๊ฐ์ ์ฝ๋๋ฅผ ์ ์ ํ์์์ด ๋ฉ์๋๋ฅผ ์ฌ์ฉํด๋ ๋ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,85 @@
+package christmas.domain;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+public class EventResult {
+ private static final String NON_BADGE = "์์";
+ private static final String STAR_BADGE = "๋ณ";
+ private static final String TREE_BADGE = "ํธ๋ฆฌ";
+ private static final String SANTA_BADGE = "์ฐํ";
+ private static final int STAR_BADGE_MINIMUM_AMOUNT = 5000;
+ private static final int STAR_BADGE_MAXIMUM_AMOUNT = 10000;
+ private static final int TREE_BADGE_MINIMUM_AMOUNT = 10000;
+ private static final int TREE_BADGE_MAXIMUM_AMOUNT = 20000;
+ private static final int SANTA_BADGE_MINIMUM_AMOUNT = 20000;
+
+ private final Map<BenefitType, Integer> allBenefit;
+
+ public EventResult(Map<BenefitType, Integer> allBenefit) {
+ this.allBenefit = allBenefit;
+ }
+
+ public int calculateTotalBenefitAmount() {
+ int totalBenefitAmount = 0;
+ List<BenefitType> benefitTypes = List.of(BenefitType.values());
+
+ for (BenefitType benefitType : benefitTypes) {
+ totalBenefitAmount += allBenefit.get(benefitType);
+ }
+
+ return totalBenefitAmount;
+ }
+
+ public int calculateTotalDiscountAmount() {
+ int totalDiscountAmount = 0;
+ List<BenefitType> benefitTypes = List.of(BenefitType.values());
+
+ for (BenefitType benefitType : benefitTypes) {
+ totalDiscountAmount += allBenefit.get(benefitType);
+ }
+ if (allBenefit.get(BenefitType.GIFT) == Menu.CHAMPAGNE.getPrice()) {
+ totalDiscountAmount -= Menu.CHAMPAGNE.getPrice();
+ }
+
+ return totalDiscountAmount;
+ }
+
+ public boolean isReceivedGiftBenefit() {
+ return allBenefit.get(BenefitType.GIFT) == Menu.CHAMPAGNE.getPrice();
+ }
+
+ public List<BenefitType> checkWhichBenefitExist() {
+ List<BenefitType> existingBenefit = new ArrayList<>();
+ BenefitType[] benefitTypes = BenefitType.values();
+
+ for (BenefitType benefitType : benefitTypes) {
+ if (allBenefit.get(benefitType) != 0) {
+ existingBenefit.add(benefitType);
+ }
+ }
+
+ return existingBenefit;
+ }
+
+ public String decideEventBadge() {
+ int totalBenefitAmount = calculateTotalBenefitAmount();
+
+ if ((totalBenefitAmount >= STAR_BADGE_MINIMUM_AMOUNT) && (totalBenefitAmount < STAR_BADGE_MAXIMUM_AMOUNT)) {
+ return STAR_BADGE;
+ }
+ if ((totalBenefitAmount >= TREE_BADGE_MINIMUM_AMOUNT) && (totalBenefitAmount < TREE_BADGE_MAXIMUM_AMOUNT)) {
+ return TREE_BADGE;
+ }
+ if ((totalBenefitAmount >= SANTA_BADGE_MINIMUM_AMOUNT)) {
+ return SANTA_BADGE;
+ }
+ return NON_BADGE;
+ }
+
+ public Map<BenefitType, Integer> getAllBenefit() {
+ return Collections.unmodifiableMap(allBenefit);
+ }
+}
\ No newline at end of file | Java | ์ด if๋ฌธ์ ์กฐ๊ฑด๋ isReceivedGiftBenefit ๋ฉ์๋๋ฅผ ์ฌ์ฉํด๋ ๋๊ฒ ๋ค์! |
@@ -0,0 +1,76 @@
+package christmas.domain;
+
+import static christmas.domain.OrderedMenu.ORDER_RE_READ_REQUEST_MESSAGE;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+public class Order {
+ private static final int MAXIMUM_MENU_QUANTITY = 20;
+
+ private final List<OrderedMenu> order;
+
+ public Order(List<OrderedMenu> order) {
+ validateOrderedMenuNamesNotAllBeverage(order);
+ validateOrderedMenuNamesNotDuplicate(order);
+ validateTotalOrderedMenuQuantity(order);
+
+ this.order = order;
+ }
+
+ private void validateOrderedMenuNamesNotAllBeverage(List<OrderedMenu> order) {
+ List<Boolean> beverageChecker = new ArrayList<>();
+
+ for (OrderedMenu orderedMenu : order) {
+ if (orderedMenu.isBeverage()) {
+ beverageChecker.add(true);
+ }
+ if (!orderedMenu.isBeverage()) {
+ beverageChecker.add(false);
+ }
+ }
+
+ if (!beverageChecker.contains(false)) {
+ throw new IllegalArgumentException(ORDER_RE_READ_REQUEST_MESSAGE);
+ }
+ }
+
+ private void validateOrderedMenuNamesNotDuplicate(List<OrderedMenu> order) {
+ Set<String> duplicateChecker = new HashSet<>();
+
+ for (OrderedMenu orderedMenu : order) {
+ duplicateChecker.add(orderedMenu.getMenuName());
+ }
+ if (duplicateChecker.size() != order.size()) {
+ throw new IllegalArgumentException(ORDER_RE_READ_REQUEST_MESSAGE);
+ }
+ }
+
+ private void validateTotalOrderedMenuQuantity(List<OrderedMenu> order) {
+ int totalQuantity = 0;
+
+ for (OrderedMenu orderedMenu : order) {
+ totalQuantity += orderedMenu.getQuantity();
+ }
+ if (totalQuantity > MAXIMUM_MENU_QUANTITY) {
+ throw new IllegalArgumentException(ORDER_RE_READ_REQUEST_MESSAGE);
+ }
+ }
+
+ public int calculateTotalOrderPrice() {
+ int totalOrderPrice = 0;
+
+ for (OrderedMenu orderedMenu : order) {
+ totalOrderPrice += orderedMenu.calculatePrice();
+ }
+
+ return totalOrderPrice;
+ }
+
+ public List<OrderedMenu> getOrder() {
+ return Collections.unmodifiableList(order);
+ }
+}
\ No newline at end of file | Java | ๋ฉ์๋๋ช
์ด ๊ธธ์ด๋ ํ์คํ ์ด๋ฆ๋ง ๋ณด๊ณ ๋ ์ด๋ค ์ญํ ์ ํ๋์ง ๋ฐ๋ก ์ ์ ์์ด์ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,21 @@
+package nextstep.subway;
+
+import org.springframework.dao.DataIntegrityViolationException;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.RestControllerAdvice;
+
+@RestControllerAdvice
+public class ControllerExceptionHandler {
+
+ @ExceptionHandler(DataIntegrityViolationException.class)
+ public ResponseEntity handleIllegalArgsException(DataIntegrityViolationException e) {
+ return ResponseEntity.badRequest().build();
+ }
+
+ @ExceptionHandler(IllegalArgumentException.class)
+ public ResponseEntity handleIllegalArgumentException(IllegalArgumentException illegalArgumentException){
+ String message = illegalArgumentException.getMessage();
+ return ResponseEntity.badRequest().body(message);
+ }
+} | Java | @RestControllerAdvice ๋ฅผ ์ฌ์ฉํ์ฌ ๋ชจ๋ ์๋ฌ๋ฅผ ํ๊ตฐ๋ฐ์ ์ฒ๋ฆฌํด์ค ์ ์๊ฒํด์ค ๋ถ๋ถ ์ข์ต๋๋ค ๐ |
@@ -0,0 +1,21 @@
+package nextstep.subway;
+
+import org.springframework.dao.DataIntegrityViolationException;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.RestControllerAdvice;
+
+@RestControllerAdvice
+public class ControllerExceptionHandler {
+
+ @ExceptionHandler(DataIntegrityViolationException.class)
+ public ResponseEntity handleIllegalArgsException(DataIntegrityViolationException e) {
+ return ResponseEntity.badRequest().build();
+ }
+
+ @ExceptionHandler(IllegalArgumentException.class)
+ public ResponseEntity handleIllegalArgumentException(IllegalArgumentException illegalArgumentException){
+ String message = illegalArgumentException.getMessage();
+ return ResponseEntity.badRequest().body(message);
+ }
+} | Java | ์ด ๋ถ๋ถ์ ์กฐ๊ธ ๊ถ๊ธํ์ฌ ์ฌ์ญค๋ด
๋๋ค! DataIntegrityViolationException ๋ ํ์ฌ ์ดํ๋ฆฌ์ผ์ด์
๋ด์์ ์ธ์ , ์ด๋ค ์ผ์ด์ค์์ ๋ฐ์ํ๊ฒ ๋๋์...? |
@@ -0,0 +1,38 @@
+package nextstep.subway.line.domain;
+
+import java.util.ArrayList;
+import java.util.List;
+import nextstep.subway.station.domain.Station;
+import org.jgrapht.GraphPath;
+import org.jgrapht.alg.shortestpath.DijkstraShortestPath;
+import org.jgrapht.graph.DefaultWeightedEdge;
+import org.jgrapht.graph.WeightedMultigraph;
+
+public class Lines {
+
+ List<Line> lines = new ArrayList<>();
+
+ public Lines(List<Line> lines) {
+ this.lines = lines;
+ }
+
+ public GraphPath minPath(Station sourceStation, Station targetStation) {
+
+ validatePath(sourceStation, targetStation);
+ WeightedMultigraph<Station, DefaultWeightedEdge> graph = new WeightedMultigraph(DefaultWeightedEdge.class);
+
+ for (Line line : lines) {
+ line.addPathInfo(graph);
+ }
+
+ DijkstraShortestPath dijkstraShortestPath = new DijkstraShortestPath(graph);
+
+ return dijkstraShortestPath.getPath(sourceStation, targetStation);
+ }
+
+ private void validatePath(Station sourceStation, Station targetStation){
+ if(sourceStation.equals(targetStation)){
+ throw new IllegalArgumentException("๊ฒฝ๋ก ์์์ญ๊ณผ ๋์ฐฉ์ญ์ด ์ผ์นํฉ๋๋ค.");
+ }
+ }
+} | Java | ์ ๊ทผ์ ํ์๊ฐ ์๋ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,38 @@
+package nextstep.subway.line.domain;
+
+import java.util.ArrayList;
+import java.util.List;
+import nextstep.subway.station.domain.Station;
+import org.jgrapht.GraphPath;
+import org.jgrapht.alg.shortestpath.DijkstraShortestPath;
+import org.jgrapht.graph.DefaultWeightedEdge;
+import org.jgrapht.graph.WeightedMultigraph;
+
+public class Lines {
+
+ List<Line> lines = new ArrayList<>();
+
+ public Lines(List<Line> lines) {
+ this.lines = lines;
+ }
+
+ public GraphPath minPath(Station sourceStation, Station targetStation) {
+
+ validatePath(sourceStation, targetStation);
+ WeightedMultigraph<Station, DefaultWeightedEdge> graph = new WeightedMultigraph(DefaultWeightedEdge.class);
+
+ for (Line line : lines) {
+ line.addPathInfo(graph);
+ }
+
+ DijkstraShortestPath dijkstraShortestPath = new DijkstraShortestPath(graph);
+
+ return dijkstraShortestPath.getPath(sourceStation, targetStation);
+ }
+
+ private void validatePath(Station sourceStation, Station targetStation){
+ if(sourceStation.equals(targetStation)){
+ throw new IllegalArgumentException("๊ฒฝ๋ก ์์์ญ๊ณผ ๋์ฐฉ์ญ์ด ์ผ์นํฉ๋๋ค.");
+ }
+ }
+} | Java | ๋์ฌ๊ตฌ๋ก ๋ฉ์๋๋ฅผ ํํํด๋ณด๋ ๊ฒ์ ์ด๋จ๊น์...? ๊ทธ๋ฆฌ๊ณ ํน์ ์ ๋๋ฆญ์ ์์ฐ์๋ ์ด์ ๊ฐ ์์ผ์ค๊น์...? |
@@ -6,9 +6,11 @@
import javax.persistence.CascadeType;
import javax.persistence.Embeddable;
import javax.persistence.OneToMany;
-import nextstep.subway.SectionsNotAddedException;
-import nextstep.subway.SectionsNotRemovedException;
+import nextstep.subway.line.exception.SectionsNotAddedException;
+import nextstep.subway.line.exception.SectionsNotRemovedException;
import nextstep.subway.station.domain.Station;
+import org.jgrapht.graph.DefaultWeightedEdge;
+import org.jgrapht.graph.WeightedMultigraph;
@Embeddable
public class Sections {
@@ -34,41 +36,36 @@ public void requestAddSection(Section section) {
sections.add(section);
return;
}
- checkExistsStation(section, section.getUpStation(), section.getDownStation());
+ checkExistsStation(section);
}
- private void checkExistsStation(Section section, Station upStation, Station downStation) {
- boolean upMatchesLineUp = stationExistsInUp(upStation);
- boolean downMatchsLineDown = stationExistsInDown(downStation);
- boolean matchesAtFront = stationExistsInUp(downStation);
- boolean matchesAtBack = stationExistsInDown(upStation);
- if (!upMatchesLineUp && !matchesAtFront && !matchesAtBack && !downMatchsLineDown) {
+ private void checkExistsStation(Section section) {
+ boolean upMatchesLineUp = stationExistsInUp(section.getUpStation());
+ boolean downMatchesLineDown = stationExistsInDown(section.getDownStation());
+ boolean matchesAtEnd = stationExistsAtEnd(section);
+
+ if (!upMatchesLineUp && !downMatchesLineDown && !matchesAtEnd) {
throw new SectionsNotAddedException("๊ตฌ๊ฐ ์ค ์ด๋ ํ ์ญ๋ ํ์ฌ ๊ตฌ๊ฐ์ ์์ต๋๋ค.");
}
- if (upMatchesLineUp && downMatchsLineDown) {
+ if (upMatchesLineUp && downMatchesLineDown) {
throw new SectionsNotAddedException("์ด๋ฏธ ๋ฑ๋ก๋ ๊ตฌ๊ฐ ์
๋๋ค.");
}
- addSectionToMatchStation(section, upStation, downStation, upMatchesLineUp, downMatchsLineDown, matchesAtFront,
- matchesAtBack);
-
+ addSectionToMatchStation(section, upMatchesLineUp, downMatchesLineDown);
}
- private void addSectionToMatchStation(Section section, Station upStation, Station downStation,
- boolean upMatchesLineUp, boolean downMatchsLineDown, boolean matchesAtFront,
- boolean matchesAtBack) {
+ private void addSectionToMatchStation(Section section, boolean upMatchesLineUp, boolean downMatchsLineDown) {
+ Station upStation = section.getUpStation();
+ Station downStation = section.getDownStation();
if (upMatchesLineUp) {
- addUpStationExists(section, upStation, downStation, section.getDistance());
- return;
+ updateUpStationMatch(section, upStation, downStation, section.getDistance());
}
if (downMatchsLineDown) {
- addDownStationExists(section, upStation, downStation, section.getDistance());
- return;
+ updateDownStatioMatch(section, upStation, downStation, section.getDistance());
}
- if (matchesAtFront || matchesAtBack) {
- sections.add(section);
- }
+ //์์ชฝ ๋์ ๋ํด์ง ๊ฒฝ์ฐ
+ sections.add(section);
}
private boolean stationExistsInUp(Station station) {
@@ -79,33 +76,40 @@ private boolean stationExistsInDown(Station station) {
return sections.stream().anyMatch(section -> section.getDownStation().equals(station));
}
+ private boolean stationExistsAtEnd(Section section) {
+ return sections.stream().anyMatch(
+ sectionIterate -> sectionIterate.getDownStation().equals(section.getUpStation())
+ || sectionIterate.getUpStation().equals(section.getDownStation()));
+ }
- private void addUpStationExists(Section section, Station upStation, Station downStation, int distance) {
+ private void updateUpStationMatch(Section section, Station upStation, Station downStation, int distance) {
sections.stream().filter(sectionIterate -> upStation.equals(sectionIterate.getUpStation())).findFirst()
.ifPresent(sectionIterate -> sectionIterate.updateUpStation(downStation, distance));
- sections.add(section);
}
- private void addDownStationExists(Section section, Station upStation, Station downStation, int distance) {
+ private void updateDownStatioMatch(Section section, Station upStation, Station downStation, int distance) {
sections.stream().filter(sectionIterate -> downStation.equals(sectionIterate.getDownStation())).findFirst()
.ifPresent(it -> it.updateDownStation(upStation, distance));
- sections.add(section);
}
+
public void removeLineStation(Station station, Line line) {
if (sections.size() <= ONE) {
throw new SectionsNotRemovedException("ํ์ฌ ๊ตฌ๊ฐ์ด ํ๋๋ฐ์ ์์ต๋๋ค.");
}
- Optional<Section> upLineStation = sections.stream().filter(it -> it.getUpStation() == station).findFirst();
- Optional<Section> downLineStation = sections.stream().filter(it -> it.getDownStation() == station).findFirst();
+ Optional<Section> upLineStation = sections.stream().filter(section -> section.getUpStation().equals(station))
+ .findFirst();
+ Optional<Section> downLineStation = sections.stream()
+ .filter(section -> section.getDownStation().equals(station)).findFirst();
connectFrontBackSection(line, upLineStation, downLineStation);
- upLineStation.ifPresent(it -> sections.remove(it));
- downLineStation.ifPresent(it -> sections.remove(it));
+ upLineStation.ifPresent(section -> sections.remove(section));
+ downLineStation.ifPresent(section -> sections.remove(section));
}
- private void connectFrontBackSection(Line line, Optional<Section> upLineStation, Optional<Section> downLineStation) {
+ private void connectFrontBackSection(Line line, Optional<Section> upLineStation,
+ Optional<Section> downLineStation) {
if (upLineStation.isPresent() && downLineStation.isPresent()) {
Station newUpStation = downLineStation.get().getUpStation();
Station newDownStation = upLineStation.get().getDownStation();
@@ -114,4 +118,11 @@ private void connectFrontBackSection(Line line, Optional<Section> upLineStation,
sections.add(new Section(line, newUpStation, newDownStation, newDistance));
}
}
+
+ public void addGraphEdge(WeightedMultigraph<Station, DefaultWeightedEdge> graph) {
+ for (Section section : sections) {
+ section.addGraphEdge(graph);
+ }
+ }
+
}
\ No newline at end of file | Java | ์ด๋ถ๋ถ๋ Section์ ๋ฉ์์ง๋ฅผ ๋์ ธ์ ํ์ธํด๋ณผ ์ ์์ ๊ฒ ๊ฐ์ต๋๋ค |
@@ -6,9 +6,11 @@
import javax.persistence.CascadeType;
import javax.persistence.Embeddable;
import javax.persistence.OneToMany;
-import nextstep.subway.SectionsNotAddedException;
-import nextstep.subway.SectionsNotRemovedException;
+import nextstep.subway.line.exception.SectionsNotAddedException;
+import nextstep.subway.line.exception.SectionsNotRemovedException;
import nextstep.subway.station.domain.Station;
+import org.jgrapht.graph.DefaultWeightedEdge;
+import org.jgrapht.graph.WeightedMultigraph;
@Embeddable
public class Sections {
@@ -34,41 +36,36 @@ public void requestAddSection(Section section) {
sections.add(section);
return;
}
- checkExistsStation(section, section.getUpStation(), section.getDownStation());
+ checkExistsStation(section);
}
- private void checkExistsStation(Section section, Station upStation, Station downStation) {
- boolean upMatchesLineUp = stationExistsInUp(upStation);
- boolean downMatchsLineDown = stationExistsInDown(downStation);
- boolean matchesAtFront = stationExistsInUp(downStation);
- boolean matchesAtBack = stationExistsInDown(upStation);
- if (!upMatchesLineUp && !matchesAtFront && !matchesAtBack && !downMatchsLineDown) {
+ private void checkExistsStation(Section section) {
+ boolean upMatchesLineUp = stationExistsInUp(section.getUpStation());
+ boolean downMatchesLineDown = stationExistsInDown(section.getDownStation());
+ boolean matchesAtEnd = stationExistsAtEnd(section);
+
+ if (!upMatchesLineUp && !downMatchesLineDown && !matchesAtEnd) {
throw new SectionsNotAddedException("๊ตฌ๊ฐ ์ค ์ด๋ ํ ์ญ๋ ํ์ฌ ๊ตฌ๊ฐ์ ์์ต๋๋ค.");
}
- if (upMatchesLineUp && downMatchsLineDown) {
+ if (upMatchesLineUp && downMatchesLineDown) {
throw new SectionsNotAddedException("์ด๋ฏธ ๋ฑ๋ก๋ ๊ตฌ๊ฐ ์
๋๋ค.");
}
- addSectionToMatchStation(section, upStation, downStation, upMatchesLineUp, downMatchsLineDown, matchesAtFront,
- matchesAtBack);
-
+ addSectionToMatchStation(section, upMatchesLineUp, downMatchesLineDown);
}
- private void addSectionToMatchStation(Section section, Station upStation, Station downStation,
- boolean upMatchesLineUp, boolean downMatchsLineDown, boolean matchesAtFront,
- boolean matchesAtBack) {
+ private void addSectionToMatchStation(Section section, boolean upMatchesLineUp, boolean downMatchsLineDown) {
+ Station upStation = section.getUpStation();
+ Station downStation = section.getDownStation();
if (upMatchesLineUp) {
- addUpStationExists(section, upStation, downStation, section.getDistance());
- return;
+ updateUpStationMatch(section, upStation, downStation, section.getDistance());
}
if (downMatchsLineDown) {
- addDownStationExists(section, upStation, downStation, section.getDistance());
- return;
+ updateDownStatioMatch(section, upStation, downStation, section.getDistance());
}
- if (matchesAtFront || matchesAtBack) {
- sections.add(section);
- }
+ //์์ชฝ ๋์ ๋ํด์ง ๊ฒฝ์ฐ
+ sections.add(section);
}
private boolean stationExistsInUp(Station station) {
@@ -79,33 +76,40 @@ private boolean stationExistsInDown(Station station) {
return sections.stream().anyMatch(section -> section.getDownStation().equals(station));
}
+ private boolean stationExistsAtEnd(Section section) {
+ return sections.stream().anyMatch(
+ sectionIterate -> sectionIterate.getDownStation().equals(section.getUpStation())
+ || sectionIterate.getUpStation().equals(section.getDownStation()));
+ }
- private void addUpStationExists(Section section, Station upStation, Station downStation, int distance) {
+ private void updateUpStationMatch(Section section, Station upStation, Station downStation, int distance) {
sections.stream().filter(sectionIterate -> upStation.equals(sectionIterate.getUpStation())).findFirst()
.ifPresent(sectionIterate -> sectionIterate.updateUpStation(downStation, distance));
- sections.add(section);
}
- private void addDownStationExists(Section section, Station upStation, Station downStation, int distance) {
+ private void updateDownStatioMatch(Section section, Station upStation, Station downStation, int distance) {
sections.stream().filter(sectionIterate -> downStation.equals(sectionIterate.getDownStation())).findFirst()
.ifPresent(it -> it.updateDownStation(upStation, distance));
- sections.add(section);
}
+
public void removeLineStation(Station station, Line line) {
if (sections.size() <= ONE) {
throw new SectionsNotRemovedException("ํ์ฌ ๊ตฌ๊ฐ์ด ํ๋๋ฐ์ ์์ต๋๋ค.");
}
- Optional<Section> upLineStation = sections.stream().filter(it -> it.getUpStation() == station).findFirst();
- Optional<Section> downLineStation = sections.stream().filter(it -> it.getDownStation() == station).findFirst();
+ Optional<Section> upLineStation = sections.stream().filter(section -> section.getUpStation().equals(station))
+ .findFirst();
+ Optional<Section> downLineStation = sections.stream()
+ .filter(section -> section.getDownStation().equals(station)).findFirst();
connectFrontBackSection(line, upLineStation, downLineStation);
- upLineStation.ifPresent(it -> sections.remove(it));
- downLineStation.ifPresent(it -> sections.remove(it));
+ upLineStation.ifPresent(section -> sections.remove(section));
+ downLineStation.ifPresent(section -> sections.remove(section));
}
- private void connectFrontBackSection(Line line, Optional<Section> upLineStation, Optional<Section> downLineStation) {
+ private void connectFrontBackSection(Line line, Optional<Section> upLineStation,
+ Optional<Section> downLineStation) {
if (upLineStation.isPresent() && downLineStation.isPresent()) {
Station newUpStation = downLineStation.get().getUpStation();
Station newDownStation = upLineStation.get().getDownStation();
@@ -114,4 +118,11 @@ private void connectFrontBackSection(Line line, Optional<Section> upLineStation,
sections.add(new Section(line, newUpStation, newDownStation, newDistance));
}
}
+
+ public void addGraphEdge(WeightedMultigraph<Station, DefaultWeightedEdge> graph) {
+ for (Section section : sections) {
+ section.addGraphEdge(graph);
+ }
+ }
+
}
\ No newline at end of file | Java | ์ฌ๊ธฐ๊น์ง ํผ๋๋ฐฑ ๋ฐ์ ์ข๋ค์ ใ
ใ
๐ |
@@ -0,0 +1,38 @@
+package nextstep.subway.path.application;
+
+import nextstep.subway.station.exception.StationNotFoundException;
+import nextstep.subway.line.domain.LineRepository;
+import nextstep.subway.line.domain.Lines;
+import nextstep.subway.path.dto.PathResponse;
+import nextstep.subway.station.domain.Station;
+import nextstep.subway.station.domain.StationRepository;
+import org.jgrapht.GraphPath;
+import org.springframework.stereotype.Service;
+
+@Service
+public class PathService {
+
+ private final StationRepository stationRepository;
+ private final LineRepository lineRepository;
+
+ public PathService(StationRepository stationRepository, LineRepository lineRepository) {
+ this.stationRepository = stationRepository;
+ this.lineRepository = lineRepository;
+ }
+
+ public PathResponse minPath(Long sourceStationId, Long targetStationId) {
+ System.out.println("PathService.minPath");
+
+ Station sourceStation = stationRepository.findById(sourceStationId)
+ .orElseThrow(() -> new StationNotFoundException("๊ฒฝ๋ก ์์์ญ์ด ์กด์ฌํ์ง ์์ต๋๋ค."));
+ Station targetStation = stationRepository.findById(targetStationId)
+ .orElseThrow(() -> new StationNotFoundException("๊ฒฝ๋ก ๋์ฐฉ์ญ์ด ์กด์ฌํ์ง ์์ต๋๋ค."));
+
+ Lines lines = new Lines(lineRepository.findAll());
+ GraphPath graphPath = lines.minPath(sourceStation, targetStation);
+
+ PathResponse pathResponse = new PathResponse(graphPath.getVertexList(), (int) graphPath.getWeight());
+
+ return pathResponse;
+ }
+} | Java | ์ฌ๊ธฐ์ ํน์ System ํจ์๋ฅผ ์ฐ์ ์ด์ ๊ฐ ์์๊น์...? Sysytem ํจ์๋ ๋ฆฌ์์ค๋ฅผ ๋ง์ด ๋จน์ด์ ์ต๋ํ ์ฌ์ฉํ์ง ์๋ ๊ฒ์ด ์ข์ต๋๋ค. |
@@ -0,0 +1,38 @@
+package nextstep.subway.path.application;
+
+import nextstep.subway.station.exception.StationNotFoundException;
+import nextstep.subway.line.domain.LineRepository;
+import nextstep.subway.line.domain.Lines;
+import nextstep.subway.path.dto.PathResponse;
+import nextstep.subway.station.domain.Station;
+import nextstep.subway.station.domain.StationRepository;
+import org.jgrapht.GraphPath;
+import org.springframework.stereotype.Service;
+
+@Service
+public class PathService {
+
+ private final StationRepository stationRepository;
+ private final LineRepository lineRepository;
+
+ public PathService(StationRepository stationRepository, LineRepository lineRepository) {
+ this.stationRepository = stationRepository;
+ this.lineRepository = lineRepository;
+ }
+
+ public PathResponse minPath(Long sourceStationId, Long targetStationId) {
+ System.out.println("PathService.minPath");
+
+ Station sourceStation = stationRepository.findById(sourceStationId)
+ .orElseThrow(() -> new StationNotFoundException("๊ฒฝ๋ก ์์์ญ์ด ์กด์ฌํ์ง ์์ต๋๋ค."));
+ Station targetStation = stationRepository.findById(targetStationId)
+ .orElseThrow(() -> new StationNotFoundException("๊ฒฝ๋ก ๋์ฐฉ์ญ์ด ์กด์ฌํ์ง ์์ต๋๋ค."));
+
+ Lines lines = new Lines(lineRepository.findAll());
+ GraphPath graphPath = lines.minPath(sourceStation, targetStation);
+
+ PathResponse pathResponse = new PathResponse(graphPath.getVertexList(), (int) graphPath.getWeight());
+
+ return pathResponse;
+ }
+} | Java | Repository ์กฐํํ๋ ๋ถ๋ถ์ด ์๋๋ฐ readOnly ์ต์
์ ์ฃผ๋ ๊ฒ์ ์ด๋จ๊น์....? |
@@ -1,9 +1,111 @@
package nextstep.subway.path;
+import static nextstep.subway.line.acceptance.LineAcceptanceTest.์งํ์ฒ _๋
ธ์ _๋ฑ๋ก๋์ด_์์;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import io.restassured.RestAssured;
+import io.restassured.response.ExtractableResponse;
+import io.restassured.response.Response;
+import java.util.HashMap;
+import java.util.Map;
import nextstep.subway.AcceptanceTest;
+import nextstep.subway.line.acceptance.LineSectionAcceptanceTest;
+import nextstep.subway.line.dto.LineRequest;
+import nextstep.subway.line.dto.LineResponse;
+import nextstep.subway.station.StationAcceptanceTest;
+import nextstep.subway.station.dto.StationResponse;
+import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
@DisplayName("์งํ์ฒ ๊ฒฝ๋ก ์กฐํ")
public class PathAcceptanceTest extends AcceptanceTest {
+
+ private LineResponse ์ ๋ถ๋น์ ;
+ private LineResponse ์ดํธ์ ;
+ private LineResponse ์ผํธ์ ;
+ private StationResponse ๊ฐ๋จ์ญ;
+ private StationResponse ์์ฌ์ญ;
+ private StationResponse ๊ต๋์ญ;
+ private StationResponse ๋จ๋ถํฐ๋ฏธ๋์ญ;
+
+ /**
+ * ๊ต๋์ญ --- *2ํธ์ * --- ๊ฐ๋จ์ญ
+ * | |
+ * *3ํธ์ * *์ ๋ถ๋น์ *
+ * | |
+ * ๋จ๋ถํฐ๋ฏธ๋์ญ --- *3ํธ์ * --- ์์ฌ
+ */
+ @BeforeEach
+ public void setUp() {
+ super.setUp();
+
+ ๊ฐ๋จ์ญ = StationAcceptanceTest.์งํ์ฒ ์ญ_๋ฑ๋ก๋์ด_์์("๊ฐ๋จ์ญ").as(StationResponse.class);
+ ์์ฌ์ญ = StationAcceptanceTest.์งํ์ฒ ์ญ_๋ฑ๋ก๋์ด_์์("์์ฌ์ญ").as(StationResponse.class);
+ ๊ต๋์ญ = StationAcceptanceTest.์งํ์ฒ ์ญ_๋ฑ๋ก๋์ด_์์("๊ต๋์ญ").as(StationResponse.class);
+ ๋จ๋ถํฐ๋ฏธ๋์ญ = StationAcceptanceTest.์งํ์ฒ ์ญ_๋ฑ๋ก๋์ด_์์("๋จ๋ถํฐ๋ฏธ๋์ญ").as(StationResponse.class);
+
+ ์ ๋ถ๋น์ = ์งํ์ฒ _๋
ธ์ _๋ฑ๋ก๋์ด_์์(new LineRequest("์ ๋ถ๋น์ ", "bg-red-600", ๊ฐ๋จ์ญ.getId(), ์์ฌ์ญ.getId(), 10)).as(
+ LineResponse.class);
+ ์ดํธ์ = ์งํ์ฒ _๋
ธ์ _๋ฑ๋ก๋์ด_์์(new LineRequest("์ดํธ์ ", "bg-red-600", ๊ต๋์ญ.getId(), ๊ฐ๋จ์ญ.getId(), 10)).as(LineResponse.class);
+ ์ผํธ์ = ์งํ์ฒ _๋
ธ์ _๋ฑ๋ก๋์ด_์์(new LineRequest("์ผํธ์ ", "bg-red-600", ๊ต๋์ญ.getId(), ์์ฌ์ญ.getId(), 5)).as(LineResponse.class);
+
+ ์งํ์ฒ _๋
ธ์ ์_์งํ์ฒ ์ญ_๋ฑ๋ก๋์ด_์์(์ผํธ์ , ๊ต๋์ญ, ๋จ๋ถํฐ๋ฏธ๋์ญ, 3);
+ }
+
+ private ExtractableResponse<Response> ์งํ์ฒ _๋
ธ์ ์_์งํ์ฒ ์ญ_๋ฑ๋ก๋์ด_์์(LineResponse lineResponse, StationResponse upStation,
+ StationResponse downStation,
+ int distance) {
+ return LineSectionAcceptanceTest.์งํ์ฒ _๋
ธ์ ์_์งํ์ฒ ์ญ_๋ฑ๋ก_์์ฒญ(lineResponse,
+ upStation, downStation, distance);
+ }
+
+ @Test
+ @DisplayName("๊ต๋์ญ-์์ฌ์ญ ์ต๋จ๊ฒฝ๋ก ์กฐํํ๊ธฐ (๊ต๋์ญ-๋จ๋ถํฐ๋ฏธ๋์ญ-์์ฌ์ญ)")
+ public void findMinPath() {
+ ExtractableResponse<Response> ์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญ๊ฒฐ๊ณผ = ์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญํ๊ธฐ(๊ต๋์ญ, ์์ฌ์ญ);
+ ์ต๋จ_๊ฒฝ๋ก_๋ชฉ๋ก_๊ฒ์ฆ(์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญ๊ฒฐ๊ณผ, 5, "๊ต๋์ญ","๋จ๋ถํฐ๋ฏธ๋์ญ", "์์ฌ์ญ");
+ }
+
+
+ @Test
+ @DisplayName("๊ฒฝ๋ก ์์์ญ ๋์ฐฉ์ญ ์ผ์น ์กฐํ ์๋ฌ ํ์ธ")
+ public void findMinPathSourceTargetSame() {
+ ExtractableResponse<Response> ์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญ๊ฒฐ๊ณผ = ์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญํ๊ธฐ(๊ต๋์ญ, ๊ต๋์ญ);
+ ์ต๋จ_๊ฒฝ๋ก_๋ชฉ๋ก_์์ฒญ๊ฒฐ๊ณผ_์๋ฌ(์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญ๊ฒฐ๊ณผ);
+ }
+
+ @Test
+ @DisplayName("๊ฒฝ๋ก ์กฐํ์ ๋ฏธ์กด์ฌ ์ญ ์๋ฌ ํ์ธ")
+ public void findMinPathNotExsistStation() {
+ ExtractableResponse<Response> ์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญ๊ฒฐ๊ณผ = ์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญํ๊ธฐ(new StationResponse(), new StationResponse());
+ ์ต๋จ_๊ฒฝ๋ก_๋ชฉ๋ก_์์ฒญ๊ฒฐ๊ณผ_์๋ฌ(์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญ๊ฒฐ๊ณผ);
+ }
+
+ private void ์ต๋จ_๊ฒฝ๋ก_๋ชฉ๋ก_์์ฒญ๊ฒฐ๊ณผ_์๋ฌ(ExtractableResponse<Response> response) {
+ assertThat(response.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST.value());
+ }
+
+ private void ์ต๋จ_๊ฒฝ๋ก_๋ชฉ๋ก_๊ฒ์ฆ(ExtractableResponse<Response> response,int distance, String... stationNames) {
+ assertThat(response.jsonPath().getInt("distance")).isEqualTo(distance);
+ assertThat(response.jsonPath().getList("stations.name")).containsExactly(stationNames);
+ }
+
+ private ExtractableResponse<Response> ์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญํ๊ธฐ(StationResponse source, StationResponse target) {
+ Map<String, Long> param = new HashMap<>();
+ param.put("source", source.getId());
+ param.put("target", target.getId());
+
+ return RestAssured
+ .given().log().all()
+ .queryParams(param)
+ .contentType(MediaType.APPLICATION_JSON_VALUE)
+ .when().get("/paths")
+ .then().log().all()
+ .extract();
+ }
+
} | Java | ์ธ์ํ
์คํธ ์ข์ต๋๋ค ๐ ๋ค๋ง ์ด๋ฒ์ ์๋ก๋ง๋์ Lines์ ๋ํ ๋จ์ ํ
์คํธ, PathService์ ๋ํ ๋จ์ํ
์คํธ๋ ์ถ๊ฐ๋๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค!
Lines์ ๊ฒฝ์ฐ ์ค์ ์ธ๋ถ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ฌ์ฉํ๋ฏ๋ก ํด๋น ์ค์ ๊ฐ์ฒด๋ฅผ ์ด์ฉํ์ฌ ํ
์คํธ๋ฅผ ์์ฑํ๊ณ , PathService์ ๊ฒฝ์ฐ๋ ์ธ๋ถ ์์กด์ฑ์ Mocking ํ ๋จ์ ํ
์คํธ๋ฅผ ์์ฑํด๋ณด๋ ๊ฒ๋ ์ข์ ๊ณต๋ถ๊ฐ ๋ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -1,9 +1,111 @@
package nextstep.subway.path;
+import static nextstep.subway.line.acceptance.LineAcceptanceTest.์งํ์ฒ _๋
ธ์ _๋ฑ๋ก๋์ด_์์;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import io.restassured.RestAssured;
+import io.restassured.response.ExtractableResponse;
+import io.restassured.response.Response;
+import java.util.HashMap;
+import java.util.Map;
import nextstep.subway.AcceptanceTest;
+import nextstep.subway.line.acceptance.LineSectionAcceptanceTest;
+import nextstep.subway.line.dto.LineRequest;
+import nextstep.subway.line.dto.LineResponse;
+import nextstep.subway.station.StationAcceptanceTest;
+import nextstep.subway.station.dto.StationResponse;
+import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
@DisplayName("์งํ์ฒ ๊ฒฝ๋ก ์กฐํ")
public class PathAcceptanceTest extends AcceptanceTest {
+
+ private LineResponse ์ ๋ถ๋น์ ;
+ private LineResponse ์ดํธ์ ;
+ private LineResponse ์ผํธ์ ;
+ private StationResponse ๊ฐ๋จ์ญ;
+ private StationResponse ์์ฌ์ญ;
+ private StationResponse ๊ต๋์ญ;
+ private StationResponse ๋จ๋ถํฐ๋ฏธ๋์ญ;
+
+ /**
+ * ๊ต๋์ญ --- *2ํธ์ * --- ๊ฐ๋จ์ญ
+ * | |
+ * *3ํธ์ * *์ ๋ถ๋น์ *
+ * | |
+ * ๋จ๋ถํฐ๋ฏธ๋์ญ --- *3ํธ์ * --- ์์ฌ
+ */
+ @BeforeEach
+ public void setUp() {
+ super.setUp();
+
+ ๊ฐ๋จ์ญ = StationAcceptanceTest.์งํ์ฒ ์ญ_๋ฑ๋ก๋์ด_์์("๊ฐ๋จ์ญ").as(StationResponse.class);
+ ์์ฌ์ญ = StationAcceptanceTest.์งํ์ฒ ์ญ_๋ฑ๋ก๋์ด_์์("์์ฌ์ญ").as(StationResponse.class);
+ ๊ต๋์ญ = StationAcceptanceTest.์งํ์ฒ ์ญ_๋ฑ๋ก๋์ด_์์("๊ต๋์ญ").as(StationResponse.class);
+ ๋จ๋ถํฐ๋ฏธ๋์ญ = StationAcceptanceTest.์งํ์ฒ ์ญ_๋ฑ๋ก๋์ด_์์("๋จ๋ถํฐ๋ฏธ๋์ญ").as(StationResponse.class);
+
+ ์ ๋ถ๋น์ = ์งํ์ฒ _๋
ธ์ _๋ฑ๋ก๋์ด_์์(new LineRequest("์ ๋ถ๋น์ ", "bg-red-600", ๊ฐ๋จ์ญ.getId(), ์์ฌ์ญ.getId(), 10)).as(
+ LineResponse.class);
+ ์ดํธ์ = ์งํ์ฒ _๋
ธ์ _๋ฑ๋ก๋์ด_์์(new LineRequest("์ดํธ์ ", "bg-red-600", ๊ต๋์ญ.getId(), ๊ฐ๋จ์ญ.getId(), 10)).as(LineResponse.class);
+ ์ผํธ์ = ์งํ์ฒ _๋
ธ์ _๋ฑ๋ก๋์ด_์์(new LineRequest("์ผํธ์ ", "bg-red-600", ๊ต๋์ญ.getId(), ์์ฌ์ญ.getId(), 5)).as(LineResponse.class);
+
+ ์งํ์ฒ _๋
ธ์ ์_์งํ์ฒ ์ญ_๋ฑ๋ก๋์ด_์์(์ผํธ์ , ๊ต๋์ญ, ๋จ๋ถํฐ๋ฏธ๋์ญ, 3);
+ }
+
+ private ExtractableResponse<Response> ์งํ์ฒ _๋
ธ์ ์_์งํ์ฒ ์ญ_๋ฑ๋ก๋์ด_์์(LineResponse lineResponse, StationResponse upStation,
+ StationResponse downStation,
+ int distance) {
+ return LineSectionAcceptanceTest.์งํ์ฒ _๋
ธ์ ์_์งํ์ฒ ์ญ_๋ฑ๋ก_์์ฒญ(lineResponse,
+ upStation, downStation, distance);
+ }
+
+ @Test
+ @DisplayName("๊ต๋์ญ-์์ฌ์ญ ์ต๋จ๊ฒฝ๋ก ์กฐํํ๊ธฐ (๊ต๋์ญ-๋จ๋ถํฐ๋ฏธ๋์ญ-์์ฌ์ญ)")
+ public void findMinPath() {
+ ExtractableResponse<Response> ์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญ๊ฒฐ๊ณผ = ์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญํ๊ธฐ(๊ต๋์ญ, ์์ฌ์ญ);
+ ์ต๋จ_๊ฒฝ๋ก_๋ชฉ๋ก_๊ฒ์ฆ(์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญ๊ฒฐ๊ณผ, 5, "๊ต๋์ญ","๋จ๋ถํฐ๋ฏธ๋์ญ", "์์ฌ์ญ");
+ }
+
+
+ @Test
+ @DisplayName("๊ฒฝ๋ก ์์์ญ ๋์ฐฉ์ญ ์ผ์น ์กฐํ ์๋ฌ ํ์ธ")
+ public void findMinPathSourceTargetSame() {
+ ExtractableResponse<Response> ์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญ๊ฒฐ๊ณผ = ์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญํ๊ธฐ(๊ต๋์ญ, ๊ต๋์ญ);
+ ์ต๋จ_๊ฒฝ๋ก_๋ชฉ๋ก_์์ฒญ๊ฒฐ๊ณผ_์๋ฌ(์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญ๊ฒฐ๊ณผ);
+ }
+
+ @Test
+ @DisplayName("๊ฒฝ๋ก ์กฐํ์ ๋ฏธ์กด์ฌ ์ญ ์๋ฌ ํ์ธ")
+ public void findMinPathNotExsistStation() {
+ ExtractableResponse<Response> ์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญ๊ฒฐ๊ณผ = ์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญํ๊ธฐ(new StationResponse(), new StationResponse());
+ ์ต๋จ_๊ฒฝ๋ก_๋ชฉ๋ก_์์ฒญ๊ฒฐ๊ณผ_์๋ฌ(์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญ๊ฒฐ๊ณผ);
+ }
+
+ private void ์ต๋จ_๊ฒฝ๋ก_๋ชฉ๋ก_์์ฒญ๊ฒฐ๊ณผ_์๋ฌ(ExtractableResponse<Response> response) {
+ assertThat(response.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST.value());
+ }
+
+ private void ์ต๋จ_๊ฒฝ๋ก_๋ชฉ๋ก_๊ฒ์ฆ(ExtractableResponse<Response> response,int distance, String... stationNames) {
+ assertThat(response.jsonPath().getInt("distance")).isEqualTo(distance);
+ assertThat(response.jsonPath().getList("stations.name")).containsExactly(stationNames);
+ }
+
+ private ExtractableResponse<Response> ์ต๋จ๊ฒฝ๋ก์กฐํ_์์ฒญํ๊ธฐ(StationResponse source, StationResponse target) {
+ Map<String, Long> param = new HashMap<>();
+ param.put("source", source.getId());
+ param.put("target", target.getId());
+
+ return RestAssured
+ .given().log().all()
+ .queryParams(param)
+ .contentType(MediaType.APPLICATION_JSON_VALUE)
+ .when().get("/paths")
+ .then().log().all()
+ .extract();
+ }
+
} | Java | ์ฐ๊ฒฐ๋์ด ์์ง ์์ ์ญ์ ๋ํ ์ต๋จ๊ฑฐ๋ฆฌ ์กฐํ์ ๊ฒฝ์ฐ์๋ ํ
์คํธ๋ฅผ ์ถ๊ฐํด๋ณด๋ ๊ฒ์ ์ด๋จ๊น์...? |
@@ -55,6 +55,7 @@ captures/
.idea/caches
# Keystore files
+keystore.properties
# Uncomment the following line if you do not want to check your keystore files in.
#*.jks
@@ -100,3 +101,6 @@ $RECYCLE.BIN/
# Windows shortcuts
*.lnk
+app/src/main/java/kr/co/connect/boostcamp/livewhere/ui/bookmark/
+app/src/main/java/kr/co/connect/boostcamp/livewhere/ui/search/
+app/src/main/res/layout-v26/ | Unknown | #82 ์์
์ด ์ด๋ค๊ฑด์ง ํ์คํ ๋ฆฌ๊ฐ ์์ด์ ์ ์ถ๊ฐ๋์๋์ง ๋ชจ๋ฅด๊ฒ ๋๋ฐ
1) ๋ณด์๊ณผ ๊ด๋ จ๋์ด ๊ณต์ ๋์ง ์์์ผ ํ๋ ํ์ผ
2) ๊ฐ์ธ๋ณ ํ๊ฒฝ์ค์ ํ์ผ
3) ์บ์ ํ์ผ
4) ์ฐ๋ ๊ธฐ ํ์ผ
๋ฑ์ ์ฌ์ ๊ฐ ์๋๋ผ๋ฉด .gitignore์ ๋ค์ด๊ฐ๋๊ฒ ๋ถ์ ์ ํด ๋ณด์
๋๋ค.
ํด๋น ํด๋๋ฅผ git์์ ์ ๊ฑฐํ๋ ค๋ค ํธ๋ฒ์ ์ด๊ฒ ์๋๊น ์ถ์ธก์ด ๋๋๋ฐ ์ฌ๋ฐ๋ฅด์ง ๋ชปํ ๋ฐฉ๋ฒ์ธ๊ฑฐ ๊ฐ์์. |
@@ -0,0 +1,68 @@
+# ์์ธ ์ด์ด <img width="85" alt="kakaotalk_20190212_204520833" src="https://user-images.githubusercontent.com/22374750/52834626-1efe2080-3126-11e9-92c3-66ac08c1f2c9.png">
+
+
+[](https://insert-koin.io)
+[](https://app.zeplin.io/project/5c4db2597a8bebbfe8be9d39/dashboard)
+
+[](https://github.com/amitshekhariitbhu/RxJava2-Android-Samples)
+[](https://developer.android.com/topic/libraries/architecture/room.html)
+[](https://developer.android.com/topic/libraries/architecture/livedata.html)
+
+booscamp3_Cํ์ ์์ธ์ด์ด repository์
๋๋ค. ํด๋น ํ๋ก์ ํธ๋ MVVM๊ธฐ๋ฐ์ Androidํ๋ก์ ํธ์
๋๋ค.
+์์กด์ฑ ์ฃผ์
์ ์ํด์ koin์ด ์ฌ์ฉ๋์๊ณ , RxJava, Room, LiveData, MotionLayout๋ฑ ๊พธ์คํ ํ์ต์ ์ํด์ ์งํ๋๊ณ ์์ต๋๋ค.
+<hr/>
+
+#### ํ์ ์๊ฐ : ๋ฌธ๋ณํ, ์ ์ง์, ์ต์ค์(๋งํฌ ์ถ๊ฐ ์์ )
+
+์์ธ์ด์ด๋ ์์ธ์ด์ด๋ฅผ ์์ํ๋ ์ฌ๋๋ค์๊ฒ ์ฃผํ์ ๊ดํ ์ ๋ณด๋ฅผ ์ ๊ณตํ๋ ์ดํ๋ฆฌ์ผ์ด์
์
๋๋ค.
+
+<p>ํ์ฌ ์ํํธ์ ๋ํ ์ ๋ณด๋ฅผ ์ ๊ณตํ๋ ๋ค์ํ ์ดํ๋ฆฌ์ผ์ด์
์ด ์กด์ฌํ์ง๋ง, ์๋์ ์ผ๋ก ์ฃผํ์ ๊ด๋ จ๋ ์ ๋ณด๋ฅผ ์ ๊ณตํ๋ ์ดํ๋ฆฌ์ผ์ด์
์ ๋ถ์กฑํฉ๋๋ค.
+๊ทธ๋ ๊ธฐ ๋๋ฌธ์ ์ด๋ฌํ ๋ถ์กฑํ ์ ๋ณด๋ฅผ ์์ธ์ด์ด๋ผ๋ ์ดํ๋ฆฌ์ผ์ด์
์ ํตํด์ ์ฃผํ์ ๊ด๋ จ๋ ์ /์์ธ, ์ฃผ๋ณ ์ง์ญ ์ ๋ณด, ์ฃผํ ์ ๋ณด๋ฑ์ ์ ๋ณด๋ฅผ ์ ๊ณตํ๋ ค๊ณ ํฉ๋๋ค.</p>
+<hr/>
+
+
+#### ํ๋กํ ํ์
UI: [](https://app.zeplin.io/project/5c4db2597a8bebbfe8be9d39/dashboard)
+
+
+ํด๋น ํ๋ก์ ํธ๋ ํ์
ํด์ Zeplin์ ์ฌ์ฉํ์ต๋๋ค. ๊ตฌ์ฒด์ ์ธ ๋ด์ฉ์ ํด๋น ๋ฑ์ง๋ฅผ ๋๋ฅด๋ฉด ํ์ธํ ์ ์์ต๋๋ค.<br>
+์ ํฌ๋ Zeplin์ ํตํด์ Style ๊ฐ์ด๋๋ฅผ ์์ฑํ๊ณ , ๊ฐ์ข
xml์ ๊ฐ์ด๋ ๊ธฐ์ค์ ์ ํ์ต๋๋ค.
+
+#### ํจํค์ง ์๊ฐ:
+1. **api**: Retrofit์ ์ฌ์ฉํ๊ธฐ ์ํ interface๋ฅผ ๋ชจ์๋๋ ํจํค์ง์
๋๋ค.
+2. **di**: Koin์ ์ฌ์ฉํ์ฌ ์์กด์ฑ ์ฃผ์
์ ํ๊ณ , ํด๋น ํจํค์ง์ di ๊ด๋ จ ๋ชจ๋์ ๋ง๋ค์์ต๋๋ค.
+3. **firebase**: Firebase์ ๊ด๋ จํ ์ ํธ๋ฆฌํฐ์ฑ ํด๋์ค๋ฅผ ๋ชจ์๋๋ ํจํค์ง์
๋๋ค.
+4. **model**: ์ฃผ์, ๋ถ๋งํฌ, ์ง์ ๋ณด, ๊ฐ๊ฒฉ๋ฑ์ ๊ด๋ จํ ๋ฐ์ดํฐ ํด๋์ค๋ฅผ ๋ชจ์๋๋ ํจํค์ง์
๋๋ค.
+5. **repository**: ViewModel๊ณผ Model์ฌ์ด์ repositoryํจํด์ ์ฌ์ฉํด์ ๊ฐ์ข
๊ฐ์ ๋ฐ์์ค๋ ํด๋์ค๋ฅผ ๋ชจ์๋ ํจํค์ง์
๋๋ค.
+6. **ui**: View์ ํด๋นํ๋ ํด๋์ค๋ค์ ๋ชจ์๋๋ ํจํค์ง์
๋๋ค.
+7. **util**: ํ๋ก์ ํธ๋ด์์ ๊ฐ์ข
์ ํธ๋ฆฌํฐ์ฑ ํด๋์ค๋ฅผ ๋ชจ์๋๋ ํจํค์ง์
๋๋ค.
+
+### [๊ธฐํ์](https://drive.google.com/file/d/1ui4lvMc81kCAki4UVtxirsg0szLEbqD2/view?usp=sharing)
+### [์ผ์ ๊ด๋ฆฌ](https://docs.google.com/spreadsheets/d/1nQlae8ONeO42Rk9Pr0tZFxilmCsfuNRmOOc4p7cFlYY/edit?usp=sharing)
+### [UI๊ธฐํ](https://drive.google.com/file/d/13BLtMr3i-YnhjuDIkYmLRVolUX6OQnIu/view?usp=sharing)
+### [๊ธฐ๋ฅ๋ช
์ธ์](https://docs.google.com/spreadsheets/d/1Y4Xpb8lSP5qQ53e1NPewsZMmYud5io1H1SQxxZZOmY4/edit?usp=sharing)
+
+### [์๋ฒ](https://github.com/seoul42/seoul42-server)
+<hr/>
+
+## 1์ฃผ์ฐจ ์ฐ์ถ๋ฌผ
+[DOCS](https://github.com/boostcampth/boostcamp3_C/tree/dev/docs) ๋ฌธ์ ์์
(๊ธฐํ์, ๊ธฐ๋ฅ์ ์์, ํ๋ก์ ํธ ์ผ์ , Api๋ช
์ธ์)
+
+Zeplin[](https://app.zeplin.io/project/5c4db2597a8bebbfe8be9d39/dashboard)
+
+
+## 2์ฃผ์ฐจ ์ฐ์ถ๋ฌผ
+
+Seoul42 API [](https://app.zeplin.io/project/5c4db2597a8bebbfe8be9d39/dashboard)
+
+
+### 2์ฃผ์ฐจ ํ๊ณ ๋ก
+
+
+์ค์๋ ํ์ผ ์ฌ์
๋ก๋ ํ์
+
+## 3์ฃผ์ฐจ ์ฐ์ถ๋ฌผ
+
+### 3์ฃผ์ฐจ ํ๊ณ ๋ก
+
+
+ | Unknown | ์ฐธ๊ณ ํ ์ ์๋ ์ด๋ฏธ์ง์ ๋งํฌ๋ฅผ ์ ๋ฃ์ด์ฃผ์
์
์ด๋ค ํ๋ก์ ํธ์ธ์ง ๋ฐ๋ก ์ ์ ์์์ต๋๋ค.
์ข๋ค์ :+1: |
@@ -1,21 +1,54 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="kr.co.connect.boostcamp.livewhere">
-
+ xmlns:tools="http://schemas.android.com/tools" package="kr.co.connect.boostcamp.livewhere">
+ <uses-permission android:name="android.permission.INTERNET"/>
+ <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
+ <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
+ <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<application
- android:allowBackup="true"
- android:icon="@mipmap/ic_launcher"
+ android:name=".LiveApplication"
+ android:allowBackup="false"
+ android:icon="@drawable/icon_logo"
+ android:roundIcon="@drawable/icon_logo"
android:label="@string/app_name"
- android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
- <activity android:name=".MainActivity">
+
+ <uses-library android:name="org.apache.http.legacy"
+ android:required="false"/>
+
+ <meta-data
+ android:name="com.google.android.geo.API_KEY"
+ android:value="@string/key_street_view"/>
+ <activity android:name=".ui.main.SplashActivity"
+ android:theme="@style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
+ <activity android:name=".ui.login.LoginActivity">
+
+ </activity>
+ <activity android:name=".ui.main.HomeActivity">
+ </activity>
+ <activity android:name=".ui.detail.DetailActivity"
+ android:windowSoftInputMode="adjustResize">
+
+ </activity>
+ <activity android:name=".ui.map.MapActivity"
+ android:screenOrientation="portrait">
+ <intent-filter>
+ <action android:name="android.intent.action.VIEW"/>
+
+ <category android:name="android.intent.category.LAUNCHER"/>
+ </intent-filter>
+ </activity>
+ <activity android:name=".ui.map.StreetMapActivity"
+ android:screenOrientation="portrait">
+ </activity>
+
</application>
</manifest>
\ No newline at end of file | Unknown | `android:screenOrientation` ์์ฑ์ด ์ผ๋ถ Activity์๋ง ์ ์ฉ๋์ด ์๋๋ฐ ์๋ํ์ ๊ฒ ์๋๋ผ ๋น ํธ๋ฆฌ์ ๊ฑฐ ๊ฐ๋ค์ |
@@ -0,0 +1,45 @@
+package kr.co.connect.boostcamp.livewhere
+
+import android.content.Context
+import androidx.multidex.MultiDex
+import androidx.multidex.MultiDexApplication
+import com.bumptech.glide.Glide
+import com.crashlytics.android.Crashlytics
+import com.facebook.stetho.Stetho
+import com.naver.maps.map.NaverMapSdk
+import io.fabric.sdk.android.Fabric
+import kr.co.connect.boostcamp.livewhere.di.appModules
+import org.koin.android.ext.android.startKoin
+
+
+// FIXME MultiDex ์ด์๊ฐ ๋ฐ์ํ ์ฌ์ง๊ฐ ์ถฉ๋ถํ๊ธฐ๋๋ฌธ์ gradle๊ณผ Applicationํด๋์ค์์ Multidex ํ๊ฒฝ์ ๊ตฌ์ฑํด์ฃผ์ธ์
+class LiveApplication : MultiDexApplication() {
+ override fun onCreate() {
+ super.onCreate()
+ //debug๋ณ์๋ฅผ ๋๊ณ debug ์ธ์ง ์บ์นํจ.
+ if (BuildConfig.isDebug) {
+ Stetho.initializeWithDefaults(this)
+ }
+ startKoin(this, appModules)
+ //Firebase Crashlytics
+ Fabric.with(this, Crashlytics())
+ NaverMapSdk.getInstance(this).client = NaverMapSdk.NaverCloudPlatformClient(BuildConfig.NaverClientId)
+ }
+
+ //application class์์ MultiDex ์ฌ์ฉ
+ override fun attachBaseContext(base: Context?) {
+ super.attachBaseContext(base)
+ MultiDex.install(this)
+ }
+
+
+ override fun onLowMemory() {
+ super.onLowMemory()
+ Glide.get(this).clearMemory()
+ }
+
+ override fun onTrimMemory(level: Int) {
+ super.onTrimMemory(level)
+ Glide.get(this).trimMemory(level)
+ }
+}
\ No newline at end of file | Kotlin | https://github.com/boostcamp-3rd/android_teamC/pull/8/files#diff-51a0b488f963eb0be6c6599bf5df497313877cf5bdff3950807373912ac1cdc9R21
์ด๋ฏธ multidex ์ค์ ๋์ด ์์ต๋๋ค.
๋ถํ์ํ ์ฃผ์์ด ๋จ์์๋๊ฑด ์ฝ๋๋ฅผ ์ฝ๋๋ฐ ์ด๋ ค์์ ์ฃผ๋ ์ ๊ฑฐํด์ฃผ์ธ์. |
@@ -0,0 +1,45 @@
+package kr.co.connect.boostcamp.livewhere
+
+import android.content.Context
+import androidx.multidex.MultiDex
+import androidx.multidex.MultiDexApplication
+import com.bumptech.glide.Glide
+import com.crashlytics.android.Crashlytics
+import com.facebook.stetho.Stetho
+import com.naver.maps.map.NaverMapSdk
+import io.fabric.sdk.android.Fabric
+import kr.co.connect.boostcamp.livewhere.di.appModules
+import org.koin.android.ext.android.startKoin
+
+
+// FIXME MultiDex ์ด์๊ฐ ๋ฐ์ํ ์ฌ์ง๊ฐ ์ถฉ๋ถํ๊ธฐ๋๋ฌธ์ gradle๊ณผ Applicationํด๋์ค์์ Multidex ํ๊ฒฝ์ ๊ตฌ์ฑํด์ฃผ์ธ์
+class LiveApplication : MultiDexApplication() {
+ override fun onCreate() {
+ super.onCreate()
+ //debug๋ณ์๋ฅผ ๋๊ณ debug ์ธ์ง ์บ์นํจ.
+ if (BuildConfig.isDebug) {
+ Stetho.initializeWithDefaults(this)
+ }
+ startKoin(this, appModules)
+ //Firebase Crashlytics
+ Fabric.with(this, Crashlytics())
+ NaverMapSdk.getInstance(this).client = NaverMapSdk.NaverCloudPlatformClient(BuildConfig.NaverClientId)
+ }
+
+ //application class์์ MultiDex ์ฌ์ฉ
+ override fun attachBaseContext(base: Context?) {
+ super.attachBaseContext(base)
+ MultiDex.install(this)
+ }
+
+
+ override fun onLowMemory() {
+ super.onLowMemory()
+ Glide.get(this).clearMemory()
+ }
+
+ override fun onTrimMemory(level: Int) {
+ super.onTrimMemory(level)
+ Glide.get(this).trimMemory(level)
+ }
+}
\ No newline at end of file | Kotlin | ๋์์ด ์๋ช
ํ ์ฝ๋๋ผ ์ฃผ์์ด ๋ถํ์ํด ๋ณด์
๋๋ค. |
@@ -0,0 +1,40 @@
+package kr.co.connect.boostcamp.livewhere.api
+
+import io.reactivex.Single
+import kr.co.connect.boostcamp.livewhere.model.HouseResponse
+import kr.co.connect.boostcamp.livewhere.model.PlaceResponse
+import retrofit2.Response
+import retrofit2.http.GET
+import retrofit2.http.POST
+import retrofit2.http.Query
+
+interface Api {
+ @GET("house/search/info")
+ fun getHouseDetail(
+ @Query("address") address: String
+ ): Single<Response<List<Any>>>
+
+ @GET("house/search/infos")
+ fun getDetail(
+ @Query("address") address: String
+ ): Single<Response<HouseResponse>>
+
+ @GET("place/search/infos")
+ fun getPlace(
+ @Query("lat") lat: String,
+ @Query("lng") lng: String,
+ @Query("radius") radius: String,
+ @Query("category") category: String
+ ): Single<Response<PlaceResponse>>
+
+ @GET("house/search/find/infos")
+ fun getDetailWithAddress(
+ @Query("address") address: String
+ ): Single<Response<HouseResponse>>
+
+ @POST("")
+ fun postReview(
+ @Query("nickname") nickname: String, @Query("id") id: String, @Query("contents") contents: String
+ ): Single<Response<Any>>
+
+}
\ No newline at end of file | Kotlin | ์ด๋ ํ ์์๋ ๊ฐ๋ฆฌํค๊ณ ์์ง ์๋ค๋ฉด RESTful ํ์ง ์์ต๋๋ค.
์ฌ๋ฐ๋ฅด์ง ๋ชปํ ์ค๊ณ์
๋๋ค. |
@@ -0,0 +1,20 @@
+package kr.co.connect.boostcamp.livewhere.api
+
+import io.reactivex.Observable
+import kr.co.connect.boostcamp.livewhere.BuildConfig
+import kr.co.connect.boostcamp.livewhere.model.TmapResponse
+import retrofit2.Response
+import retrofit2.http.GET
+import retrofit2.http.Query
+
+interface TmapApi {
+ @GET("tmap/pois")
+ fun getAddress(
+ @Query("searchKeyword") searchKeyword: String,
+ @Query("appKey") appKey: String = BuildConfig.TmapApiKey,
+ @Query("count") count: String = "10",
+ @Query("areaLLCode") code: String = "11"
+ ): Observable<Response<TmapResponse>>
+
+
+}
\ No newline at end of file | Kotlin | `10`, `11`์ ์ด๋ค ๊ธฐ์ค์ผ๋ก ์ ํด์ง default ๊ฐ์ธ์ง ์ ๋ฐฉ๋ฒ์ด ์์ต๋๋ค.
์์๋ก ๋นผ๋ด๊ณ ๋ณ์๋ช
์ ์๋ฏธ๋ฅผ ๋ด๋๊ฑด ์ด๋จ๊น์? |
@@ -0,0 +1,20 @@
+package kr.co.connect.boostcamp.livewhere.api
+
+import io.reactivex.Observable
+import kr.co.connect.boostcamp.livewhere.BuildConfig
+import kr.co.connect.boostcamp.livewhere.model.TmapResponse
+import retrofit2.Response
+import retrofit2.http.GET
+import retrofit2.http.Query
+
+interface TmapApi {
+ @GET("tmap/pois")
+ fun getAddress(
+ @Query("searchKeyword") searchKeyword: String,
+ @Query("appKey") appKey: String = BuildConfig.TmapApiKey,
+ @Query("count") count: String = "10",
+ @Query("areaLLCode") code: String = "11"
+ ): Observable<Response<TmapResponse>>
+
+
+}
\ No newline at end of file | Kotlin | Retrofit์ผ๋ก ๊ตฌํ๋๋๋ฐ Observable์ผ ํ์๊ฐ ์์ต๋๋ค. Http๋๊น์. |
@@ -0,0 +1,19 @@
+package kr.co.connect.boostcamp.livewhere.api
+
+import io.reactivex.Single
+import kr.co.connect.boostcamp.livewhere.BuildConfig
+import kr.co.connect.boostcamp.livewhere.model.ReverseGeo
+import retrofit2.Response
+import retrofit2.http.GET
+import retrofit2.http.Headers
+import retrofit2.http.Query
+
+interface ReverseGeoApi {
+ @Headers("Authorization: KakaoAK " + BuildConfig.KakaoServiceKey)
+ @GET("geo/coord2address.json")
+ fun getAddress(
+ @Query("y") latitude: String,
+ @Query("x") longitude: String,
+ @Query("input_coord") inputCoord: String
+ ): Single<Response<ReverseGeo>>
+}
\ No newline at end of file | Kotlin | gps ์ขํ ์ ๋ณด์ธ๊ฑธ๋ก ๋ณด์ด๋๋ฐ String์ด ๋ง๋์? |
@@ -0,0 +1,12 @@
+package kr.co.connect.boostcamp.livewhere.data.entity
+
+import androidx.room.ColumnInfo
+import androidx.room.Entity
+import androidx.room.PrimaryKey
+
+@Entity(tableName = "recent_search")
+data class RecentSearchEntity(
+ @PrimaryKey var text: String,
+ @ColumnInfo(name = "Longitude") var longitude: String,
+ @ColumnInfo(name = "Latitude") var latitude: String
+)
\ No newline at end of file | Kotlin | ๋ค๋ฅธ ํ
์ด๋ธ์ ์ปฌ๋ผ๋ค์ ์๋ฌธ์๋ก ์์ํ๋ snake case๋ฅผ ์ฌ์ฉํ๊ณ ์์ต๋๋ค.
ํต์ผ์ด ํ์ํด๋ณด์ฌ์ |
@@ -0,0 +1,13 @@
+package kr.co.connect.boostcamp.livewhere.di
+
+
+val appModules = arrayListOf(
+ apiModule
+ , loginModule
+ , sharedModule
+ , databaseModule
+ , homeModule
+ , mapModule
+ , reverseGeoApiModule
+ , detailModule
+) | Kotlin | ๋ค๋ฅธ ์ฝ๋๋ค๊ณผ ์ ํ ๋ค๋ฅธ code format์ธ๋ฐ ํต์ผ์ด ํ์ํด ๋ณด์
๋๋ค. |
@@ -0,0 +1,24 @@
+package kr.co.connect.boostcamp.livewhere.di
+
+import androidx.room.Room
+import kr.co.connect.boostcamp.livewhere.data.database.AppDataBase
+import org.koin.android.ext.koin.androidContext
+import org.koin.dsl.module.module
+
+const val DATABASE_NAME = "mdatabase.db"
+
+val databaseModule = module {
+ single("databaseModule") {
+ Room.databaseBuilder(androidContext(), AppDataBase::class.java, DATABASE_NAME)
+ .fallbackToDestructiveMigration()
+ .build()
+ }
+
+ single("bookmarkDAO") {
+ get<AppDataBase>().bookmarkDao()
+ }
+
+ single("recentSearchDAO") {
+ get<AppDataBase>().recentSearchDao()
+ }
+}
\ No newline at end of file | Kotlin | ์ด ๋ชจ๋์ ์ ์๋ 3๊ฐ์ง injection๋ค์ named inject๊ฐ ํ์ํ๊ฐ์?
๋ถํ์ํด๋ณด์
๋๋ค. |
@@ -0,0 +1,22 @@
+package codesquad.dto.question;
+
+import lombok.*;
+
+@AllArgsConstructor
+@Getter
+@Setter
+@Builder
+public class QuestionRequestDto {
+ private String writer;
+ private String title;
+ private String contents;
+
+ @Override
+ public String toString() {
+ return "QuestionDto{" +
+ "writer='" + writer + '\'' +
+ ", title='" + title + '\'' +
+ ", contents='" + contents + '\'' +
+ '}';
+ }
+} | Java | ๊ธฐ๋ณธ ์์ฑ์๋ฅผ ์์ฑํด์ฃผ์ ์ด์ ๊ฐ ์์๊น์? |
@@ -1,22 +1,36 @@
package codesquad;
-import codesquad.repository.ArrayUserRepository;
+import codesquad.repository.QuestionRepositoryImpl;
+import codesquad.repository.UserRepositoryImpl;
+import codesquad.repository.QuestionRepository;
import codesquad.repository.UserRepository;
+import codesquad.service.QuestionService;
+import codesquad.service.QuestionServiceImpl;
import codesquad.service.UserService;
import codesquad.service.UserServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
-
+
@Bean
public UserService userService() {
return new UserServiceImpl(userRepository());
}
@Bean
public UserRepository userRepository() {
- return new ArrayUserRepository();
+ return new UserRepositoryImpl();
+ }
+
+ @Bean
+ public QuestionService questionService() {
+ return new QuestionServiceImpl(questionRepository());
+ }
+
+ @Bean
+ public QuestionRepository questionRepository() {
+ return new QuestionRepositoryImpl();
}
} | Java | ์ปจํธ๋กค๋ฌ๋ @Controller ์ด๋
ธํ
์ด์
์ ์ด์ฉํด ๋น์ ๋ฑ๋กํ๊ณ ๊ณ์๋๋ฐ, Service์ Repository๋ Config ํ์ผ์์ ๋น์ ๋ฐ๋ก ๋ฑ๋กํด์ฃผ๊ณ ๊ณ์๋ ์ด์ ๊ฐ ๊ถ๊ธํฉ๋๋ค! |
@@ -7,6 +7,8 @@
public interface UserRepository {
void register(UserEntity userEntity);
+ void update(String userId, UserEntity userEntity);
+
UserEntity findById(String userId);
List<UserEntity> findAll(); | Java | update()๋ dto๋ฅผ ๋๊ฒจ์ฃผ๊ณ ์๋๋ฐ, register()๋ ์ํฐํฐ๋ฅผ ๋๊ฒจ์ฃผ๋ ์ด์ ๊ฐ ๊ถ๊ธํฉ๋๋ค! |
@@ -0,0 +1,30 @@
+package codesquad.service;
+
+import codesquad.entity.QuestionEntity;
+import codesquad.repository.QuestionRepository;
+
+import java.util.List;
+
+public class QuestionServiceImpl implements QuestionService {
+ private final QuestionRepository questionRepository;
+
+ public QuestionServiceImpl(QuestionRepository questionRepository) {
+ this.questionRepository = questionRepository;
+ }
+
+ @Override
+ public void postQuestion(QuestionEntity questionEntity) {
+ questionRepository.post(questionEntity);
+ questionRepository.setBaseTime(questionEntity);
+ }
+
+ @Override
+ public List<QuestionEntity> findQuestions() {
+ return questionRepository.findAll();
+ }
+
+ @Override
+ public QuestionEntity findQuestion(String id) {
+ return questionRepository.findAll().get(Integer.parseInt(id) - 1);
+ }
+} | Java | ์ํฐํฐ๋ฅผ ์ด์ฉํด ๋ฐ์ดํฐ๋ฅผ ์ฃผ๊ณ ๋ฐ์ผ๋ฉด ์ด๋ค ๋ฌธ์ ๊ฐ ์์์ง ๊ณ ๋ฏผํด๋ณด์๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,30 @@
+package codesquad.service;
+
+import codesquad.entity.QuestionEntity;
+import codesquad.repository.QuestionRepository;
+
+import java.util.List;
+
+public class QuestionServiceImpl implements QuestionService {
+ private final QuestionRepository questionRepository;
+
+ public QuestionServiceImpl(QuestionRepository questionRepository) {
+ this.questionRepository = questionRepository;
+ }
+
+ @Override
+ public void postQuestion(QuestionEntity questionEntity) {
+ questionRepository.post(questionEntity);
+ questionRepository.setBaseTime(questionEntity);
+ }
+
+ @Override
+ public List<QuestionEntity> findQuestions() {
+ return questionRepository.findAll();
+ }
+
+ @Override
+ public QuestionEntity findQuestion(String id) {
+ return questionRepository.findAll().get(Integer.parseInt(id) - 1);
+ }
+} | Java | Entity, Model, Dto, VO์ ์ฐจ์ด์ ๋ํด ์์๋ณด์๋ฉด ์ข์ ๊ฒ ๊ฐ์์ |
@@ -0,0 +1,74 @@
+package codesquad.controller;
+
+import codesquad.AppConfig;
+import codesquad.dto.question.QuestionRequestDto;
+import codesquad.dto.question.QuestionResponseDto;
+import codesquad.entity.QuestionEntity;
+import codesquad.mapper.QuestionMapper;
+import codesquad.service.QuestionService;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
+import org.springframework.stereotype.Controller;
+import org.springframework.ui.Model;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+@Controller
+public class QuestionController {
+ ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
+ QuestionService questionService = applicationContext.getBean("questionService", QuestionService.class);
+
+ @GetMapping("/questions/post")
+ public String getQuestionForm() {
+ return "qna/form";
+ }
+
+ @PostMapping("/questions")
+ public String postQuestion(QuestionRequestDto questionRequestDto) {
+ QuestionEntity questionEntity = QuestionMapper.dtoToEntity(questionRequestDto);
+ questionService.postQuestion(questionEntity);
+ return "redirect:/questions";
+ }
+
+ @GetMapping("/questions")
+ public String getQuestionList(Model model) {
+ List<QuestionResponseDto> questions = questionService.findQuestions().stream()
+ .map(questionEntity -> QuestionMapper.entityToDto(questionEntity))
+ .collect(Collectors.toList());
+
+ model.addAttribute("questions", questions);
+
+ return "qna/list";
+ }
+
+ @GetMapping("/questions/{id}")
+ public String getQuestionShow(@PathVariable String id, Model model) {
+ QuestionResponseDto question = new QuestionResponseDto(questionService.findQuestion(id));
+
+ model.addAttribute("writer", question.getWriter());
+ model.addAttribute("title", question.getTitle());
+ model.addAttribute("contents", question.getContents());
+ model.addAttribute("date", question.getDate());
+
+ return "qna/show";
+ }
+
+ @GetMapping("/")
+ public String getHome(Model model) {
+ List<QuestionEntity> questionEntityList = questionService.findQuestions();
+ if (questionEntityList.size() == 0) {
+ return "qna/list";
+ }
+
+ List<QuestionResponseDto> questionResponseDtoList = questionService.findQuestions().stream()
+ .map(questionEntity -> QuestionMapper.entityToDto(questionEntity))
+ .collect(Collectors.toList());
+
+ model.addAttribute("questions", questionResponseDtoList);
+ return "qna/list";
+ }
+}
\ No newline at end of file | Java | applicationcontext๋ก๋ถํฐ ์ง์ ๋น์ ๊ฐ์ ธ์ค์
์ ์ฌ์ฉํ์ ์ด์ ๊ฐ ๊ถ๊ธํฉ๋๋ค! |
@@ -1,18 +1,17 @@
package codesquad.controller;
import codesquad.AppConfig;
-import codesquad.dto.UserDto;
+import codesquad.dto.user.UserDto;
+import codesquad.dto.user.UserUpdateRequestDto;
import codesquad.entity.UserEntity;
+import codesquad.mapper.UserMapper;
import codesquad.service.UserService;
import org.modelmapper.ModelMapper;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;
@@ -39,7 +38,6 @@ public String registerUser(UserDto userDto) {
@GetMapping()
public String getUserList(Model model) {
- System.out.println("userService.findUsers().get(0) = " + userService.findUsers().get(0));
List<UserDto> users = userService.findUsers().stream()
.map(userEntity -> modelMapper.map(userEntity, UserDto.class)).collect(Collectors.toList());
model.addAttribute("users", users);
@@ -57,4 +55,15 @@ public String getUserProfile(@PathVariable String userId, Model model) {
return "user/profile";
}
+
+ @GetMapping("/{userId}/form")
+ public String getProfileEditForm() {
+ return "user/update_form";
+ }
+
+ @PutMapping("/{userId}/update")
+ public String updateUserProfile(@PathVariable("userId") String userId, UserUpdateRequestDto requestDto) {
+ userService.updateUser(userId, UserMapper.dtoToEntity(requestDto));
+ return "redirect:/users";
+ }
} | Java | ์
๋ฐ์ดํธ์๋ ๋ณดํต PUT๊ณผ PATCH๊ฐ ์ฌ์ฉ๋ฉ๋๋ค. ์ด ๋์ ์ฐจ์ด๋ ๋ฌด์์ผ๊น์? |
@@ -1,22 +1,36 @@
package codesquad;
-import codesquad.repository.ArrayUserRepository;
+import codesquad.repository.QuestionRepositoryImpl;
+import codesquad.repository.UserRepositoryImpl;
+import codesquad.repository.QuestionRepository;
import codesquad.repository.UserRepository;
+import codesquad.service.QuestionService;
+import codesquad.service.QuestionServiceImpl;
import codesquad.service.UserService;
import codesquad.service.UserServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
-
+
@Bean
public UserService userService() {
return new UserServiceImpl(userRepository());
}
@Bean
public UserRepository userRepository() {
- return new ArrayUserRepository();
+ return new UserRepositoryImpl();
+ }
+
+ @Bean
+ public QuestionService questionService() {
+ return new QuestionServiceImpl(questionRepository());
+ }
+
+ @Bean
+ public QuestionRepository questionRepository() {
+ return new QuestionRepositoryImpl();
}
} | Java | ์ฐ์ ์์กด์ฑ์ ์ฃผ์
ํ์ฌ ์ฝ๋/๊ฐ์ฒด ๊ฐ์ ๊ฒฐํฉ๋๋ฅผ ๋ฎ์ถ๊ธฐ ์ํด Service์ Repository๋ ์๋ฐ ์ฝ๋๋ก ์ง์ ์คํ๋ง ๋น์ ๋ฑ๋กํ์์ต๋๋ค. ์ด๋ ๊ฐ๋ฐ์ ์งํํ๋ค Repository๋ฅผ ๋ณ๊ฒฝํด์ผํ๋ ์ํฉ์ผ ๋, Config์ ๋ฑ๋ก๋ Repository Bean๋ง ์์ ํ๋ฉด ๋๊ธฐ ๋๋ฌธ์
๋๋ค.
๊ทธ๋ผ Controller์ ์ญํ ์ ์๊ฐํด๋ณด๊ฒ ์ต๋๋ค.
์ปจํธ๋กค๋ฌ๋ View์ Service๋ฅผ ์ด์ด์ฃผ๋ ์ญํ ๋ง ํ๊ณ ๋น์ฆ๋์ค ๋ก์ง์ ๊ฐ์ง๊ณ ์์ง ์์ต๋๋ค. ๋ฐ๋ผ์ Repository๊ฐ ๋ณ๊ฒฝ๋๊ฑฐ๋ ๋น์ฆ๋์ค ๋ก์ง์ด ๋ณ๊ฒฝ๋์ด๋ Controller๋ ๋ณ๊ฒฝ๋์ง ์์ผ๋ฏ๋ก Config์์ ๋ฑ๋กํ์ง ์์์ต๋๋ค.
ref: https://inf.run/SZEa -> ๋ง ๋ค๋ฌ๋๋ฐ ๋์ ๋ฐ์์ต๋๋ค:) |
@@ -0,0 +1,74 @@
+package codesquad.controller;
+
+import codesquad.AppConfig;
+import codesquad.dto.question.QuestionRequestDto;
+import codesquad.dto.question.QuestionResponseDto;
+import codesquad.entity.QuestionEntity;
+import codesquad.mapper.QuestionMapper;
+import codesquad.service.QuestionService;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
+import org.springframework.stereotype.Controller;
+import org.springframework.ui.Model;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+@Controller
+public class QuestionController {
+ ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
+ QuestionService questionService = applicationContext.getBean("questionService", QuestionService.class);
+
+ @GetMapping("/questions/post")
+ public String getQuestionForm() {
+ return "qna/form";
+ }
+
+ @PostMapping("/questions")
+ public String postQuestion(QuestionRequestDto questionRequestDto) {
+ QuestionEntity questionEntity = QuestionMapper.dtoToEntity(questionRequestDto);
+ questionService.postQuestion(questionEntity);
+ return "redirect:/questions";
+ }
+
+ @GetMapping("/questions")
+ public String getQuestionList(Model model) {
+ List<QuestionResponseDto> questions = questionService.findQuestions().stream()
+ .map(questionEntity -> QuestionMapper.entityToDto(questionEntity))
+ .collect(Collectors.toList());
+
+ model.addAttribute("questions", questions);
+
+ return "qna/list";
+ }
+
+ @GetMapping("/questions/{id}")
+ public String getQuestionShow(@PathVariable String id, Model model) {
+ QuestionResponseDto question = new QuestionResponseDto(questionService.findQuestion(id));
+
+ model.addAttribute("writer", question.getWriter());
+ model.addAttribute("title", question.getTitle());
+ model.addAttribute("contents", question.getContents());
+ model.addAttribute("date", question.getDate());
+
+ return "qna/show";
+ }
+
+ @GetMapping("/")
+ public String getHome(Model model) {
+ List<QuestionEntity> questionEntityList = questionService.findQuestions();
+ if (questionEntityList.size() == 0) {
+ return "qna/list";
+ }
+
+ List<QuestionResponseDto> questionResponseDtoList = questionService.findQuestions().stream()
+ .map(questionEntity -> QuestionMapper.entityToDto(questionEntity))
+ .collect(Collectors.toList());
+
+ model.addAttribute("questions", questionResponseDtoList);
+ return "qna/list";
+ }
+}
\ No newline at end of file | Java | AppConfig์์ @ComponentScan ๊ฐ์ Spring Bean์ ์๋์ผ๋ก ๊ฐ์ ธ์ค๊ธฐ ์ํ ์ด๋
ธํ
์ด์
์ ์ฌ์ฉํ์ง ์์๊ธฐ์ ์ง์ ๋น์ ๊ฐ์ ธ์์ต๋๋ค!
(์ฌ์ค ์ง๋ฌธ ์๋๋ฅผ ์ ๋๋ก ์ดํดํ์ง ๋ชปํ์ต๋๋ค. ๋ถ์ฐ ์ค๋ช
ํด์ฃผ์๋ฉด ๊ฐ์ฌํ๊ฒ ์ต๋๋ค!) |
@@ -1,18 +1,17 @@
package codesquad.controller;
import codesquad.AppConfig;
-import codesquad.dto.UserDto;
+import codesquad.dto.user.UserDto;
+import codesquad.dto.user.UserUpdateRequestDto;
import codesquad.entity.UserEntity;
+import codesquad.mapper.UserMapper;
import codesquad.service.UserService;
import org.modelmapper.ModelMapper;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;
@@ -39,7 +38,6 @@ public String registerUser(UserDto userDto) {
@GetMapping()
public String getUserList(Model model) {
- System.out.println("userService.findUsers().get(0) = " + userService.findUsers().get(0));
List<UserDto> users = userService.findUsers().stream()
.map(userEntity -> modelMapper.map(userEntity, UserDto.class)).collect(Collectors.toList());
model.addAttribute("users", users);
@@ -57,4 +55,15 @@ public String getUserProfile(@PathVariable String userId, Model model) {
return "user/profile";
}
+
+ @GetMapping("/{userId}/form")
+ public String getProfileEditForm() {
+ return "user/update_form";
+ }
+
+ @PutMapping("/{userId}/update")
+ public String updateUserProfile(@PathVariable("userId") String userId, UserUpdateRequestDto requestDto) {
+ userService.updateUser(userId, UserMapper.dtoToEntity(requestDto));
+ return "redirect:/users";
+ }
} | Java | `PUT`์ ์์ ์ ์ฒด๋ฅผ ๊ต์ฒดํ์ฌ, ์์์ ๋ชจ๋ ํ๋๊ฐ ํ์ํ๊ณ
`PATCH`๋ ์์์ ๋ถ๋ถ๋ง ๊ต์ฒดํ์ฌ, ์์์ ์ผ๋ถ ํ๋๋ง ์์ด๋ ๋ฉ๋๋ค.
GOOD
```
PUT /userId/1
{
"userId" : "mywnajsldkf",
"age" : 24
}
GET /userId/1
{
"userId" : "mywnajsldkf",
"age" : 24
}
```
BAD
```
PUT /userId/1
{
"userId" : "mywnajsldkf",
}
GET /userId/1
{
"userId" : "mywnajsldkf",
"age" : null
}
```
GOOD
```
PATCH /userId/1
{
"userId" : "mywnajsldkf",
}
GET /userId/1
{
"userId" : "mywnajsldkf",
"age" : 24
}
``` |
@@ -7,6 +7,8 @@
public interface UserRepository {
void register(UserEntity userEntity);
+ void update(String userId, UserEntity userEntity);
+
UserEntity findById(String userId);
List<UserEntity> findAll(); | Java | dto <-> entity ์ฌ์ด์ ๋งตํ์ ์ด๋์ ํด์ผํ ์ง ๊ณ ๋ฏผ์ ํ๋๋ฐ์.
DTO๋ ์ปจํธ๋กค๋ฌ ๋ ์ด์ด์ ์ข
์๋์ด์ผ ํ๋ค๊ณ ์๊ฐํด ๋งตํ์ ๊ด๋ จ๋ ๊ฒ์ ๋ชจ๋ ์ปจํธ๋กค๋ฌ์์ ๋๋ ค๊ณ ํ์์ต๋๋ค.
update()์ ๋ํ ๋ถ๋ถ์ ํผ๋๋ฐฑ์ ๋ณด๊ณ ๋ค์ ๋ณด๋, ์๋ก์ด userEntity๋ฅผ ์์ฑํ๋ register์ ๋ค๋ฅด๊ฒ ๊ธฐ์กด์ ์๋ userEntity๋ฅผ ์์ ํ๋ ๊ฒ์ด๋ค๋ณด๋ ๊ฐ์ updateํ๋ ๋ฐฉํฅ์ ์ง์คํ์ต๋๋ค. ๊ทธ๋ฌ๋ค๋ณด๋ DTO -> Entity๋ ์๋กญ๊ฒ ๊ฐ์ฒด๋ฅผ ๋ง๋ ๋ค๋ ์๊ฐ์ ๊ฑฐ์น์ง ์์๋ค์.๐
๋ค์๋ณด๋ register() ์ฒ๋ผ controller์์ entity๋ก ๋ฐ๊ฟ์ ๋๊ฒจ์ง๊ณ entity์ ์๋ ๊ฐ๋ค์ repository์์ ๊บผ๋ด์ด ์
๋ฐ์ดํธํ๋ ๋ฐฉ์์ผ๋ก ์์ ํ๊ณ ์ถ์๋ฐ @saint6839 ๋์ ์๊ฐ์ ์ด๋ ์ธ์?
+)
dto <-> entity๋ ์ด๋์์ ๊ดํ ๋ถ๋ถ์...
์ด์ ๋ฆฌ๋ทฐ์์๋ ์ง๋ฌธ๋๋ฆฌ๊ธฐ๋ ํ๊ณ , ๋ค์ํ [ํ ๋ก ๊ธ 1](https://okky.kr/articles/708060), [ํ ๋ก ๊ธ 2](https://tecoble.techcourse.co.kr/post/2021-04-25-dto-layer-scope/) ๋ฑ์ ์ฐพ์๋ณด๊ธฐ๋ ํ๋๋ฐ์~
์ค์ค๋ก ๋ด๋ฆฐ ์์
๋ฐฉํฅ์ฑ์ **repository๊น์ง ๋ค์ด๊ฐ์ง ๋ง ๊ฒ, ํ๋ก์ ํธ ๋ด์ ์ผ๊ด์ฑ์ ์ ์งํ ๊ฒ, (๋ฌด์๋ณด๋ค) ๊ฐ์ด ํ๋ ์ฌ๋์ด๋ ๋ง์ถ ๊ฒ** ์
๋๋ค.๐
์ด ๋ถ๋ถ์ ๋ํด ์์ฝ๋์ ์๊ฐ๋ ๋ค์ด๋ณด๊ณ ์ถ๋ค์~ |
@@ -0,0 +1,30 @@
+package codesquad.service;
+
+import codesquad.entity.QuestionEntity;
+import codesquad.repository.QuestionRepository;
+
+import java.util.List;
+
+public class QuestionServiceImpl implements QuestionService {
+ private final QuestionRepository questionRepository;
+
+ public QuestionServiceImpl(QuestionRepository questionRepository) {
+ this.questionRepository = questionRepository;
+ }
+
+ @Override
+ public void postQuestion(QuestionEntity questionEntity) {
+ questionRepository.post(questionEntity);
+ questionRepository.setBaseTime(questionEntity);
+ }
+
+ @Override
+ public List<QuestionEntity> findQuestions() {
+ return questionRepository.findAll();
+ }
+
+ @Override
+ public QuestionEntity findQuestion(String id) {
+ return questionRepository.findAll().get(Integer.parseInt(id) - 1);
+ }
+} | Java | > ์ํฐํฐ๋ฅผ ์ด์ฉํด ๋ฐ์ดํฐ๋ฅผ ์ฃผ๊ณ ๋ฐ์ผ๋ฉด ์ด๋ค ๋ฌธ์ ๊ฐ ์์์ง ๊ณ ๋ฏผํด๋ณด์๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค!
๋ค! ํ๋ฒ ๊ณ ๋ฏผํด๋ณด๊ฒ ์ต๋๋ค~ ํน์ ์์ฝ๋์ด ๋ง์ํ์ ๋ฐ์ดํฐ๋ฅผ ์ฃผ๊ณ ๋ฐ๋ ๋ถ๋ถ์ view(controller)์ ์ฃผ๊ณ ๋ฐ๋๋ค๋ ๋ง์์ด์ค๊น์? |
@@ -0,0 +1,30 @@
+package codesquad.service;
+
+import codesquad.entity.QuestionEntity;
+import codesquad.repository.QuestionRepository;
+
+import java.util.List;
+
+public class QuestionServiceImpl implements QuestionService {
+ private final QuestionRepository questionRepository;
+
+ public QuestionServiceImpl(QuestionRepository questionRepository) {
+ this.questionRepository = questionRepository;
+ }
+
+ @Override
+ public void postQuestion(QuestionEntity questionEntity) {
+ questionRepository.post(questionEntity);
+ questionRepository.setBaseTime(questionEntity);
+ }
+
+ @Override
+ public List<QuestionEntity> findQuestions() {
+ return questionRepository.findAll();
+ }
+
+ @Override
+ public QuestionEntity findQuestion(String id) {
+ return questionRepository.findAll().get(Integer.parseInt(id) - 1);
+ }
+} | Java | > Entity, Model, Dto, VO์ ์ฐจ์ด์ ๋ํด ์์๋ณด์๋ฉด ์ข์ ๊ฒ ๊ฐ์์
์กฐ์ธ ๊ฐ์ฌํฉ๋๋ค~
๊ณต๋ถํ๋ฉด์ ๊ถ๊ธํ ์ ์ด ์์ต๋๋ค.
์์ง VO๋ฅผ ์ฌ์ฉํ๋ ์ด์ ๊ฐ ์๋ฟ์ง ์๋๋ฐ์~
DTO์ฒ๋ผ ๋ฐ์ดํฐ๋ฅผ ์ ์กํ๋ ์ํฉ์๋ง ์ด๋ค๋ ๊ฒ์ด ์๋,
VO์ ์ ์ฝ์ฌํญ(๋ถ๋ณ์ฑ, ๋๋ฑ์ฑ, ์๊ฐ ์ ํจ์ฑ)์ด ์๊ธฐ์
๊ฐ์ฒด ์์ฑ ์ VO ๊ทธ ์์ฒด๊ฐ ์ ์ฝ์ฌํญ์ด ๋๊ฑฐ๋ ์ธ์คํด์ค๊ฐ ์ ํด์ ธ ์๋ ๊ฒฝ์ฐ ๋ฏธ๋ฆฌ ์ธ์คํด์ค๋ฅผ ์์ฑํ๋ ๋ฑ
VO์ ํน์ง์ผ๋ก ์ป์ ์ ์๋ ์ด์ ์ด ์๊ธฐ์ ์ฌ์ฉํ๋ค๊ณ ์ดํดํด๋ ๋ ๊น์?
์๋๋ถํฐ๋ ์ ๋ฆฌํ ๋ด์ฉ์
๋๋ค.
# Entity
- DB์ ํ
์ด๋ธ๊ณผ ๋งคํ๋๋ ๊ฐ์ฒด๋ก, `id`๋ฅผ ํตํด ๊ฐ๊ฐ์ Entity๋ฅผ ๊ตฌ๋ถํฉ๋๋ค.
- ๋ก์ง์ ๊ฐ์ง ์ ์์ต๋๋ค.
```java
public class User {
private Long id;
private String name;
private String email;
@Builder
public User(String name, String email) {
this.name = name;
this.email = email;
}
public User update(String name, String email) {
this.name = name;
this.email = email;
return this;
}
}
```
# DTO
- Data Transfer Object, ๋ง ๊ทธ๋๋ก ๊ณ์ธต(Layer: Service, Controller, Repository)๊ฐ ๋ฐ์ดํฐ ๊ตํ์ ์ํด ์ฌ์ฉํ๋ ๊ฐ์ฒด์
๋๋ค.
- ๋ก์ง์ ๊ฐ์ง ์๊ณ , getter/setter ๋ฉ์๋๋ง ๊ฐ์ต๋๋ค.
```java
class UserDto {
private int name;
private int email;
public UserDto(int name, int email){
this.name = name;
this.email = email;
}
public int getName() {
return name;
}
public int setName(int name) {
this.name = name;
}
...
}
```
# VO
Value Object์ ์ฝ์๋ก ๊ฐ ๊ทธ ์์ฒด์
๋๋ค.
์ฌ์ฉ ์, ์ผ๋ํด์ผํ ๋ถ๋ถ์ **1. equals & hash code ๋ฉ์๋๋ฅผ ์ฌ์ ์ํด์ผ ํ๋ค. 2. ์์ ์(setter)๊ฐ ์๋ ๋ถ๋ณ ๊ฐ์ฒด์ฌ์ผ ํ๋ค.** ์
๋๋ค.
1๋ฒ์ ๋ํด ์ข ๋ ์ด์ผ๊ธฐํ์๋ฉด ๋๋ฑ์ฑ์ ๊ฐ๊ธฐ ๋๋ฌธ์ ๊ฐ์ฒด๊ฐ ์ค์ ๋ค๋ฅธ ๊ฐ์ฒด์ด๋๋ผ๋, ๋
ผ๋ฆฌ์ ์ผ๋ก ๊ฐ์ด ๊ฐ๋ค๋ฉด(๋์ ์์ดํฐ 13๋ฏธ๋, ๋์ ํด๋ํฐ 13๋ฏธ๋ ์๋ก ๋ค๋ฅด์ง๋ง ๊ฐ์) ๊ฐ๋ค๊ณ ๋งํฉ๋๋ค.
2๋ฒ์ setter๊ฐ ์์ด์ ๊ฐ ๋ณ๊ฒฝ ๊ฑฑ์ ์ด ์์ด DB์์ ๊ฐ์ ๊ฐ์ ธ์ ๋ฐ์ดํฐ๋ฅผ VO์ ๋ด์ผ๋ฉด ํญ์ VO์ ๊ฐ์ ์๋ณธ์ผ๋ก ์ ๋ขฐํ ์ ์์ต๋๋ค.
+) ์ ์ ๋ฆฌ๋ ๊ธ๋ ์ฒจ๋ถํฉ๋๋ค.
* https://tecoble.techcourse.co.kr/post/2020-06-11-value-object/
* https://hudi.blog/value-object/
# Model
Model์ ๋น์ฆ๋์ค ๋ก์ง์์ ๋ฐ์ํ๋ ๊ฐ์ด๋ผ๊ณ ์๊ฐํฉ๋๋ค.
DB์ ๊ฐ์ ๋ฃ๊ฑฐ๋ ๊ฐ์ ธ์ค๋ ๊ฒ์ด ์๋ ์ค๊ฐ์ ์ฐ์ฐ์ด ์ด๋ฃจ์ด์ง ๋ ํ๋๋ค์ ๋ชจ๋ธ์ ๋ด์ ๊ด๋ฆฌํ๋ค๊ณ ์๊ฐํฉ๋๋ค. |
@@ -1,22 +1,36 @@
package codesquad;
-import codesquad.repository.ArrayUserRepository;
+import codesquad.repository.QuestionRepositoryImpl;
+import codesquad.repository.UserRepositoryImpl;
+import codesquad.repository.QuestionRepository;
import codesquad.repository.UserRepository;
+import codesquad.service.QuestionService;
+import codesquad.service.QuestionServiceImpl;
import codesquad.service.UserService;
import codesquad.service.UserServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
-
+
@Bean
public UserService userService() {
return new UserServiceImpl(userRepository());
}
@Bean
public UserRepository userRepository() {
- return new ArrayUserRepository();
+ return new UserRepositoryImpl();
+ }
+
+ @Bean
+ public QuestionService questionService() {
+ return new QuestionServiceImpl(questionRepository());
+ }
+
+ @Bean
+ public QuestionRepository questionRepository() {
+ return new QuestionRepositoryImpl();
}
} | Java | ์์กด์ฑ ์ฃผ์
์ ์คํ๋ง์ด ์์์ ํด์ฃผ๋ ๋ถ๋ถ์
๋๋ค ~
์คํ๋ง ๋ถํธ์ DI ๋ฐฉ์์ ๋ํด ์์๋ณด๋ฉด ์ข์ ๊ฒ ๊ฐ์์ |
@@ -0,0 +1,74 @@
+package codesquad.controller;
+
+import codesquad.AppConfig;
+import codesquad.dto.question.QuestionRequestDto;
+import codesquad.dto.question.QuestionResponseDto;
+import codesquad.entity.QuestionEntity;
+import codesquad.mapper.QuestionMapper;
+import codesquad.service.QuestionService;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
+import org.springframework.stereotype.Controller;
+import org.springframework.ui.Model;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+@Controller
+public class QuestionController {
+ ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
+ QuestionService questionService = applicationContext.getBean("questionService", QuestionService.class);
+
+ @GetMapping("/questions/post")
+ public String getQuestionForm() {
+ return "qna/form";
+ }
+
+ @PostMapping("/questions")
+ public String postQuestion(QuestionRequestDto questionRequestDto) {
+ QuestionEntity questionEntity = QuestionMapper.dtoToEntity(questionRequestDto);
+ questionService.postQuestion(questionEntity);
+ return "redirect:/questions";
+ }
+
+ @GetMapping("/questions")
+ public String getQuestionList(Model model) {
+ List<QuestionResponseDto> questions = questionService.findQuestions().stream()
+ .map(questionEntity -> QuestionMapper.entityToDto(questionEntity))
+ .collect(Collectors.toList());
+
+ model.addAttribute("questions", questions);
+
+ return "qna/list";
+ }
+
+ @GetMapping("/questions/{id}")
+ public String getQuestionShow(@PathVariable String id, Model model) {
+ QuestionResponseDto question = new QuestionResponseDto(questionService.findQuestion(id));
+
+ model.addAttribute("writer", question.getWriter());
+ model.addAttribute("title", question.getTitle());
+ model.addAttribute("contents", question.getContents());
+ model.addAttribute("date", question.getDate());
+
+ return "qna/show";
+ }
+
+ @GetMapping("/")
+ public String getHome(Model model) {
+ List<QuestionEntity> questionEntityList = questionService.findQuestions();
+ if (questionEntityList.size() == 0) {
+ return "qna/list";
+ }
+
+ List<QuestionResponseDto> questionResponseDtoList = questionService.findQuestions().stream()
+ .map(questionEntity -> QuestionMapper.entityToDto(questionEntity))
+ .collect(Collectors.toList());
+
+ model.addAttribute("questions", questionResponseDtoList);
+ return "qna/list";
+ }
+}
\ No newline at end of file | Java | ์คํ๋ง๋ถํธ์์ ์์ฑ์ ์ฃผ์
์ ํ๋ ๋ฐฉ๋ฒ์ ๋ํด ๊ฒ์ํด๋ณด์๋ฉด ์ข์ ๊ฒ ๊ฐ์์ |
@@ -0,0 +1,45 @@
+package codesquad.mapper;
+
+import codesquad.dto.question.QuestionRequestDto;
+import codesquad.dto.question.QuestionResponseDto;
+import codesquad.entity.QuestionEntity;
+
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+
+public class QuestionMapper {
+
+ public static QuestionEntity dtoToEntity(QuestionRequestDto questionRequestDto) {
+ if (questionRequestDto == null){
+ return null;
+ }
+
+ QuestionEntity.QuestionEntityBuilder questionEntity = QuestionEntity.builder();
+
+ questionEntity.writer(questionRequestDto.getWriter());
+ questionEntity.title(questionRequestDto.getTitle());
+ questionEntity.contents(questionRequestDto.getContents());
+
+ return questionEntity.build();
+ }
+
+ public static QuestionResponseDto entityToDto(QuestionEntity questionEntity) {
+ if (questionEntity == null) {
+ return null;
+ }
+
+ QuestionResponseDto.QuestionResponseDtoBuilder questionResponseDto = QuestionResponseDto.builder();
+
+ questionResponseDto.writer(questionEntity.getWriter());
+ questionResponseDto.title(questionEntity.getTitle());
+ questionResponseDto.contents(questionEntity.getContents());
+ questionResponseDto.date(localTimeToString(questionEntity.getCreatedDate()));
+
+ return questionResponseDto.build();
+ }
+
+ public static String localTimeToString(LocalDateTime localDateTime) {
+ String stringLocalTime = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
+ return stringLocalTime;
+ }
+} | Java | ๋ณ์๋ private ์ผ๋ก ์ ์ธํ๊ณ setter ๋ฅผ ์ฌ์ฉํด์ ์ ๊ทผํ๋๊ฒ ์๋ฐ์ ์ผ๋ฐ์ ์ธ ์์น์
๋๋ค ~ |
@@ -0,0 +1,24 @@
+package codesquad.entity;
+
+import lombok.*;
+
+@Setter
+@Getter
+@Builder
+@NoArgsConstructor
+@AllArgsConstructor
+public class QuestionEntity extends BaseTimeEntity {
+
+ private String writer;
+ private String title;
+ private String contents;
+
+ @Override
+ public String toString() {
+ return "QuestionEntity{" +
+ "writer='" + writer + '\'' +
+ ", title='" + title + '\'' +
+ ", contents='" + contents + '\'' +
+ '}';
+ }
+} | Java | Entity ๋ผ๋ postfix ๋ฅผ ๋ถ์ด์ง ์์๋ ๋ ๊ฒ ๊ฐ์ต๋๋ค ~ |
@@ -1,22 +1,36 @@
package codesquad;
-import codesquad.repository.ArrayUserRepository;
+import codesquad.repository.QuestionRepositoryImpl;
+import codesquad.repository.UserRepositoryImpl;
+import codesquad.repository.QuestionRepository;
import codesquad.repository.UserRepository;
+import codesquad.service.QuestionService;
+import codesquad.service.QuestionServiceImpl;
import codesquad.service.UserService;
import codesquad.service.UserServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
-
+
@Bean
public UserService userService() {
return new UserServiceImpl(userRepository());
}
@Bean
public UserRepository userRepository() {
- return new ArrayUserRepository();
+ return new UserRepositoryImpl();
+ }
+
+ @Bean
+ public QuestionService questionService() {
+ return new QuestionServiceImpl(questionRepository());
+ }
+
+ @Bean
+ public QuestionRepository questionRepository() {
+ return new QuestionRepositoryImpl();
}
} | Java | ์ ์ด์ ์ญ์ (IoC)๊ฐ ๋ฌด์์ธ์ง๋ ํ ๋ฒ ์์๋ณด์๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,30 @@
+package codesquad.service;
+
+import codesquad.entity.QuestionEntity;
+import codesquad.repository.QuestionRepository;
+
+import java.util.List;
+
+public class QuestionServiceImpl implements QuestionService {
+ private final QuestionRepository questionRepository;
+
+ public QuestionServiceImpl(QuestionRepository questionRepository) {
+ this.questionRepository = questionRepository;
+ }
+
+ @Override
+ public void postQuestion(QuestionEntity questionEntity) {
+ questionRepository.post(questionEntity);
+ questionRepository.setBaseTime(questionEntity);
+ }
+
+ @Override
+ public List<QuestionEntity> findQuestions() {
+ return questionRepository.findAll();
+ }
+
+ @Override
+ public QuestionEntity findQuestion(String id) {
+ return questionRepository.findAll().get(Integer.parseInt(id) - 1);
+ }
+} | Java | > > ์ํฐํฐ๋ฅผ ์ด์ฉํด ๋ฐ์ดํฐ๋ฅผ ์ฃผ๊ณ ๋ฐ์ผ๋ฉด ์ด๋ค ๋ฌธ์ ๊ฐ ์์์ง ๊ณ ๋ฏผํด๋ณด์๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค!
>
> ๋ค! ํ๋ฒ ๊ณ ๋ฏผํด๋ณด๊ฒ ์ต๋๋ค~ ํน์ ์์ฝ๋์ด ๋ง์ํ์ ๋ฐ์ดํฐ๋ฅผ ์ฃผ๊ณ ๋ฐ๋ ๋ถ๋ถ์ view(controller)์ ์ฃผ๊ณ ๋ฐ๋๋ค๋ ๋ง์์ด์ค๊น์?
์ปจํธ๋กค๋ฌ ๋ฟ ์๋๋ผ ๋ ์ด์ด๋ ์ํคํ
์ณ์์ ๊ฐ ๊ณ์ธต๊ฐ์ ๋ฐ์ดํฐ๋ฅผ ์ฃผ๊ณ ๋ฐ๋ ๊ฒ์ ์๋ฏธํฉ๋๋ค! |
@@ -7,6 +7,8 @@
public interface UserRepository {
void register(UserEntity userEntity);
+ void update(String userId, UserEntity userEntity);
+
UserEntity findById(String userId);
List<UserEntity> findAll(); | Java | > dto <-> entity ์ฌ์ด์ ๋งตํ์ ์ด๋์ ํด์ผํ ์ง ๊ณ ๋ฏผ์ ํ๋๋ฐ์. DTO๋ ์ปจํธ๋กค๋ฌ ๋ ์ด์ด์ ์ข
์๋์ด์ผ ํ๋ค๊ณ ์๊ฐํด ๋งตํ์ ๊ด๋ จ๋ ๊ฒ์ ๋ชจ๋ ์ปจํธ๋กค๋ฌ์์ ๋๋ ค๊ณ ํ์์ต๋๋ค.
>
> update()์ ๋ํ ๋ถ๋ถ์ ํผ๋๋ฐฑ์ ๋ณด๊ณ ๋ค์ ๋ณด๋, ์๋ก์ด userEntity๋ฅผ ์์ฑํ๋ register์ ๋ค๋ฅด๊ฒ ๊ธฐ์กด์ ์๋ userEntity๋ฅผ ์์ ํ๋ ๊ฒ์ด๋ค๋ณด๋ ๊ฐ์ updateํ๋ ๋ฐฉํฅ์ ์ง์คํ์ต๋๋ค. ๊ทธ๋ฌ๋ค๋ณด๋ DTO -> Entity๋ ์๋กญ๊ฒ ๊ฐ์ฒด๋ฅผ ๋ง๋ ๋ค๋ ์๊ฐ์ ๊ฑฐ์น์ง ์์๋ค์.๐
>
> ๋ค์๋ณด๋ register() ์ฒ๋ผ controller์์ entity๋ก ๋ฐ๊ฟ์ ๋๊ฒจ์ง๊ณ entity์ ์๋ ๊ฐ๋ค์ repository์์ ๊บผ๋ด์ด ์
๋ฐ์ดํธํ๋ ๋ฐฉ์์ผ๋ก ์์ ํ๊ณ ์ถ์๋ฐ @saint6839 ๋์ ์๊ฐ์ ์ด๋ ์ธ์?
>
> +) dto <-> entity๋ ์ด๋์์ ๊ดํ ๋ถ๋ถ์... ์ด์ ๋ฆฌ๋ทฐ์์๋ ์ง๋ฌธ๋๋ฆฌ๊ธฐ๋ ํ๊ณ , ๋ค์ํ [ํ ๋ก ๊ธ 1](https://okky.kr/articles/708060), [ํ ๋ก ๊ธ 2](https://tecoble.techcourse.co.kr/post/2021-04-25-dto-layer-scope/) ๋ฑ์ ์ฐพ์๋ณด๊ธฐ๋ ํ๋๋ฐ์~ ์ค์ค๋ก ๋ด๋ฆฐ ์์
๋ฐฉํฅ์ฑ์ **repository๊น์ง ๋ค์ด๊ฐ์ง ๋ง ๊ฒ, ํ๋ก์ ํธ ๋ด์ ์ผ๊ด์ฑ์ ์ ์งํ ๊ฒ, (๋ฌด์๋ณด๋ค) ๊ฐ์ด ํ๋ ์ฌ๋์ด๋ ๋ง์ถ ๊ฒ** ์
๋๋ค.๐ ์ด ๋ถ๋ถ์ ๋ํด ์์ฝ๋์ ์๊ฐ๋ ๋ค์ด๋ณด๊ณ ์ถ๋ค์~
๊ฐ์ธ์ ์ผ๋ก๋ Entity <-> Dto ๋ณํ ์ฑ
์์ ์๋น์ค ๊ณ์ธต์ ๋ถ์ฌํ๋๊ฒ์ ์ ํธํ๋ ํธ์
๋๋ค. ์ปจํธ๋กค๋ฌ ๊ณ์ธต์ ๋ฉ์๋ ๋ค์ด๋ฐ์ ๋น์ฆ๋์ค ์ฉ์ด๋ฅผ, ์๋น์ค ๊ณ์ธต์ ๋ฉ์๋ ๋ค์ด๋ฐ์ ๊ฐ๋ฐ ์ฉ์ด๋ฅผ ์ฌ์ฉํ๋ค๋ ์์์ ๋ณธ ์ ์ด ์์ต๋๋ค(์๋ง๋ ๊น์ํ๋).
๊ทธ๋งํผ ์ปจํธ๋กค๋ฌ ๊ณ์ธต์ ๊ฐ๋ฐ์ ์ธ ์์๋ณด๋ค๋ ์ฌ์ฉ์๋ก๋ถํฐ ๋ค์ด์จ ์์ฒญ์ ์ฒ๋ฆฌํ๋๋ฐ ์ฑ
์์ด ์ง์ค๋์ด์ผ ํ๋ ๊ณ์ธต์ด๋ผ๊ณ ์๊ฐํฉ๋๋ค. ์ด๋ฌํ ์ด์ ๋๋ฌธ์ ์ ๋ ์๋น์ค ๊ณ์ธต์์ Entity์ Dto ๋ณํ์ ๋ค๋ฃจ๋ ๊ฒ์ ์ ํธํ๋ ํธ์
๋๋ค.
์ ๋ต์ ์๋ ๊ฒ ๊ฐ์ง๋ง ๋ณธ์ธ์ด ์ ํธํ๋ ๋ฐฉ๋ฒ์ด ์๋ค๋ฉด, ๊ทธ ๊ทผ๊ฑฐ์ ๋ํด์ ์๊ฐํด๋ณด์๋ฉด ์ข์ ๊ฒ ๊ฐ์์(๋จ์ํ ๋๋ถ๋ถ ์ฌ๋๋ค์ด ๊ทธ๋ ๋ค๊ณ ํด์๊ฐ ์๋..) |
@@ -7,6 +7,8 @@
public interface UserRepository {
void register(UserEntity userEntity);
+ void update(String userId, UserEntity userEntity);
+
UserEntity findById(String userId);
List<UserEntity> findAll(); | Java | @saint6839
์ ๋ service(application or usecase), domain ์ ์ธ๋ถ์ ๊ฒ์ผ๋ก๋ถํฐ ๋
๋ฆฝ์ ์ด๊ณ ์ต๋ํ ์์ํ ์๋ต์ ๋ณด๋ด์ผ ์ฌ์ฉ์ฑ์ด ์ข์์ง๋ค๊ณ ์๊ฐํฉ๋๋ค.
๋ฐ๋ผ์ service ๋ ์ด์ด์์๋ ์ธ๋ถ ์๊ตฌ์ฌํญ์ ํด๋นํ๋ ๋ฐ์ดํฐ ๊ตฌ์กฐ์ธ dto ๋ณํ์ ์ง์ํ๋๋ก ๊ฐ๋ฐํ๋ ํธ์
๋๋ค. ์ค์ ์๋น์ค์์ ๊ฐ๋ฐํ๋ค๋ณด๋ฉด 1controller - 1service ๊ฐ ์๋๋ผ n๊ฐ์ controller ์ผ์ด์ค์์ ์๋ก ๋ค๋ฅธ ๋ชฉ์ ์ผ๋ก 1service ๋ฅผ ํธ์ถํ๋ ์ผ์ด์ค๋ ์์ผ๋ ๊ฐ์๊ฐ ํ์ํ ๋ฐ์ดํฐ๊ฐ ๋ค๋ฅผ ๊ฒฝ์ฐ, dto ๊ฐ ๊ณตํต์ผ๋ก ์ฌ์ฉ๋์ด์ ๋ฑ๋ฑํด์ง๊ณ ๋ฌด์์ด ์ด๋ค ์ผ์ด์ค์ ๊ผญ ํ์ํ ๋ฐ์ดํฐ์ธ์ง ๊ตฌ๋ถํ๊ธฐ๋ ์ด๋ ค์์ง๋๋ค. ๊ทธ๋ฆฌ๊ณ ์๋ก์ ๋ณ๊ฒฝ์ ์ํฅ๋ ๋ง์ด ๋ฐ๊ตฌ์.
๊ทธ๋ ๋ค๊ณ entity ๋ฅผ ์์ํ๊ฒ ๊ทธ๋๋ก ๋ฐํํ๊ฒ ๋๋ฉด OSIV ๊ณ ๋ฏผ์ ๋น ์ง๊ฒ ๋ฉ๋๋ค. ๊ทธ๋์ ์ข ๋ณต์กํ ์ฝ๋์์๋ Service layer DTO ๋ฅผ ๋ฐ๋ก ์ ์ํด์ ๊ทธ๊ฒ์ผ๋ก ๋ณํํ์ฌ ๊ณตํต์ ์ผ๋ก ๋ฐํํด์ฃผ๊ณ , controller ์์๋ service dto ๋ฅผ ๋ฐ์์ ํ์ํ ๋ถ๋ถ๋ค์ ๋ค์ controller layer dto ๋ก ๋ณํํด์ ์ฌ์ฉํ๊ธฐ๋ ํฉ๋๋ค. ๋๋ฌด ํด๋์ค๊ฐ ๋ง์์ง๊ณ ์คํ๋ ค ๋ณต์กํด์ง๋ค๋ ๊ฒฝํฅ์ด ์์ด์ ์ด๋ฐ ํ ์ดํ์ ์์๋ ์ถ์ฒํ์ง ์์ง๋ง ์ด๋ฐ ๋ถ๋ถ๋ ์๊ตฌ๋ ํ๊ณ ๋๊ธฐ์
๋ ์ข์ ๊ฒ ๊ฐ์์ ๊ณต์ ๋๋ฆฝ๋๋ค ~
์ด ์ผ์ด์ค์์๋ ์์ ๊ท๋ชจ์ด๋ ๊ทธ๋ฅ service layer ์์ dto ๋ณํ์ ํ๋ ๊ฒ์ ์ถ์ฒํฉ๋๋ค ~ |
@@ -0,0 +1,30 @@
+package codesquad.service;
+
+import codesquad.entity.QuestionEntity;
+import codesquad.repository.QuestionRepository;
+
+import java.util.List;
+
+public class QuestionServiceImpl implements QuestionService {
+ private final QuestionRepository questionRepository;
+
+ public QuestionServiceImpl(QuestionRepository questionRepository) {
+ this.questionRepository = questionRepository;
+ }
+
+ @Override
+ public void postQuestion(QuestionEntity questionEntity) {
+ questionRepository.post(questionEntity);
+ questionRepository.setBaseTime(questionEntity);
+ }
+
+ @Override
+ public List<QuestionEntity> findQuestions() {
+ return questionRepository.findAll();
+ }
+
+ @Override
+ public QuestionEntity findQuestion(String id) {
+ return questionRepository.findAll().get(Integer.parseInt(id) - 1);
+ }
+} | Java | ์์ง 1๋จ๊ณ๋ผ์ ์ด๋ฐ ๋ถ๋ถ์ ๋ํ ์ฝ๋ฉํธ๋ ์ข ๋ ์น์ ํ ์ค๋ช
ํด์ฃผ์ด๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,24 @@
+package codesquad.entity;
+
+import lombok.*;
+
+@Setter
+@Getter
+@Builder
+@NoArgsConstructor
+@AllArgsConstructor
+public class QuestionEntity extends BaseTimeEntity {
+
+ private String writer;
+ private String title;
+ private String contents;
+
+ @Override
+ public String toString() {
+ return "QuestionEntity{" +
+ "writer='" + writer + '\'' +
+ ", title='" + title + '\'' +
+ ", contents='" + contents + '\'' +
+ '}';
+ }
+} | Java | @hyukjin-lee class๋ช
๋ง์ํ์ค๊น์?? |
@@ -0,0 +1,74 @@
+package codesquad.controller;
+
+import codesquad.AppConfig;
+import codesquad.dto.question.QuestionRequestDto;
+import codesquad.dto.question.QuestionResponseDto;
+import codesquad.entity.QuestionEntity;
+import codesquad.mapper.QuestionMapper;
+import codesquad.service.QuestionService;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
+import org.springframework.stereotype.Controller;
+import org.springframework.ui.Model;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+@Controller
+public class QuestionController {
+ ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
+ QuestionService questionService = applicationContext.getBean("questionService", QuestionService.class);
+
+ @GetMapping("/questions/post")
+ public String getQuestionForm() {
+ return "qna/form";
+ }
+
+ @PostMapping("/questions")
+ public String postQuestion(QuestionRequestDto questionRequestDto) {
+ QuestionEntity questionEntity = QuestionMapper.dtoToEntity(questionRequestDto);
+ questionService.postQuestion(questionEntity);
+ return "redirect:/questions";
+ }
+
+ @GetMapping("/questions")
+ public String getQuestionList(Model model) {
+ List<QuestionResponseDto> questions = questionService.findQuestions().stream()
+ .map(questionEntity -> QuestionMapper.entityToDto(questionEntity))
+ .collect(Collectors.toList());
+
+ model.addAttribute("questions", questions);
+
+ return "qna/list";
+ }
+
+ @GetMapping("/questions/{id}")
+ public String getQuestionShow(@PathVariable String id, Model model) {
+ QuestionResponseDto question = new QuestionResponseDto(questionService.findQuestion(id));
+
+ model.addAttribute("writer", question.getWriter());
+ model.addAttribute("title", question.getTitle());
+ model.addAttribute("contents", question.getContents());
+ model.addAttribute("date", question.getDate());
+
+ return "qna/show";
+ }
+
+ @GetMapping("/")
+ public String getHome(Model model) {
+ List<QuestionEntity> questionEntityList = questionService.findQuestions();
+ if (questionEntityList.size() == 0) {
+ return "qna/list";
+ }
+
+ List<QuestionResponseDto> questionResponseDtoList = questionService.findQuestions().stream()
+ .map(questionEntity -> QuestionMapper.entityToDto(questionEntity))
+ .collect(Collectors.toList());
+
+ model.addAttribute("questions", questionResponseDtoList);
+ return "qna/list";
+ }
+}
\ No newline at end of file | Java | > applicationcontext๋ก๋ถํฐ ์ง์ ๋น์ ๊ฐ์ ธ์ค์
์ ์ฌ์ฉํ์ ์ด์ ๊ฐ ๊ถ๊ธํฉ๋๋ค!
questionService๋ ๋ค์๊ณผ ๊ฐ์ด ์์ฑ์๋ฅผ ํตํด ์ฃผ์
๋์์ต๋๋ค.
**AppConfig**
```java
@Bean
public QuestionService questionService() {
return new QuestionServiceImpl(questionRepository());
}
@Bean
public QuestionRepository questionRepository() {
return new QuestionRepositoryImpl();
}
```
QuestionServiceImpl
```java
public QuestionServiceImpl(QuestionRepository questionRepository) {
this.questionRepository = questionRepository;
}
```
์์ฑ์ ์ฃผ์
์ ํ ๊ฒฝ์ฐ, `getBean()`์ ํตํด ๊ฐ์ฒด๋ฅผ ์ป์ด์์ ์ฌ์ฉํด์ผ ํฉ๋๋ค. |
@@ -0,0 +1,45 @@
+package codesquad.mapper;
+
+import codesquad.dto.question.QuestionRequestDto;
+import codesquad.dto.question.QuestionResponseDto;
+import codesquad.entity.QuestionEntity;
+
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+
+public class QuestionMapper {
+
+ public static QuestionEntity dtoToEntity(QuestionRequestDto questionRequestDto) {
+ if (questionRequestDto == null){
+ return null;
+ }
+
+ QuestionEntity.QuestionEntityBuilder questionEntity = QuestionEntity.builder();
+
+ questionEntity.writer(questionRequestDto.getWriter());
+ questionEntity.title(questionRequestDto.getTitle());
+ questionEntity.contents(questionRequestDto.getContents());
+
+ return questionEntity.build();
+ }
+
+ public static QuestionResponseDto entityToDto(QuestionEntity questionEntity) {
+ if (questionEntity == null) {
+ return null;
+ }
+
+ QuestionResponseDto.QuestionResponseDtoBuilder questionResponseDto = QuestionResponseDto.builder();
+
+ questionResponseDto.writer(questionEntity.getWriter());
+ questionResponseDto.title(questionEntity.getTitle());
+ questionResponseDto.contents(questionEntity.getContents());
+ questionResponseDto.date(localTimeToString(questionEntity.getCreatedDate()));
+
+ return questionResponseDto.build();
+ }
+
+ public static String localTimeToString(LocalDateTime localDateTime) {
+ String stringLocalTime = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
+ return stringLocalTime;
+ }
+} | Java | @hyukjin-lee ๋ต!!! ๊ธฐ์ตํ๊ฒ ์ต๋๋ค. ์ด๋ฒ์๋ ๋ณ๊ฒฝ ๊ฐ๋ฅ์ฑ์ ์ด์ด๋๋ setter ์ฌ์ฉ์ ์ง์ํ๊ณ , ํ์ํ ๋ฐ์ดํฐ๋ง ์ค์ ํ๊ณ ์ถ์ด Builder ํจํด์ ์ฌ์ฉํด๋ณด์์ต๋๋ค~ |
@@ -1,158 +1,89 @@
package codesquad.qua;
-import codesquad.answer.Answer;
-import codesquad.answer.AnswerRepository;
-import codesquad.user.User;
-import codesquad.utils.SessionUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
+import codesquad.exception.QuestionDeleteException;
+import codesquad.exception.QuestionEditException;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
-import java.util.NoSuchElementException;
@Controller
+@RequiredArgsConstructor
+@Slf4j
public class QuestionController {
- private final Logger logger = LoggerFactory.getLogger(this.getClass());
- @Autowired
- QuestionRepository questionRepository;
-
- @Autowired
- AnswerRepository answerRepository;
+ private final QuestionService questionService;
@GetMapping("/questions/form")
public String createForm(HttpSession session) {
- User user = SessionUtil.getUserBySession(session);
-
- if (user == null) {
+ if (!questionService.setCreateForm(session)) {
return "/login";
}
return "qna/form";
}
@PostMapping("/questions")
- public String create(Question question, HttpSession session) {
- User user = SessionUtil.getUserBySession(session);
-
- if (user == null) {
+ public String createQuestion(QuestionDto questionDto, HttpSession session) {
+ if (!questionService.create(questionDto, session)) {
return "/login";
}
- question.setWriter(user);
- questionRepository.save(question);
- logger.info("user : {}", question.getWriter().getName());
return "redirect:/";
}
@GetMapping("/")
- public String list(Model model) {
- model.addAttribute("question", questionRepository.findAll());
+ public String showQuestionList(Model model) {
+ model.addAttribute("question", questionService.list());
return "qna/list";
}
@GetMapping("/questions/{id}")
- public String qnaInfo(Model model, @PathVariable("id") Long id) {
- Question question = findQuestionById(id);
- model.addAttribute("question", question);
- model.addAttribute("count", countAnswers(question));
-
+ public String showQuestion(Model model, @PathVariable("id") Long id) {
+ model.addAttribute("question", questionService.findQuestionById(id));
+ model.addAttribute("count", questionService.countAnswers(id));
return "qna/show";
}
- @Transactional
@PutMapping("/questions/{id}")
- public String update(Question changedQuestion, @PathVariable("id") Long id, HttpSession session) {
- User user = SessionUtil.getUserBySession(session);
- Question savedQuestion = findQuestionById(id);
-
- if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ public String updateQuestion(QuestionDto changedQuestion, @PathVariable("id") Long id, HttpSession session) {
+ try {
+ questionService.update(changedQuestion, id, session);
+ } catch (QuestionEditException showException) {
return "qna/show_failed";
}
- logger.info("user: {}", user.getName());
- logger.info("question: {}", savedQuestion.getWriter());
-
- savedQuestion.update(changedQuestion);
-
return "redirect:/";
}
@GetMapping("/questions/{id}/updateForm")
public String updateForm(Model model, @PathVariable("id") Long id, HttpSession session) {
- User user = SessionUtil.getUserBySession(session);
- Question savedQuestion = findQuestionById(id);
-
- if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ try {
+ questionService.setUpdateForm(id, session);
+ } catch (QuestionEditException showException) {
return "qna/show_failed";
}
- logger.info("user: {}", user.getName());
- logger.info("question: {}", savedQuestion.getWriter());
-
- model.addAttribute("question", savedQuestion);
+ model.addAttribute("question", questionService.findQuestionById(id));
return "qna/updateForm";
}
@DeleteMapping("/questions/{id}")
- @Transactional
- public String remove(@PathVariable("id") Long id, HttpSession session) {
- User user = SessionUtil.getUserBySession(session);
- Question savedQuestion = findQuestionById(id);
-
- logger.info("user: {}", user.getName());
- logger.info("question: {}", savedQuestion.getWriter());
+ public String removeQuestion(@PathVariable("id") Long id, HttpSession session) {
- if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ try {
+ questionService.remove(id, session);
+ } catch (QuestionEditException showException) {
return "qna/show_failed";
- }
-
- if (!canDeleteQuestion(savedQuestion, user)) {
+ } catch (QuestionDeleteException deleteException) {
return "qna/delete_failed";
}
- savedQuestion.changeDeleteFlag();
-
- for (Answer answer : savedQuestion.getAnswers()) {
- answer.changeDeletedFlag();
- }
-
return "redirect:/questions/" + id;
}
-
- private Question findQuestionById(Long id) {
- return questionRepository.findById(id)
- .orElseThrow(NoSuchElementException::new);
- }
-
- private boolean isQuestionMatchUser(User loginUser, Question question) {
- return question.equalsWriter(loginUser);
- }
-
- private boolean canDeleteQuestion(Question deletedQuestion, User user) {
- if (deletedQuestion.hasAnswers()) {
- for (Answer answer : deletedQuestion.getAnswers()) {
- if (!answer.equalsWriter(user)) {
- return false;
- }
- }
- }
- return true;
- }
-
- private int countAnswers(Question question) {
- int count = 0;
- for (Answer answer : question.getAnswers()) {
- if (!answer.isDeletedFlag()) {
- count++;
- }
- }
- return count;
- }
}
\ No newline at end of file | Java | Question์ ๋ํ Exception์ customizing ํ ์ด์ ์
๋๋ค
QuestionEditException์ ํด๋น ์ง๋ฌธ์๊ฐ ์๋๊ธฐ ๋๋ฌธ์ ์ญ์ ํ ์ ์๋ ๊ฒฝ์ฐ,
QuestionDeleteException์ ๋ค๋ฅธ User์ ๋ต๊ธ์ด ์กด์ฌํ์ฌ ์ญ์ ํ ์ ์๋ ๊ฒฝ์ฐ์
๋๋ค
์ฒ์์๋ boolean์ผ๋ก ์ฒ๋ฆฌํ๋ ค๋ค๊ฐ ๋ ๊ฐ์ง ๊ฒฝ์ฐ๊ฐ ์๊ฒ ๋์ด(=๋ ๊ฐ์ง view)
exception์ ๋ง๋ค์์ต๋๋ค |
@@ -1,10 +1,15 @@
package codesquad.user;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+
import javax.persistence.*;
import java.util.Objects;
@Entity
+@NoArgsConstructor
+@Getter
public class User {
@Id
@@ -20,43 +25,14 @@ public class User {
private String email;
- public String getUserId() {
- return userId;
- }
-
- public void setUserId(String userId) {
- this.userId = userId;
- }
-
- public String getPassword() {
- return password;
+ User(SignUpUserDto signUpUserDto) {
+ userId = signUpUserDto.getUserId();
+ password = signUpUserDto.getPassword();
+ name = signUpUserDto.getName();
+ email = signUpUserDto.getEmail();
}
- public void setPassword(String password) {
- this.password = password;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getEmail() {
- return email;
- }
-
- public void setEmail(String email) {
- this.email = email;
- }
-
- public Long getId() {
- return id;
- }
-
- public void update(User user) {
+ public void update(SignUpUserDto user) {
if (equalsPassword(user.getPassword())) {
name = user.getName();
email = user.getEmail();
@@ -67,6 +43,10 @@ public boolean equalsPassword(String password) {
return this.password.equals(password);
}
+ public boolean equalsPassword(LoginUserDto loginUserDto) {
+ return password.equals(loginUserDto.getPassword());
+ }
+
public boolean equalsId(Long id) {
return this.id.equals(id);
}
@@ -76,15 +56,11 @@ public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
- return Objects.equals(getId(), user.getId()) &&
- Objects.equals(getUserId(), user.getUserId()) &&
- Objects.equals(getPassword(), user.getPassword()) &&
- Objects.equals(getName(), user.getName()) &&
- Objects.equals(getEmail(), user.getEmail());
+ return Objects.equals(getId(), user.getId());
}
@Override
public int hashCode() {
- return Objects.hash(getId(), getUserId(), getPassword(), getName(), getEmail());
+ return Objects.hash(getId());
}
} | Java | ์ ๋ฒ์ ๋ง์ํด์ฃผ์ equals์ ๋ํ ๋ฆฌ๋ทฐ ์๊ฐํด๋ดค์ต๋๋ค
๋ง์๋๋ก ๊ด๊ณํ DB์์๋ "์๋ณ์(id)" ๊ฐ ๊ณ ์ ํ ๊ฐ์ผ๋ก, ํด๋น ์๋ณ์๊ฐ ๋์ผํ๋ค๋ฉด ๊ฐ์ ๋ฐ์ดํฐ๋ผ๊ณ ์ธ์ํ๋๋ฐ equals๋ฅผ overridingํ๋ค๋ฉด ๋ชจ๋ ํ๋์ ๊ฐ์ด ๋์ผํด์ผ ๊ฐ์ ๊ฐ์ฒด๋ผ๊ณ ํ๋จํฉ๋๋ค
equals๋ฅผ ๊ตณ์ด overridingํ ํ์์๋ ์ํฉ์์ overriding์ ํ๋ค๋ฉด HashSet์ด๋ HashMap์ ์ํฅ์ ์ฃผ์ด ์์์น ๋ชปํ ์ํฉ์ด ๋ฐ์ํ ์๋ ์์ต๋๋ค
๋ฐ๋ผ์ User๋ฅผ ์๋ณํ๊ธฐ ์ํด์๋ "id"๋ก ์ถฉ๋ถํ๊ธฐ ๋๋ฌธ์ equals๋ฅผ overridingํ์ง ์์๋๋๋ค ๋ผ๋ ์๊ฐ์
๋๋ค |
@@ -0,0 +1,126 @@
+package codesquad.qua;
+
+import codesquad.answer.Answer;
+import codesquad.exception.QuestionDeleteException;
+import codesquad.exception.QuestionEditException;
+import codesquad.user.User;
+import codesquad.utils.SessionUtil;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.servlet.http.HttpSession;
+import java.util.List;
+import java.util.NoSuchElementException;
+
+@Slf4j
+@RequiredArgsConstructor
+@Service
+public class QuestionService {
+
+ private final QuestionRepository questionRepository;
+
+ public boolean setCreateForm(HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+
+ return user != null;
+ }
+
+ public boolean create(QuestionDto questionDto, HttpSession session) {
+ log.info("์์ฑ์ = {}", questionDto.getWriter());
+ log.info("์ ๋ชฉ = {}", questionDto.getTitle());
+
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return false;
+ }
+
+ questionRepository.save(new Question(questionDto, user));
+
+ return true;
+ }
+
+ public List<Question> list() {
+ return questionRepository.findAll();
+ }
+
+ public void setUpdateForm(long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ log.info("user: {}", user.getName());
+ log.info("question: {}", savedQuestion.getWriter());
+ }
+
+ @Transactional
+ public void update(QuestionDto changedQuestion, long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ log.info("user: {}", user.getName());
+ log.info("question content: {}", changedQuestion.getContents());
+ log.info("question title: {}", changedQuestion.getTitle());
+
+ savedQuestion.update(changedQuestion);
+ }
+
+ @Transactional
+ public void remove(long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ log.info("user: {}", user.getName());
+ log.info("question: {}", savedQuestion.getWriter());
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ if (!canDeleteQuestion(savedQuestion, user)) {
+ throw new QuestionDeleteException();
+ }
+
+ savedQuestion.deleteQuestion();
+ }
+
+ public long countAnswers(long questionId) {
+ Long countAnswer = questionRepository.countNotDeletedAnswers(questionId);
+
+ if (countAnswer == null) {
+ return 0L;
+ }
+
+ return countAnswer;
+ }
+
+ public Question findQuestionById(Long id) {
+ return questionRepository.findById(id)
+ .orElseThrow(NoSuchElementException::new);
+ }
+
+ private boolean canDeleteQuestion(Question deletedQuestion, User user) {
+ if (deletedQuestion.hasAnswers()) {
+ for (Answer answer : deletedQuestion.getAnswers()) {
+ if (!answer.equalsWriter(user)) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ private boolean isQuestionMatchUser(User loginUser, Question question) {
+ log.info("match User? = {}", question.equalsWriter(loginUser));
+ return question.equalsWriter(loginUser);
+ }
+} | Java | canDeleteQuestion์ ์ง๋ฌธ์ ์ญ์ ํ ์ ์๋์ง ํ๋จํ๋ ๋ฉ์๋์
๋๋ค
- ๋ต๊ธ์ด ์์ ๊ฒฝ์ฐ ์ญ์ ๊ฐ๋ฅ
- ๋ต๊ธ์ด ์์ผ๋ ์์ฑ์ ๋ชจ๋ ์ง๋ฌธ ์์ฑ์์ ๊ฐ์ ๊ฒฝ์ฐ ์ญ์ ๊ฐ๋ฅ
ํด๋น ๋ฉ์๋๋ Question์ด ์ญ์ ๋ ์ ์์ด?๋ผ๊ณ ๋ฌป๊ณ , Question์ด ์ญ์ ๋ ์ ์์ด/์์ด๋ฅผ ํ๋จํฉ๋๋ค
๊ทธ๋์ ์ ๋ ์ด ๋ถ๋ถ์ด Question์๊ฒ ๋ฌผ์ด๋ณด๊ณ Question์ด ๊ฒฐ์ ํ๋ ๊ฒ์ด๋ผ๋ ์๊ฐ์ด ๋ค์ด Question ํด๋์ค์ ์์ด์ผํ ๊น๋ผ๋ ์๊ฐ์ ํ์ต๋๋ค.
ํ์ง๋ง ์ด ๋
ผ๋ฆฌ๋ผ๋ฉด ์๋ isQuestionMatchUser(์ง๋ฌธ ์์ฑ์์ ๋ก๊ทธ์ธ ๋ User๊ฐ ๊ฐ์์ง ํ๋จํ๋ ๋ฉ์๋)๋ Question์ ์์ด์ผํ์ง ์์๊น๋ผ๋ ์๊ฐ์ ํ์ง๋ง, ๊ทธ๋ ๊ฒ ๋๋ฉด Question ํด๋์ค๊ฐ ๋๋ฌด ๋ฌด๊ฑฐ์์ง์ง ์์๊น๋ผ๋ ์๊ฐ๋ ๋ค์์ต๋๋ค
๋ฆฌ๋ทฐ์ด๋์ ์ด๋ป๊ฒ ์๊ฐํ์๋์ง ๊ถ๊ธํด์ comment ๋จ๊ฒจ๋ด
๋๋ค! |
@@ -0,0 +1,62 @@
+package codesquad.answer;
+
+import codesquad.qua.Question;
+import codesquad.qua.QuestionRepository;
+import codesquad.response.Result;
+import codesquad.user.User;
+import codesquad.utils.SessionUtil;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.servlet.http.HttpSession;
+import java.util.NoSuchElementException;
+
+@Service
+@Slf4j
+@RequiredArgsConstructor
+public class AnswerService {
+
+ private final AnswerRepository answerRepository;
+ private final QuestionRepository questionRepository;
+
+ public Result<ResponseAnswerDto> create(long questionId, RequestAnswerDto requestAnswerDto, HttpSession session) {
+ log.info("comment = {}", requestAnswerDto.getComment());
+
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return Result.fail("๋ก๊ทธ์ธ ํ์ธ์");
+ }
+
+ Question question = questionRepository.findById(questionId)
+ .orElseThrow(NoSuchElementException::new);
+
+ Answer answer = new Answer(question, user, requestAnswerDto.getComment());
+ answer.addQuestion(question);
+ answerRepository.save(answer);
+
+ return Result.ok(answer.toResponseAnswerDto());
+ }
+
+ @Transactional
+ public Result<ResponseAnswerDto> remove(long questionId, long answerId, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return Result.fail("๋ก๊ทธ์ธ ํ์ธ์");
+ }
+
+ Answer answer = answerRepository.findQuestionFetchJoinById(answerId)
+ .orElseThrow(NoSuchElementException::new);
+
+ if (!answer.equalsWriter(user)) {
+ return Result.fail("๋ค๋ฅธ ์ฌ๋ ๋ต๊ธ์ ์ญ์ ๋ชปํด์");
+ }
+
+ answer.changeDeletedFlag();
+
+ return Result.ok(answer.toResponseAnswerDto());
+ }
+}
\ No newline at end of file | Java | Answer์ ๋น์ฆ๋์ค ๋ก์ง์ ๋ด๋นํ๋ AnswerService์์ Question๊ด๋ จ ๋ฐ์ดํฐ๊ฐ ํ์ํ ๋ QuestionRepository๋ฅผ ์ง์ ์ฐธ์กฐํ๋ ๋ฐฉ๋ฒ๋ ์์ง๋ง, QuestionService๋ฅผ ํตํด ์ฐธ์กฐํ๋๋ก ํ ์๋ ์์ ๊ฑฐ ๊ฐ์๋ฐ ์ด๋ค ์ฐจ์ด๊ฐ ์์๊น์? |
@@ -0,0 +1,62 @@
+package codesquad.answer;
+
+import codesquad.qua.Question;
+import codesquad.qua.QuestionRepository;
+import codesquad.response.Result;
+import codesquad.user.User;
+import codesquad.utils.SessionUtil;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.servlet.http.HttpSession;
+import java.util.NoSuchElementException;
+
+@Service
+@Slf4j
+@RequiredArgsConstructor
+public class AnswerService {
+
+ private final AnswerRepository answerRepository;
+ private final QuestionRepository questionRepository;
+
+ public Result<ResponseAnswerDto> create(long questionId, RequestAnswerDto requestAnswerDto, HttpSession session) {
+ log.info("comment = {}", requestAnswerDto.getComment());
+
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return Result.fail("๋ก๊ทธ์ธ ํ์ธ์");
+ }
+
+ Question question = questionRepository.findById(questionId)
+ .orElseThrow(NoSuchElementException::new);
+
+ Answer answer = new Answer(question, user, requestAnswerDto.getComment());
+ answer.addQuestion(question);
+ answerRepository.save(answer);
+
+ return Result.ok(answer.toResponseAnswerDto());
+ }
+
+ @Transactional
+ public Result<ResponseAnswerDto> remove(long questionId, long answerId, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return Result.fail("๋ก๊ทธ์ธ ํ์ธ์");
+ }
+
+ Answer answer = answerRepository.findQuestionFetchJoinById(answerId)
+ .orElseThrow(NoSuchElementException::new);
+
+ if (!answer.equalsWriter(user)) {
+ return Result.fail("๋ค๋ฅธ ์ฌ๋ ๋ต๊ธ์ ์ญ์ ๋ชปํด์");
+ }
+
+ answer.changeDeletedFlag();
+
+ return Result.ok(answer.toResponseAnswerDto());
+ }
+}
\ No newline at end of file | Java | Answer๋ฅผ db์์ ์กฐํํ๋ ๋ก์ง ๋ค์ ์ธ์
์ ์ ์ฒดํฌ๊ฐ ์ด๋ค์ง๊ณ ์์ต๋๋ค. ๊ฐ์ ํ ์ ์ด ์์ด๋ณด์ด๋๋ฐ ์ด๋ป๊ฒ ์๊ฐํ์๋์? |
@@ -0,0 +1,27 @@
+package codesquad.answer;
+
+import codesquad.response.Result;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.web.bind.annotation.*;
+
+import javax.servlet.http.HttpSession;
+
+@RestController
+@RequiredArgsConstructor
+@Slf4j
+public class ApiAnswerController {
+
+ private final AnswerService answerService;
+
+ @PostMapping("/questions/{question-id}/answers")
+ public Result<ResponseAnswerDto> create(@PathVariable("question-id") Long questionId, @RequestBody RequestAnswerDto requestAnswerDto, HttpSession session) {
+ return answerService.create(questionId, requestAnswerDto, session);
+ }
+
+ @DeleteMapping("/questions/{question-id}/answers/{answer-id}")
+ public Result<ResponseAnswerDto> remove(@PathVariable("question-id") Long questionId,
+ @PathVariable("answer-id") Long answerId, HttpSession session) {
+ return answerService.remove(questionId, answerId, session);
+ }
+} | Java | ์ด ์์ฒญ์ ์๋ต ์ํ์ฝ๋๋ ์ด๋ป๊ฒ ๋๊ฐ๊น์? |
@@ -0,0 +1,126 @@
+package codesquad.qua;
+
+import codesquad.answer.Answer;
+import codesquad.exception.QuestionDeleteException;
+import codesquad.exception.QuestionEditException;
+import codesquad.user.User;
+import codesquad.utils.SessionUtil;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.servlet.http.HttpSession;
+import java.util.List;
+import java.util.NoSuchElementException;
+
+@Slf4j
+@RequiredArgsConstructor
+@Service
+public class QuestionService {
+
+ private final QuestionRepository questionRepository;
+
+ public boolean setCreateForm(HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+
+ return user != null;
+ }
+
+ public boolean create(QuestionDto questionDto, HttpSession session) {
+ log.info("์์ฑ์ = {}", questionDto.getWriter());
+ log.info("์ ๋ชฉ = {}", questionDto.getTitle());
+
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return false;
+ }
+
+ questionRepository.save(new Question(questionDto, user));
+
+ return true;
+ }
+
+ public List<Question> list() {
+ return questionRepository.findAll();
+ }
+
+ public void setUpdateForm(long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ log.info("user: {}", user.getName());
+ log.info("question: {}", savedQuestion.getWriter());
+ }
+
+ @Transactional
+ public void update(QuestionDto changedQuestion, long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ log.info("user: {}", user.getName());
+ log.info("question content: {}", changedQuestion.getContents());
+ log.info("question title: {}", changedQuestion.getTitle());
+
+ savedQuestion.update(changedQuestion);
+ }
+
+ @Transactional
+ public void remove(long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ log.info("user: {}", user.getName());
+ log.info("question: {}", savedQuestion.getWriter());
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ if (!canDeleteQuestion(savedQuestion, user)) {
+ throw new QuestionDeleteException();
+ }
+
+ savedQuestion.deleteQuestion();
+ }
+
+ public long countAnswers(long questionId) {
+ Long countAnswer = questionRepository.countNotDeletedAnswers(questionId);
+
+ if (countAnswer == null) {
+ return 0L;
+ }
+
+ return countAnswer;
+ }
+
+ public Question findQuestionById(Long id) {
+ return questionRepository.findById(id)
+ .orElseThrow(NoSuchElementException::new);
+ }
+
+ private boolean canDeleteQuestion(Question deletedQuestion, User user) {
+ if (deletedQuestion.hasAnswers()) {
+ for (Answer answer : deletedQuestion.getAnswers()) {
+ if (!answer.equalsWriter(user)) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ private boolean isQuestionMatchUser(User loginUser, Question question) {
+ log.info("match User? = {}", question.equalsWriter(loginUser));
+ return question.equalsWriter(loginUser);
+ }
+} | Java | 1. Service๊ฐ์ฒด๊ฐ HttpSession๋ฅผ ์์์ผํ ํ์๊ฐ ์์๊น์?
2. ํ์ฌ ์์ฒญ์ ๋ํ ์ธ์
์ ๋ณด๊ฐ ์กด์ฌํ๋์ง ํ๋จํ๋ ๋ฉ์๋๋ก ๋ณด์ด๋๋ฐ, ํ์ฌ ๋ฉ์๋๋ช
์ด ์ค์ ์ญํ ์ ์ถฉ๋ถํ ์ค๋ช
ํ์ง ๋ชปํ๋ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,126 @@
+package codesquad.qua;
+
+import codesquad.answer.Answer;
+import codesquad.exception.QuestionDeleteException;
+import codesquad.exception.QuestionEditException;
+import codesquad.user.User;
+import codesquad.utils.SessionUtil;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.servlet.http.HttpSession;
+import java.util.List;
+import java.util.NoSuchElementException;
+
+@Slf4j
+@RequiredArgsConstructor
+@Service
+public class QuestionService {
+
+ private final QuestionRepository questionRepository;
+
+ public boolean setCreateForm(HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+
+ return user != null;
+ }
+
+ public boolean create(QuestionDto questionDto, HttpSession session) {
+ log.info("์์ฑ์ = {}", questionDto.getWriter());
+ log.info("์ ๋ชฉ = {}", questionDto.getTitle());
+
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return false;
+ }
+
+ questionRepository.save(new Question(questionDto, user));
+
+ return true;
+ }
+
+ public List<Question> list() {
+ return questionRepository.findAll();
+ }
+
+ public void setUpdateForm(long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ log.info("user: {}", user.getName());
+ log.info("question: {}", savedQuestion.getWriter());
+ }
+
+ @Transactional
+ public void update(QuestionDto changedQuestion, long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ log.info("user: {}", user.getName());
+ log.info("question content: {}", changedQuestion.getContents());
+ log.info("question title: {}", changedQuestion.getTitle());
+
+ savedQuestion.update(changedQuestion);
+ }
+
+ @Transactional
+ public void remove(long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ log.info("user: {}", user.getName());
+ log.info("question: {}", savedQuestion.getWriter());
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ if (!canDeleteQuestion(savedQuestion, user)) {
+ throw new QuestionDeleteException();
+ }
+
+ savedQuestion.deleteQuestion();
+ }
+
+ public long countAnswers(long questionId) {
+ Long countAnswer = questionRepository.countNotDeletedAnswers(questionId);
+
+ if (countAnswer == null) {
+ return 0L;
+ }
+
+ return countAnswer;
+ }
+
+ public Question findQuestionById(Long id) {
+ return questionRepository.findById(id)
+ .orElseThrow(NoSuchElementException::new);
+ }
+
+ private boolean canDeleteQuestion(Question deletedQuestion, User user) {
+ if (deletedQuestion.hasAnswers()) {
+ for (Answer answer : deletedQuestion.getAnswers()) {
+ if (!answer.equalsWriter(user)) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ private boolean isQuestionMatchUser(User loginUser, Question question) {
+ log.info("match User? = {}", question.equalsWriter(loginUser));
+ return question.equalsWriter(loginUser);
+ }
+} | Java | ์ธ์
์ ์ ์ ์ ๋ณด๊ฐ ํฌํจ๋์ผ๋งํ๋ ๋ชจ๋ ๋ฉ์๋์์ ํด๋น ๋ก์ง์ด ์์ฑ๋๊ณ ์๋๋ฐ ์ด๋ป๊ฒ ํ๋ฉด ์ค๋ณต์ ์ค์ผ ์ ์์๊น์? |
@@ -0,0 +1,126 @@
+package codesquad.qua;
+
+import codesquad.answer.Answer;
+import codesquad.exception.QuestionDeleteException;
+import codesquad.exception.QuestionEditException;
+import codesquad.user.User;
+import codesquad.utils.SessionUtil;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.servlet.http.HttpSession;
+import java.util.List;
+import java.util.NoSuchElementException;
+
+@Slf4j
+@RequiredArgsConstructor
+@Service
+public class QuestionService {
+
+ private final QuestionRepository questionRepository;
+
+ public boolean setCreateForm(HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+
+ return user != null;
+ }
+
+ public boolean create(QuestionDto questionDto, HttpSession session) {
+ log.info("์์ฑ์ = {}", questionDto.getWriter());
+ log.info("์ ๋ชฉ = {}", questionDto.getTitle());
+
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return false;
+ }
+
+ questionRepository.save(new Question(questionDto, user));
+
+ return true;
+ }
+
+ public List<Question> list() {
+ return questionRepository.findAll();
+ }
+
+ public void setUpdateForm(long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ log.info("user: {}", user.getName());
+ log.info("question: {}", savedQuestion.getWriter());
+ }
+
+ @Transactional
+ public void update(QuestionDto changedQuestion, long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ log.info("user: {}", user.getName());
+ log.info("question content: {}", changedQuestion.getContents());
+ log.info("question title: {}", changedQuestion.getTitle());
+
+ savedQuestion.update(changedQuestion);
+ }
+
+ @Transactional
+ public void remove(long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ log.info("user: {}", user.getName());
+ log.info("question: {}", savedQuestion.getWriter());
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ if (!canDeleteQuestion(savedQuestion, user)) {
+ throw new QuestionDeleteException();
+ }
+
+ savedQuestion.deleteQuestion();
+ }
+
+ public long countAnswers(long questionId) {
+ Long countAnswer = questionRepository.countNotDeletedAnswers(questionId);
+
+ if (countAnswer == null) {
+ return 0L;
+ }
+
+ return countAnswer;
+ }
+
+ public Question findQuestionById(Long id) {
+ return questionRepository.findById(id)
+ .orElseThrow(NoSuchElementException::new);
+ }
+
+ private boolean canDeleteQuestion(Question deletedQuestion, User user) {
+ if (deletedQuestion.hasAnswers()) {
+ for (Answer answer : deletedQuestion.getAnswers()) {
+ if (!answer.equalsWriter(user)) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ private boolean isQuestionMatchUser(User loginUser, Question question) {
+ log.info("match User? = {}", question.equalsWriter(loginUser));
+ return question.equalsWriter(loginUser);
+ }
+} | Java | ๋ฉ์๋๋ช
์ ๋ณด๊ณ Question์ ๋ํ ๋น์ฆ๋์ค๋ก์ง์ ์ํํ๋ ๊ฐ์ฒด์์ Form๊น์ง ๊ด์ฌํ๋ ๊ฑด๊ฐ๋ผ๋ ์๊ฐ์ด ๋ค์์ต๋๋ค. |
@@ -0,0 +1,126 @@
+package codesquad.qua;
+
+import codesquad.answer.Answer;
+import codesquad.exception.QuestionDeleteException;
+import codesquad.exception.QuestionEditException;
+import codesquad.user.User;
+import codesquad.utils.SessionUtil;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.servlet.http.HttpSession;
+import java.util.List;
+import java.util.NoSuchElementException;
+
+@Slf4j
+@RequiredArgsConstructor
+@Service
+public class QuestionService {
+
+ private final QuestionRepository questionRepository;
+
+ public boolean setCreateForm(HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+
+ return user != null;
+ }
+
+ public boolean create(QuestionDto questionDto, HttpSession session) {
+ log.info("์์ฑ์ = {}", questionDto.getWriter());
+ log.info("์ ๋ชฉ = {}", questionDto.getTitle());
+
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return false;
+ }
+
+ questionRepository.save(new Question(questionDto, user));
+
+ return true;
+ }
+
+ public List<Question> list() {
+ return questionRepository.findAll();
+ }
+
+ public void setUpdateForm(long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ log.info("user: {}", user.getName());
+ log.info("question: {}", savedQuestion.getWriter());
+ }
+
+ @Transactional
+ public void update(QuestionDto changedQuestion, long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ log.info("user: {}", user.getName());
+ log.info("question content: {}", changedQuestion.getContents());
+ log.info("question title: {}", changedQuestion.getTitle());
+
+ savedQuestion.update(changedQuestion);
+ }
+
+ @Transactional
+ public void remove(long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ log.info("user: {}", user.getName());
+ log.info("question: {}", savedQuestion.getWriter());
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ if (!canDeleteQuestion(savedQuestion, user)) {
+ throw new QuestionDeleteException();
+ }
+
+ savedQuestion.deleteQuestion();
+ }
+
+ public long countAnswers(long questionId) {
+ Long countAnswer = questionRepository.countNotDeletedAnswers(questionId);
+
+ if (countAnswer == null) {
+ return 0L;
+ }
+
+ return countAnswer;
+ }
+
+ public Question findQuestionById(Long id) {
+ return questionRepository.findById(id)
+ .orElseThrow(NoSuchElementException::new);
+ }
+
+ private boolean canDeleteQuestion(Question deletedQuestion, User user) {
+ if (deletedQuestion.hasAnswers()) {
+ for (Answer answer : deletedQuestion.getAnswers()) {
+ if (!answer.equalsWriter(user)) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ private boolean isQuestionMatchUser(User loginUser, Question question) {
+ log.info("match User? = {}", question.equalsWriter(loginUser));
+ return question.equalsWriter(loginUser);
+ }
+} | Java | ์ ๋ ์ฝ๋ ์ฌ์ฌ์ฉ์ฑ ์ธก๋ฉด์์ ์๊ฐํด๋ดค์ ๋ ์ด ๋ก์ง์ด ํด๋น Service์์๋ง ์ฌ์ฉ๋๋ ๊ฑฐ๋ผ๋ฉด Question์ด ๋ฌด๊ฑฐ์์ง๋ ๊ฒ์ ๊ณ ๋ คํด์ Service์์ ๋ด๋นํ๋๋ก ๊ตฌํํ ๊ฒ ๊ฐ์ต๋๋ค. ๋ฐ๋ฉด ์ด Service๋ฅผ ๋ฒ์ด๋ ์์ญ์์๋ ์ฌ์ฉ๋๋ ๋ก์ง์ด๋ผ๋ฉด Question์์ ๋ด๋นํ๋ ๊ฒ์ด ์ค๋ณต์ ์ค์ด๋ ๋ฐฉ๋ฒ์ด์ง ์์๊น ์๊ฐํฉ๋๋ค! |
@@ -0,0 +1,62 @@
+package codesquad.answer;
+
+import codesquad.qua.Question;
+import codesquad.qua.QuestionRepository;
+import codesquad.response.Result;
+import codesquad.user.User;
+import codesquad.utils.SessionUtil;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.servlet.http.HttpSession;
+import java.util.NoSuchElementException;
+
+@Service
+@Slf4j
+@RequiredArgsConstructor
+public class AnswerService {
+
+ private final AnswerRepository answerRepository;
+ private final QuestionRepository questionRepository;
+
+ public Result<ResponseAnswerDto> create(long questionId, RequestAnswerDto requestAnswerDto, HttpSession session) {
+ log.info("comment = {}", requestAnswerDto.getComment());
+
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return Result.fail("๋ก๊ทธ์ธ ํ์ธ์");
+ }
+
+ Question question = questionRepository.findById(questionId)
+ .orElseThrow(NoSuchElementException::new);
+
+ Answer answer = new Answer(question, user, requestAnswerDto.getComment());
+ answer.addQuestion(question);
+ answerRepository.save(answer);
+
+ return Result.ok(answer.toResponseAnswerDto());
+ }
+
+ @Transactional
+ public Result<ResponseAnswerDto> remove(long questionId, long answerId, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return Result.fail("๋ก๊ทธ์ธ ํ์ธ์");
+ }
+
+ Answer answer = answerRepository.findQuestionFetchJoinById(answerId)
+ .orElseThrow(NoSuchElementException::new);
+
+ if (!answer.equalsWriter(user)) {
+ return Result.fail("๋ค๋ฅธ ์ฌ๋ ๋ต๊ธ์ ์ญ์ ๋ชปํด์");
+ }
+
+ answer.changeDeletedFlag();
+
+ return Result.ok(answer.toResponseAnswerDto());
+ }
+}
\ No newline at end of file | Java | ResponseAnswerDto๋ฅผ Result๋ก ํ๋ฒ ๋ ๊ฐ์ธ๋ ๋ฐฉ์์ผ๋ก ๊ตฌํํ์
จ๋๋ฐ ์ด๋ค ์ด์ ๊ฐ ์์๊น์? |
@@ -1,158 +1,89 @@
package codesquad.qua;
-import codesquad.answer.Answer;
-import codesquad.answer.AnswerRepository;
-import codesquad.user.User;
-import codesquad.utils.SessionUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
+import codesquad.exception.QuestionDeleteException;
+import codesquad.exception.QuestionEditException;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
-import java.util.NoSuchElementException;
@Controller
+@RequiredArgsConstructor
+@Slf4j
public class QuestionController {
- private final Logger logger = LoggerFactory.getLogger(this.getClass());
- @Autowired
- QuestionRepository questionRepository;
-
- @Autowired
- AnswerRepository answerRepository;
+ private final QuestionService questionService;
@GetMapping("/questions/form")
public String createForm(HttpSession session) {
- User user = SessionUtil.getUserBySession(session);
-
- if (user == null) {
+ if (!questionService.setCreateForm(session)) {
return "/login";
}
return "qna/form";
}
@PostMapping("/questions")
- public String create(Question question, HttpSession session) {
- User user = SessionUtil.getUserBySession(session);
-
- if (user == null) {
+ public String createQuestion(QuestionDto questionDto, HttpSession session) {
+ if (!questionService.create(questionDto, session)) {
return "/login";
}
- question.setWriter(user);
- questionRepository.save(question);
- logger.info("user : {}", question.getWriter().getName());
return "redirect:/";
}
@GetMapping("/")
- public String list(Model model) {
- model.addAttribute("question", questionRepository.findAll());
+ public String showQuestionList(Model model) {
+ model.addAttribute("question", questionService.list());
return "qna/list";
}
@GetMapping("/questions/{id}")
- public String qnaInfo(Model model, @PathVariable("id") Long id) {
- Question question = findQuestionById(id);
- model.addAttribute("question", question);
- model.addAttribute("count", countAnswers(question));
-
+ public String showQuestion(Model model, @PathVariable("id") Long id) {
+ model.addAttribute("question", questionService.findQuestionById(id));
+ model.addAttribute("count", questionService.countAnswers(id));
return "qna/show";
}
- @Transactional
@PutMapping("/questions/{id}")
- public String update(Question changedQuestion, @PathVariable("id") Long id, HttpSession session) {
- User user = SessionUtil.getUserBySession(session);
- Question savedQuestion = findQuestionById(id);
-
- if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ public String updateQuestion(QuestionDto changedQuestion, @PathVariable("id") Long id, HttpSession session) {
+ try {
+ questionService.update(changedQuestion, id, session);
+ } catch (QuestionEditException showException) {
return "qna/show_failed";
}
- logger.info("user: {}", user.getName());
- logger.info("question: {}", savedQuestion.getWriter());
-
- savedQuestion.update(changedQuestion);
-
return "redirect:/";
}
@GetMapping("/questions/{id}/updateForm")
public String updateForm(Model model, @PathVariable("id") Long id, HttpSession session) {
- User user = SessionUtil.getUserBySession(session);
- Question savedQuestion = findQuestionById(id);
-
- if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ try {
+ questionService.setUpdateForm(id, session);
+ } catch (QuestionEditException showException) {
return "qna/show_failed";
}
- logger.info("user: {}", user.getName());
- logger.info("question: {}", savedQuestion.getWriter());
-
- model.addAttribute("question", savedQuestion);
+ model.addAttribute("question", questionService.findQuestionById(id));
return "qna/updateForm";
}
@DeleteMapping("/questions/{id}")
- @Transactional
- public String remove(@PathVariable("id") Long id, HttpSession session) {
- User user = SessionUtil.getUserBySession(session);
- Question savedQuestion = findQuestionById(id);
-
- logger.info("user: {}", user.getName());
- logger.info("question: {}", savedQuestion.getWriter());
+ public String removeQuestion(@PathVariable("id") Long id, HttpSession session) {
- if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ try {
+ questionService.remove(id, session);
+ } catch (QuestionEditException showException) {
return "qna/show_failed";
- }
-
- if (!canDeleteQuestion(savedQuestion, user)) {
+ } catch (QuestionDeleteException deleteException) {
return "qna/delete_failed";
}
- savedQuestion.changeDeleteFlag();
-
- for (Answer answer : savedQuestion.getAnswers()) {
- answer.changeDeletedFlag();
- }
-
return "redirect:/questions/" + id;
}
-
- private Question findQuestionById(Long id) {
- return questionRepository.findById(id)
- .orElseThrow(NoSuchElementException::new);
- }
-
- private boolean isQuestionMatchUser(User loginUser, Question question) {
- return question.equalsWriter(loginUser);
- }
-
- private boolean canDeleteQuestion(Question deletedQuestion, User user) {
- if (deletedQuestion.hasAnswers()) {
- for (Answer answer : deletedQuestion.getAnswers()) {
- if (!answer.equalsWriter(user)) {
- return false;
- }
- }
- }
- return true;
- }
-
- private int countAnswers(Question question) {
- int count = 0;
- for (Answer answer : question.getAnswers()) {
- if (!answer.isDeletedFlag()) {
- count++;
- }
- }
- return count;
- }
}
\ No newline at end of file | Java | ์ด๋ฏธ ๋ณด์
จ์ ์๋ ์์ง๋ง ํ๋ฒ ์ฝ์ด๋ณด์๋ฉด ์ข์ ๊ฑฐ ๊ฐ์ ๊ณต์ ๋๋ฆฝ๋๋ค!
https://tecoble.techcourse.co.kr/post/2020-08-17-custom-exception/ |
@@ -1,158 +1,89 @@
package codesquad.qua;
-import codesquad.answer.Answer;
-import codesquad.answer.AnswerRepository;
-import codesquad.user.User;
-import codesquad.utils.SessionUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
+import codesquad.exception.QuestionDeleteException;
+import codesquad.exception.QuestionEditException;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
-import java.util.NoSuchElementException;
@Controller
+@RequiredArgsConstructor
+@Slf4j
public class QuestionController {
- private final Logger logger = LoggerFactory.getLogger(this.getClass());
- @Autowired
- QuestionRepository questionRepository;
-
- @Autowired
- AnswerRepository answerRepository;
+ private final QuestionService questionService;
@GetMapping("/questions/form")
public String createForm(HttpSession session) {
- User user = SessionUtil.getUserBySession(session);
-
- if (user == null) {
+ if (!questionService.setCreateForm(session)) {
return "/login";
}
return "qna/form";
}
@PostMapping("/questions")
- public String create(Question question, HttpSession session) {
- User user = SessionUtil.getUserBySession(session);
-
- if (user == null) {
+ public String createQuestion(QuestionDto questionDto, HttpSession session) {
+ if (!questionService.create(questionDto, session)) {
return "/login";
}
- question.setWriter(user);
- questionRepository.save(question);
- logger.info("user : {}", question.getWriter().getName());
return "redirect:/";
}
@GetMapping("/")
- public String list(Model model) {
- model.addAttribute("question", questionRepository.findAll());
+ public String showQuestionList(Model model) {
+ model.addAttribute("question", questionService.list());
return "qna/list";
}
@GetMapping("/questions/{id}")
- public String qnaInfo(Model model, @PathVariable("id") Long id) {
- Question question = findQuestionById(id);
- model.addAttribute("question", question);
- model.addAttribute("count", countAnswers(question));
-
+ public String showQuestion(Model model, @PathVariable("id") Long id) {
+ model.addAttribute("question", questionService.findQuestionById(id));
+ model.addAttribute("count", questionService.countAnswers(id));
return "qna/show";
}
- @Transactional
@PutMapping("/questions/{id}")
- public String update(Question changedQuestion, @PathVariable("id") Long id, HttpSession session) {
- User user = SessionUtil.getUserBySession(session);
- Question savedQuestion = findQuestionById(id);
-
- if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ public String updateQuestion(QuestionDto changedQuestion, @PathVariable("id") Long id, HttpSession session) {
+ try {
+ questionService.update(changedQuestion, id, session);
+ } catch (QuestionEditException showException) {
return "qna/show_failed";
}
- logger.info("user: {}", user.getName());
- logger.info("question: {}", savedQuestion.getWriter());
-
- savedQuestion.update(changedQuestion);
-
return "redirect:/";
}
@GetMapping("/questions/{id}/updateForm")
public String updateForm(Model model, @PathVariable("id") Long id, HttpSession session) {
- User user = SessionUtil.getUserBySession(session);
- Question savedQuestion = findQuestionById(id);
-
- if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ try {
+ questionService.setUpdateForm(id, session);
+ } catch (QuestionEditException showException) {
return "qna/show_failed";
}
- logger.info("user: {}", user.getName());
- logger.info("question: {}", savedQuestion.getWriter());
-
- model.addAttribute("question", savedQuestion);
+ model.addAttribute("question", questionService.findQuestionById(id));
return "qna/updateForm";
}
@DeleteMapping("/questions/{id}")
- @Transactional
- public String remove(@PathVariable("id") Long id, HttpSession session) {
- User user = SessionUtil.getUserBySession(session);
- Question savedQuestion = findQuestionById(id);
-
- logger.info("user: {}", user.getName());
- logger.info("question: {}", savedQuestion.getWriter());
+ public String removeQuestion(@PathVariable("id") Long id, HttpSession session) {
- if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ try {
+ questionService.remove(id, session);
+ } catch (QuestionEditException showException) {
return "qna/show_failed";
- }
-
- if (!canDeleteQuestion(savedQuestion, user)) {
+ } catch (QuestionDeleteException deleteException) {
return "qna/delete_failed";
}
- savedQuestion.changeDeleteFlag();
-
- for (Answer answer : savedQuestion.getAnswers()) {
- answer.changeDeletedFlag();
- }
-
return "redirect:/questions/" + id;
}
-
- private Question findQuestionById(Long id) {
- return questionRepository.findById(id)
- .orElseThrow(NoSuchElementException::new);
- }
-
- private boolean isQuestionMatchUser(User loginUser, Question question) {
- return question.equalsWriter(loginUser);
- }
-
- private boolean canDeleteQuestion(Question deletedQuestion, User user) {
- if (deletedQuestion.hasAnswers()) {
- for (Answer answer : deletedQuestion.getAnswers()) {
- if (!answer.equalsWriter(user)) {
- return false;
- }
- }
- }
- return true;
- }
-
- private int countAnswers(Question question) {
- int count = 0;
- for (Answer answer : question.getAnswers()) {
- if (!answer.isDeletedFlag()) {
- count++;
- }
- }
- return count;
- }
}
\ No newline at end of file | Java | ์ค ๋ง์ต๋๋ค ์ ๋ ์ฌ์ฉ์ ์ ์ ์์ธ๋ฅผ ์ฌ์ฉํ๊ธฐ ์ ์ ์ฌ๋ ค์ฃผ์ ๋งํฌ๋ฅผ ๋ดค์ต๋๋ค.
๋งํฌ์ ๋ํด์ ๋ณด๋ฉด ๊ตณ์ด ๋๋ ํ์ ์์ด, IllegalArgumentException, IllegalstateException์ ๋ฐ๋ผ ๋ค๋ฅธ ๋ทฐ๋ฅผ ๋ณด์ฌ์ค ์ ์์ง๋ง, ์ด๋๋ ๋ช
์์ ์ผ๋ก ๋ณด์ฌ์ฃผ๋๊ฒ ๋ซ์ง ์์๊น ๋ผ๋ ์๊ฐ์ ํ์ต๋๋ค |
@@ -0,0 +1,126 @@
+package codesquad.qua;
+
+import codesquad.answer.Answer;
+import codesquad.exception.QuestionDeleteException;
+import codesquad.exception.QuestionEditException;
+import codesquad.user.User;
+import codesquad.utils.SessionUtil;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.servlet.http.HttpSession;
+import java.util.List;
+import java.util.NoSuchElementException;
+
+@Slf4j
+@RequiredArgsConstructor
+@Service
+public class QuestionService {
+
+ private final QuestionRepository questionRepository;
+
+ public boolean setCreateForm(HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+
+ return user != null;
+ }
+
+ public boolean create(QuestionDto questionDto, HttpSession session) {
+ log.info("์์ฑ์ = {}", questionDto.getWriter());
+ log.info("์ ๋ชฉ = {}", questionDto.getTitle());
+
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return false;
+ }
+
+ questionRepository.save(new Question(questionDto, user));
+
+ return true;
+ }
+
+ public List<Question> list() {
+ return questionRepository.findAll();
+ }
+
+ public void setUpdateForm(long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ log.info("user: {}", user.getName());
+ log.info("question: {}", savedQuestion.getWriter());
+ }
+
+ @Transactional
+ public void update(QuestionDto changedQuestion, long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ log.info("user: {}", user.getName());
+ log.info("question content: {}", changedQuestion.getContents());
+ log.info("question title: {}", changedQuestion.getTitle());
+
+ savedQuestion.update(changedQuestion);
+ }
+
+ @Transactional
+ public void remove(long id, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+ Question savedQuestion = findQuestionById(id);
+
+ log.info("user: {}", user.getName());
+ log.info("question: {}", savedQuestion.getWriter());
+
+ if (user == null || !isQuestionMatchUser(user, savedQuestion)) {
+ throw new QuestionEditException();
+ }
+
+ if (!canDeleteQuestion(savedQuestion, user)) {
+ throw new QuestionDeleteException();
+ }
+
+ savedQuestion.deleteQuestion();
+ }
+
+ public long countAnswers(long questionId) {
+ Long countAnswer = questionRepository.countNotDeletedAnswers(questionId);
+
+ if (countAnswer == null) {
+ return 0L;
+ }
+
+ return countAnswer;
+ }
+
+ public Question findQuestionById(Long id) {
+ return questionRepository.findById(id)
+ .orElseThrow(NoSuchElementException::new);
+ }
+
+ private boolean canDeleteQuestion(Question deletedQuestion, User user) {
+ if (deletedQuestion.hasAnswers()) {
+ for (Answer answer : deletedQuestion.getAnswers()) {
+ if (!answer.equalsWriter(user)) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ private boolean isQuestionMatchUser(User loginUser, Question question) {
+ log.info("match User? = {}", question.equalsWriter(loginUser));
+ return question.equalsWriter(loginUser);
+ }
+} | Java | updateํ๊ธฐ ์ํด์๋ ์กฐ๊ฑด์ด ํ์ํ๋ฐ ์ด ์กฐ๊ฑด์ ๊ฒ์ฆํ๋ ๊ฒ๋ Question์ ๋ํ ๋น์ฆ๋์ค๋ก์ง์ด๋ผ๊ณ ์๊ฐํด์ ์์ฑํ์ต๋๋ค.
ํน์ ๋ฉ์๋๋ช
์ ์์ ํ๋๊ฒ ์ข์๋ณด์ผ ๊ฒ ๊ฐ์ ๋ง์์ด์ค๊น์~~?? |
@@ -0,0 +1,62 @@
+package codesquad.answer;
+
+import codesquad.qua.Question;
+import codesquad.qua.QuestionRepository;
+import codesquad.response.Result;
+import codesquad.user.User;
+import codesquad.utils.SessionUtil;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.servlet.http.HttpSession;
+import java.util.NoSuchElementException;
+
+@Service
+@Slf4j
+@RequiredArgsConstructor
+public class AnswerService {
+
+ private final AnswerRepository answerRepository;
+ private final QuestionRepository questionRepository;
+
+ public Result<ResponseAnswerDto> create(long questionId, RequestAnswerDto requestAnswerDto, HttpSession session) {
+ log.info("comment = {}", requestAnswerDto.getComment());
+
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return Result.fail("๋ก๊ทธ์ธ ํ์ธ์");
+ }
+
+ Question question = questionRepository.findById(questionId)
+ .orElseThrow(NoSuchElementException::new);
+
+ Answer answer = new Answer(question, user, requestAnswerDto.getComment());
+ answer.addQuestion(question);
+ answerRepository.save(answer);
+
+ return Result.ok(answer.toResponseAnswerDto());
+ }
+
+ @Transactional
+ public Result<ResponseAnswerDto> remove(long questionId, long answerId, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return Result.fail("๋ก๊ทธ์ธ ํ์ธ์");
+ }
+
+ Answer answer = answerRepository.findQuestionFetchJoinById(answerId)
+ .orElseThrow(NoSuchElementException::new);
+
+ if (!answer.equalsWriter(user)) {
+ return Result.fail("๋ค๋ฅธ ์ฌ๋ ๋ต๊ธ์ ์ญ์ ๋ชปํด์");
+ }
+
+ answer.changeDeletedFlag();
+
+ return Result.ok(answer.toResponseAnswerDto());
+ }
+}
\ No newline at end of file | Java | ์ค,, ์ด ๋ถ๋ถ์ DB ์ ๊ทผ์ ๋ฌด๊ฑฐ์ด ์์
์ด๊ธฐ ๋๋ฌธ์ ์ธ์
์ ์ฒดํฌํ๊ณ ๋์ DB ์ ๊ทผํ๋ ๊ฒ์ด ์ข์๋ณด์
๋๋ค
๊ฐ์ฌํฉ๋๋ค! |
@@ -0,0 +1,62 @@
+package codesquad.answer;
+
+import codesquad.qua.Question;
+import codesquad.qua.QuestionRepository;
+import codesquad.response.Result;
+import codesquad.user.User;
+import codesquad.utils.SessionUtil;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.servlet.http.HttpSession;
+import java.util.NoSuchElementException;
+
+@Service
+@Slf4j
+@RequiredArgsConstructor
+public class AnswerService {
+
+ private final AnswerRepository answerRepository;
+ private final QuestionRepository questionRepository;
+
+ public Result<ResponseAnswerDto> create(long questionId, RequestAnswerDto requestAnswerDto, HttpSession session) {
+ log.info("comment = {}", requestAnswerDto.getComment());
+
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return Result.fail("๋ก๊ทธ์ธ ํ์ธ์");
+ }
+
+ Question question = questionRepository.findById(questionId)
+ .orElseThrow(NoSuchElementException::new);
+
+ Answer answer = new Answer(question, user, requestAnswerDto.getComment());
+ answer.addQuestion(question);
+ answerRepository.save(answer);
+
+ return Result.ok(answer.toResponseAnswerDto());
+ }
+
+ @Transactional
+ public Result<ResponseAnswerDto> remove(long questionId, long answerId, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return Result.fail("๋ก๊ทธ์ธ ํ์ธ์");
+ }
+
+ Answer answer = answerRepository.findQuestionFetchJoinById(answerId)
+ .orElseThrow(NoSuchElementException::new);
+
+ if (!answer.equalsWriter(user)) {
+ return Result.fail("๋ค๋ฅธ ์ฌ๋ ๋ต๊ธ์ ์ญ์ ๋ชปํด์");
+ }
+
+ answer.changeDeletedFlag();
+
+ return Result.ok(answer.toResponseAnswerDto());
+ }
+}
\ No newline at end of file | Java | ์ด ๋ถ๋ถ๋ง ๊ทธ๋ฐ๊ฒ ์๋๋ผ ๋ค๋ฅธ ๊ณณ๋ ๊ทธ๋ ๊ฒ ์์ฑ๋์ด์๋ค์!! |
@@ -0,0 +1,62 @@
+package codesquad.answer;
+
+import codesquad.qua.Question;
+import codesquad.qua.QuestionRepository;
+import codesquad.response.Result;
+import codesquad.user.User;
+import codesquad.utils.SessionUtil;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.servlet.http.HttpSession;
+import java.util.NoSuchElementException;
+
+@Service
+@Slf4j
+@RequiredArgsConstructor
+public class AnswerService {
+
+ private final AnswerRepository answerRepository;
+ private final QuestionRepository questionRepository;
+
+ public Result<ResponseAnswerDto> create(long questionId, RequestAnswerDto requestAnswerDto, HttpSession session) {
+ log.info("comment = {}", requestAnswerDto.getComment());
+
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return Result.fail("๋ก๊ทธ์ธ ํ์ธ์");
+ }
+
+ Question question = questionRepository.findById(questionId)
+ .orElseThrow(NoSuchElementException::new);
+
+ Answer answer = new Answer(question, user, requestAnswerDto.getComment());
+ answer.addQuestion(question);
+ answerRepository.save(answer);
+
+ return Result.ok(answer.toResponseAnswerDto());
+ }
+
+ @Transactional
+ public Result<ResponseAnswerDto> remove(long questionId, long answerId, HttpSession session) {
+ User user = SessionUtil.getUserBySession(session);
+
+ if (user == null) {
+ return Result.fail("๋ก๊ทธ์ธ ํ์ธ์");
+ }
+
+ Answer answer = answerRepository.findQuestionFetchJoinById(answerId)
+ .orElseThrow(NoSuchElementException::new);
+
+ if (!answer.equalsWriter(user)) {
+ return Result.fail("๋ค๋ฅธ ์ฌ๋ ๋ต๊ธ์ ์ญ์ ๋ชปํด์");
+ }
+
+ answer.changeDeletedFlag();
+
+ return Result.ok(answer.toResponseAnswerDto());
+ }
+}
\ No newline at end of file | Java | ๋ฏธ์
๋ช
์ธ์์ Result๋ฅผ ๋ฐํํ๋ผ๊ณ ํด์ ์ด๋ ๊ฒ ์์ฑํ์ต๋๋ค! |
@@ -0,0 +1,27 @@
+package codesquad.answer;
+
+import codesquad.response.Result;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.web.bind.annotation.*;
+
+import javax.servlet.http.HttpSession;
+
+@RestController
+@RequiredArgsConstructor
+@Slf4j
+public class ApiAnswerController {
+
+ private final AnswerService answerService;
+
+ @PostMapping("/questions/{question-id}/answers")
+ public Result<ResponseAnswerDto> create(@PathVariable("question-id") Long questionId, @RequestBody RequestAnswerDto requestAnswerDto, HttpSession session) {
+ return answerService.create(questionId, requestAnswerDto, session);
+ }
+
+ @DeleteMapping("/questions/{question-id}/answers/{answer-id}")
+ public Result<ResponseAnswerDto> remove(@PathVariable("question-id") Long questionId,
+ @PathVariable("answer-id") Long answerId, HttpSession session) {
+ return answerService.remove(questionId, answerId, session);
+ }
+} | Java | create๋ฉ์๋๋ ์ฑ๊ณต, ์คํจ ์ฌ๋ถ์์ด Result ๋ฅผ ๋ฐํํ๊ธฐ ๋๋ฌธ์ 200 OK๊ฐ ๋๊ฐ ๊ฒ์ด๋ผ๊ณ ์๊ฐํฉ๋๋ค! |
@@ -0,0 +1,13 @@
+export class NetworkError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = "NetworkError";
+ }
+}
+
+export class HttpError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = "HttpError";
+ }
+} | JavaScript | ์ฌ์ฉ๋์ง ์๋ ์ฝ๋๊ฐ ๋จ์์๋ค์, ํน์ ์ด๋ค ์๋๋ก ๋ง๋์
จ์๊น์?! |
@@ -0,0 +1,39 @@
+function formatUrl(config) {
+ const { href, query } = config;
+ const searchParams = new URLSearchParams(query);
+
+ return `${href}?${searchParams.toString()}`;
+}
+
+function formatHeaders(headersRecord) {
+ const headers = new Headers();
+
+ headers.append("content-type", "application/json");
+ Object.entries(headersRecord).forEach(([key, value]) => {
+ headers.append(key, value);
+ });
+ return headers;
+}
+
+export async function createAPIRequest(request) {
+ const response = await fetch(
+ formatUrl({
+ href: request.url,
+ query: request.query ?? {},
+ }),
+ {
+ method: request.method || "GET",
+ headers: formatHeaders(request.headers),
+ body: request.body,
+ },
+ ).catch((error) => {
+ throw new Error("Network error: ", error);
+ });
+
+ if (!response.ok) {
+ throw new Error("Http error: ", response.status);
+ }
+
+ const data = !response.body ? null : await response.json();
+ return data;
+} | JavaScript | [MDN Error() ์์ฑ์](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Error/Error) ๋ฌธ์ ์ฒจ๋ถ๋๋ฆฝ๋๋ค!
error ๊ฐ์ฒด๋ ์ฒซ๋ฒ์งธ ์ธ์๋ก `message`๋ฅผ ๋ฐ์ผ๋ฉฐ, ๋๋ฒ์งธ ์ธ๋ฒ์งธ ์ธ์๊ฐ ์๊ธดํ์ง๋ง, ๋นํ์ค์
๋๋ค!
์ค์ ๋ก ์๋ฌ๋ฅผ ์ผ์ผ์ผ๋ณด๋ฉด alert์์ `Http error: ` , `Network error: `
ํด๋น ๋ฌธ์์ด๋ง ๋
ธ์ถ๋๋ ๊ฑธ ํ์ธํ์ค ์ ์์๊ฑฐ์์! |
@@ -0,0 +1,39 @@
+function formatUrl(config) {
+ const { href, query } = config;
+ const searchParams = new URLSearchParams(query);
+
+ return `${href}?${searchParams.toString()}`;
+}
+
+function formatHeaders(headersRecord) {
+ const headers = new Headers();
+
+ headers.append("content-type", "application/json");
+ Object.entries(headersRecord).forEach(([key, value]) => {
+ headers.append(key, value);
+ });
+ return headers;
+}
+
+export async function createAPIRequest(request) {
+ const response = await fetch(
+ formatUrl({
+ href: request.url,
+ query: request.query ?? {},
+ }),
+ {
+ method: request.method || "GET",
+ headers: formatHeaders(request.headers),
+ body: request.body,
+ },
+ ).catch((error) => {
+ throw new Error("Network error: ", error);
+ });
+
+ if (!response.ok) {
+ throw new Error("Http error: ", response.status);
+ }
+
+ const data = !response.body ? null : await response.json();
+ return data;
+} | JavaScript | ์ด ํ์ผ์ ๋ํ ์ ๋ฐ์ ์ธ ๋๋์ `formatUrl`, `formatHeaders` ํจ์์ ํ์์ฑ์ ๋ชจ๋ฅด๊ฒ ๋ค.. ์ด๊ธด ํฉ๋๋ค!
`createAPIRequest` ์ฒ๋ผ ์ ์ฒด์ ์ธ ์์ฒญ์ ๋ํ ๊ณตํต ํจ์๋ ์์ผ๋ฉด ๋น์ฐํ ์ข๋ค!
์ด๊ธดํ๋ฐ ํํ์ ๋ํด์๋ ์กฐ๊ธ ์์ฌ์ด ๋ถ๋ถ์ด ์๋ค๊ณ ๋๊ปด์ง๋๋ค!
์ฝ๋ฉํธ๋ก ํ๋ ํ๋ ์์ฑํด๋ณผ๊ฒ์! |
@@ -0,0 +1,39 @@
+function formatUrl(config) {
+ const { href, query } = config;
+ const searchParams = new URLSearchParams(query);
+
+ return `${href}?${searchParams.toString()}`;
+}
+
+function formatHeaders(headersRecord) {
+ const headers = new Headers();
+
+ headers.append("content-type", "application/json");
+ Object.entries(headersRecord).forEach(([key, value]) => {
+ headers.append(key, value);
+ });
+ return headers;
+}
+
+export async function createAPIRequest(request) {
+ const response = await fetch(
+ formatUrl({
+ href: request.url,
+ query: request.query ?? {},
+ }),
+ {
+ method: request.method || "GET",
+ headers: formatHeaders(request.headers),
+ body: request.body,
+ },
+ ).catch((error) => {
+ throw new Error("Network error: ", error);
+ });
+
+ if (!response.ok) {
+ throw new Error("Http error: ", response.status);
+ }
+
+ const data = !response.body ? null : await response.json();
+ return data;
+} | JavaScript | `headers.append("content-type", "application/json")`;
์ฌ์ค์ ์ญํ ์ ๋ชจ๋ ์์ฒญ์ ํด๋น ํค๋๋ฅผ ๋ํด์ฃผ๋ ์ญํ ๋ฐ์ ์๋๋ฐ
`createAPIRequest`์ headers์์ ํด์ฃผ๋ฉด ๋์ง ์์๊น ์ถ๋ค์!
```js
headers: {
...request.headers
'content-type': "application/json"
}
``` |
@@ -0,0 +1,39 @@
+function formatUrl(config) {
+ const { href, query } = config;
+ const searchParams = new URLSearchParams(query);
+
+ return `${href}?${searchParams.toString()}`;
+}
+
+function formatHeaders(headersRecord) {
+ const headers = new Headers();
+
+ headers.append("content-type", "application/json");
+ Object.entries(headersRecord).forEach(([key, value]) => {
+ headers.append(key, value);
+ });
+ return headers;
+}
+
+export async function createAPIRequest(request) {
+ const response = await fetch(
+ formatUrl({
+ href: request.url,
+ query: request.query ?? {},
+ }),
+ {
+ method: request.method || "GET",
+ headers: formatHeaders(request.headers),
+ body: request.body,
+ },
+ ).catch((error) => {
+ throw new Error("Network error: ", error);
+ });
+
+ if (!response.ok) {
+ throw new Error("Http error: ", response.status);
+ }
+
+ const data = !response.body ? null : await response.json();
+ return data;
+} | JavaScript | ๊ฐ์ฅ ๋จผ์ searchParams์ ์ฌ๋ถ์ ๊ด๊ณ ์์ด URL์ `?`๊ฐ ๋ถ์ต๋๋ค!
๊ทธ๋ฆฌ๊ณ `createAPIRequest`๋ณด๋ค ์ค์ ์์ฒญํ๋ ๊ณณ์์ ์ฌ์ฉํ๋ ๊ฒ์ด ์ด๋จ๊น ์ถ๊ธดํฉ๋๋ค!
์ด๋ค ์๋ฏธ๋๋ฉด์!
fetch API๋ฅผ ์ฌ์ฉํ๋ ๊ฒ์ ๋๋ฌ๋ด๊ณ , ์ฌ์ฉ์ฒ์์ ์ด๋ฅผ ์์๋ณผ ์ ์์ผ๋ฉด ๋ ์ข๊ฒ ๋ค๋ ์๊ฐ์
๋๋ค.
`fetchPopularMovies`๋ fetch API์ ์ง์ ์ฌ์ฉํ ์ ์๋ ํํ์ `createAPIRequest`์ ์๋ง์ ์ธ์๋ฅผ ๋๊ฒจ์ค๋๋ค.
`createAPIRequest`๋ ์ด ์ธ์๋ฅผ ๊ฐ๊ณตํด์ fetch API์ ์ฌ์ฉํ ์ ์๋ ํํ๋ก ๋ณ๊ฒฝ์ ํ๊ณ ์๋๋ฐ์!
์ด ํจ์๋ฅผ ์ฌ์ฉํ๋ ์
์ฅ์์ `createAPIRequest`์ ๋์๊ณผ ํ๋ผ๋ฏธํฐ๋ฅผ ๋ชจ๋ฅด๋๋ผ๋
fetch API์ request ์ ๋ณด์ ๋ง๋ ์ธ์๋ฅผ ๋๊ฒจ์ฃผ๋ฉด, ํ์ํ ์ถ๊ฐ์ ์ธ ์ฒ๋ฆฌ๋ฅผ ํด์ ์์ฒญ์ ํด์ค๋ค! ๊ฐ ๋ ์ ์์ ๊ฒ ๊ฐ์์~
๊ทธ๋ฐ ์๋ฏธ์์, fetch๋ ์ฒซ๋ฒ์งธ ์ธ์๋ก URL์ ๋ฐ์ผ๋, createAPIRequest์์ ์ฌ์ฉ๋๋ค๋ฉด,
createAPIRequest๋ ์ธ์๋ก fetch์ request ์ ๋ณด์ ๋์ผํ ํํ์ ์ธ์๋ฅผ ๋ฐ์ ์ ์๊ฒ ๋๊ณ , ์ฌ์ฉํ๋ ์
์ฅ์์ ์ถ๊ฐ์ ์ธ ์ฝ๋ ํ์ต์ด ํ์ํ๊ฒ๋ ๊ฒ ๊ฐ์์~ |
@@ -0,0 +1,39 @@
+function formatUrl(config) {
+ const { href, query } = config;
+ const searchParams = new URLSearchParams(query);
+
+ return `${href}?${searchParams.toString()}`;
+}
+
+function formatHeaders(headersRecord) {
+ const headers = new Headers();
+
+ headers.append("content-type", "application/json");
+ Object.entries(headersRecord).forEach(([key, value]) => {
+ headers.append(key, value);
+ });
+ return headers;
+}
+
+export async function createAPIRequest(request) {
+ const response = await fetch(
+ formatUrl({
+ href: request.url,
+ query: request.query ?? {},
+ }),
+ {
+ method: request.method || "GET",
+ headers: formatHeaders(request.headers),
+ body: request.body,
+ },
+ ).catch((error) => {
+ throw new Error("Network error: ", error);
+ });
+
+ if (!response.ok) {
+ throw new Error("Http error: ", response.status);
+ }
+
+ const data = !response.body ? null : await response.json();
+ return data;
+} | JavaScript | ์ฝ๋ฉํธ๊ฐ ๋ง์ด ๊ธธ์ด์ก๋ค์.. ใ
ใ
ใ
ใ
์์ฝํ์๋ฉด, ์ธํฐํ์ด์ค๋ฅผ ๋๋ฃ๊ฐ ๋ฐ๋ก ๋ฏ์ด๋ณด์ง ์์๋ ๋ฐ๋ก ์ดํดํ ์ ์๋ ํํ๋ก ์์ฑํ์..! ์
๋๋ค |
@@ -0,0 +1,39 @@
+function formatUrl(config) {
+ const { href, query } = config;
+ const searchParams = new URLSearchParams(query);
+
+ return `${href}?${searchParams.toString()}`;
+}
+
+function formatHeaders(headersRecord) {
+ const headers = new Headers();
+
+ headers.append("content-type", "application/json");
+ Object.entries(headersRecord).forEach(([key, value]) => {
+ headers.append(key, value);
+ });
+ return headers;
+}
+
+export async function createAPIRequest(request) {
+ const response = await fetch(
+ formatUrl({
+ href: request.url,
+ query: request.query ?? {},
+ }),
+ {
+ method: request.method || "GET",
+ headers: formatHeaders(request.headers),
+ body: request.body,
+ },
+ ).catch((error) => {
+ throw new Error("Network error: ", error);
+ });
+
+ if (!response.ok) {
+ throw new Error("Http error: ", response.status);
+ }
+
+ const data = !response.body ? null : await response.json();
+ return data;
+} | JavaScript | `data` ๋ณ์๋ฅผ ์์ฑํ ํ์ํ ์์ด ๋ฐ๋ก ๊ฒฐ๊ณผ๊ฐ์ ๋ฐํํ๋ฉด ๋ ๊ฒ ๊ฐ๋ค์~ |
@@ -0,0 +1,37 @@
+import "./components/layout/app-header.js";
+import "./components/movie/movie-card.js";
+import "./components/movie/movie-list.js";
+import "./components/movie/movie-container.js";
+
+import { html } from "./utils/template.js";
+
+class App extends HTMLElement {
+ constructor() {
+ super();
+ this.attachShadow({ mode: "open" });
+ }
+
+ connectedCallback() {
+ this.render();
+ }
+
+ render() {
+ this.shadowRoot.innerHTML = this.template();
+ }
+
+ template() {
+ return html`
+ <style>
+ * {
+ padding-bottom: 48px;
+ }
+ </style>
+ <app-header></app-header>
+ <main>
+ <movie-container></movie-container>
+ </main>
+ `;
+ }
+}
+
+customElements.define("movie-app", App); | JavaScript | ์ ๊ฑฐ ํด๋ ๊ด์ฐฎ์ ์คํ์ผ ๊ฐ์๋ฐ ์ด๋ค ์๋ฏธ๊ฐ ์์๊น์? |
@@ -0,0 +1,2 @@
+export const html = String.raw;
+export const css = String.raw; | JavaScript | ๋ง์ฐฌ๊ฐ์ง๋ก ์ฌ์ฉ๋์ง ์๊ณ ์๋ค์! |
@@ -0,0 +1,58 @@
+import endedPopularMovies from "../fixtures/ended-popular-movies.json";
+
+describe("์ํ ๋ชฉ๋ก", () => {
+ beforeEach(() => {
+ const url = "http://localhost:8080";
+ cy.visit(url);
+
+ cy.get("movie-app")
+ .as("movieApp")
+ .shadow()
+ .find("movie-container")
+ .as("movieContainer")
+ .shadow()
+ .find("movie-list")
+ .as("movieList")
+ .shadow()
+ .find("movie-card")
+ .as("movieCard");
+ });
+
+ it("์ต์ด ๋ก๋์ 20๊ฐ์ ์ํ ์นด๋๋ฅผ ๋ณด์ฌ์ค๋ค.", () => {
+ cy.get("@movieCard").should("have.length", 20);
+ });
+
+ it("๋๋ณด๊ธฐ ๋ฒํผ ํด๋ฆญ์ 20๊ฐ์ ์ํ๋ฅผ ์ถ๊ฐ๋ก ๋ณด์ฌ์ค๋ค.", () => {
+ cy.get("@movieContainer").shadow().find(".show-more").as("showMoreButton");
+
+ cy.get("@movieCard").should("have.length", 20);
+ cy.get("@showMoreButton").contains("๋๋ณด๊ธฐ").click();
+ cy.get("@movieCard").should("have.length", 40);
+ });
+
+ it("๋ก๋ฉ์ค์ผ ๋๋ ์ค์ผ๋ ํค ์นด๋๋ฅผ ๋ณด์ฌ์ค๋ค.", () => {
+ cy.intercept("GET", "**/popular*", (req) => {
+ req.on("response", (res) => {
+ res.setDelay(1000); // Delay the response to simulate loading
+ });
+ }).as("getPopularMoviesDelayed");
+
+ cy.reload();
+ cy.get("@movieCard").shadow().find(".skeleton").should("exist");
+ cy.wait("@getPopularMoviesDelayed");
+
+ cy.get("@movieCard").should("have.length", 20);
+ });
+
+ it("์ํ ๋ชฉ๋ก์ ๋์ด์ ๋ถ๋ฌ์ฌ ์ ์์ผ๋ฉด '๋๋ณด๊ธฐ' ๋ฒํผ์ด ์ฌ๋ผ์ง๋ค.", () => {
+ cy.intercept("GET", "**/popular*", endedPopularMovies).as(
+ "getEndedPopularMovies",
+ );
+ cy.get("@movieContainer").shadow().find(".show-more").as("showMoreButton");
+ cy.get("@showMoreButton").should("exist");
+ cy.get("@showMoreButton").click();
+
+ cy.wait("@getEndedPopularMovies");
+ cy.get("@movieContainer").shadow().find("show-more").should("not.exist");
+ });
+}); | JavaScript | ํ
์คํธ๊ฐ ๋ชจ๋ ํดํผ์ผ์ด์ค๋ฅผ ๊ฐ์ ํ๊ณ ์์ฑ๋ ๊ฒ ๊ฐ์์!
๋คํธ์ํฌ ์๋ฌ๋ HTTP ์๋ฌ์ ๊ดํ ์ํฉ์ ์ ์ ํ๊ฒ ์์ฑ๋ ์ฝ๋๋๋ก ๋์ํ๋์ง๋ ํ์ธํ๋ฉด ์ข์ ๊ฒ ๊ฐ๋ค์! |
@@ -0,0 +1,143 @@
+import StarFilled from "../../../images/star_filled.png";
+import { html } from "../../utils/template.js";
+
+const BASE_URL = "https://image.tmdb.org/t/p/w220_and_h330_face";
+
+class MovieCard extends HTMLElement {
+ static get observedAttributes() {
+ return ["posterPath", "title", "voteAverage", "isLoading"];
+ }
+
+ constructor() {
+ super();
+ this.attachShadow({ mode: "open" });
+ }
+
+ get posterPath() {
+ return this.getAttribute("posterPath");
+ }
+
+ get title() {
+ return this.getAttribute("title");
+ }
+
+ get voteAverage() {
+ return this.getAttribute("voteAverage");
+ }
+
+ get isLoading() {
+ return this.getAttribute("isLoading") === "true";
+ }
+
+ attributeChangedCallback(name, oldValue, newValue) {
+ if (oldValue !== newValue) {
+ this.render();
+ }
+ }
+
+ connectedCallback() {
+ this.render();
+ }
+
+ render() {
+ const state = {
+ posterPath: this.posterPath,
+ title: this.title,
+ voteAverage: this.voteAverage,
+ isLoading: this.isLoading,
+ };
+ this.shadowRoot.innerHTML = this.template(state);
+ }
+
+ template({ posterPath, title, voteAverage, isLoading }) {
+ return html`
+ <style>
+ .movie-card {
+ display: flex;
+ flex-direction: column;
+ }
+
+ .movie-thumbnail {
+ border-radius: 8px;
+ width: 180px;
+ height: 270px;
+ background-size: contain;
+ }
+
+ .movie-title {
+ margin-top: 16px;
+ font-size: 1.2rem;
+ font-weight: bold;
+ }
+
+ .movie-score {
+ margin-top: 16px;
+ font-size: 1.2rem;
+ }
+
+ .movie-score::after {
+ margin-left: 8px;
+ }
+
+ a {
+ color: inherit;
+ text-decoration: none;
+ }
+
+ .movie-title.skeleton::after,
+ .movie-score.skeleton::after {
+ font-size: 0;
+ content: "loading";
+ }
+
+ .movie-card .skeleton {
+ background: linear-gradient(-90deg, #aaa, #f0f0f0, #aaa, #f0f0f0);
+ background-size: 400%;
+ animation: skeleton-animation 5s infinite ease-out;
+ border-radius: 8px;
+ }
+
+ @keyframes skeleton-animation {
+ 0% {
+ background-position: 0% 50%;
+ }
+ 50% {
+ background-position: 100% 50%;
+ }
+ 100% {
+ background-position: 0% 50%;
+ }
+ }
+ </style>
+ <li>
+ ${isLoading
+ ? html`
+ <div class="movie-card">
+ <div class="movie-thumbnail skeleton"></div>
+ <p class="movie-title skeleton"></p>
+ <p class="movie-score skeleton"></p>
+ </div>
+ `
+ : html`
+ <a href="#">
+ <div class="movie-card">
+ <img
+ class="movie-thumbnail"
+ src="${BASE_URL}/${posterPath}"
+ loading="lazy"
+ alt="${title}"
+ />
+ <p class="movie-title">${title}</p>
+ <p class="movie-score">
+ <img src="${StarFilled}" alt="๋ณ์ " />
+ ${Number(voteAverage).toFixed(1)}
+ </p>
+ </div>
+ </a>
+ `}
+ </li>
+ `;
+ }
+}
+
+customElements.define("movie-card", MovieCard); | JavaScript | `a` ํ๊ทธ ๋ฐ `href="#'`๋ฅผ ์ฌ์ฉํ์ ์ด์ ๊ฐ ์๋์? |
@@ -3,7 +3,10 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
- <title>React App</title>
+ <meta name="description" content="Web site created using create-react-app"/>
+ <link href="https://fonts.googleapis.com/css2?family=Lobster&display=swap" rel="stylesheet">
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
+ <title>Westagram</title>
</head>
<body>
<div id="root"></div> | Unknown | description์ ์์ด๋ ๋์ง ์์๊น์? ์ ๋ชจ๋ฅด๊ฒ ์ต๋๋ค ใ
ใ
|
@@ -0,0 +1,50 @@
+import React from 'react';
+import { withRouter } from 'react-router-dom';
+import './Login.scss';
+
+
+class LoginJaeyoung extends React.Component {
+ constructor () {
+ super();
+ this.state = {
+ id: '',
+ pw : '',
+ };
+ }
+
+ handleInput = (e) => {
+ const { name,value} = e.target;
+ this.setState({
+ [name]: value
+ })
+ }
+
+ goToMain = () => {
+ this.props.history.push('/main-jaeyoung')
+ }
+
+
+ render () {
+ const { handleInput } = this
+ const isBtnAble = this.state.id.includes('@') && this.state.pw.length >= 5;
+
+
+ return (
+ <div className="loginContainer">
+ <div className="logoName">
+ <h1>Instargram</h1>
+ </div>
+ <div className="loginInfo">
+ <input type="text" name="id" onChange={handleInput} className="loginId" placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ" />
+ <input type="password" name="pw" onChange={handleInput} className="loginPs" placeholder="๋น๋ฐ๋ฒํธ"/>
+ <button className="loginBt" onClick={this.goToMain} disabled={!isBtnAble}>๋ก๊ทธ์ธ</button>
+ </div>
+ <div className="forgetPassword">
+ <a href="https://www.naver.com/">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </div>
+ )
+ }
+}
+
+export default withRouter( LoginJaeyoung );
\ No newline at end of file | JavaScript | https://www.notion.so/wecode/React-Refactoring-Check-List-aea297cf88ed4601b769e4b2c2cfd4e1#089493d6bfca438aa328226e327cff92
์ด ๋ถ๋ถ์ ์ฐธ๊ณ ํ๋ฉด ํ๋์ ๋ฉ์๋๋กค ๋ฌถ์ ์ ์์ต๋๋ค. |
@@ -0,0 +1,85 @@
+* {
+ box-sizing: border-box;
+}
+
+.loginContainer {
+ border: 2px solid #e6e6e6;
+ width: 350px;
+ height: 380px;
+ margin: 0 auto;
+ .logoName {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ width: 100%;
+ h1 {
+ font-family: "Lobster", cursive;
+ width: 175px;
+ height: 52px;
+ text-align: center;
+ padding-top: 6px;
+ }
+ }
+ .loginInfo {
+ height: 213px;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ padding-top: 10px;
+ .loginId {
+ width: 268px;
+ height: 38px;
+ margin-bottom: 5px;
+ padding-left: 10px;
+ border-radius: 3px;
+ border: 1px solid #efefef;
+ background: #fafafa;
+ color: #9c9c9c;
+ font-size: 14px;
+ &:focus {
+ outline-color: gray;
+ }
+ }
+ .loginPs {
+ width: 268px;
+ height: 38px;
+ margin-bottom: 5px;
+ padding-left: 10px;
+ border-radius: 3px;
+ border: 1px solid #efefef;
+ background: #fafafa;
+ color: #9c9c9c;
+ font-size: 14px;
+ &:focus {
+ outline-color: gray;
+ }
+ }
+ .loginBt {
+ width: 268px;
+ height: 30px;
+ margin-top: 5px;
+ border-radius: 3px;
+ background-color: #2795f6;
+ color: #ffffff;
+ border-style: none;
+
+ &:focus {
+ outline: none;
+ }
+
+ &:disabled {
+ background-color: #b2dffc;
+ }
+ }
+ }
+ .forgetPassword{
+ display: flex;
+ justify-content: center;
+ margin-top: 20px;
+ a {
+ color: #043569; text-decoration: none;
+ }
+ }
+
+
+} | Unknown | ์ด ๋ถ๋ถ์ common.css์ ์์ผ๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,85 @@
+* {
+ box-sizing: border-box;
+}
+
+.loginContainer {
+ border: 2px solid #e6e6e6;
+ width: 350px;
+ height: 380px;
+ margin: 0 auto;
+ .logoName {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ width: 100%;
+ h1 {
+ font-family: "Lobster", cursive;
+ width: 175px;
+ height: 52px;
+ text-align: center;
+ padding-top: 6px;
+ }
+ }
+ .loginInfo {
+ height: 213px;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ padding-top: 10px;
+ .loginId {
+ width: 268px;
+ height: 38px;
+ margin-bottom: 5px;
+ padding-left: 10px;
+ border-radius: 3px;
+ border: 1px solid #efefef;
+ background: #fafafa;
+ color: #9c9c9c;
+ font-size: 14px;
+ &:focus {
+ outline-color: gray;
+ }
+ }
+ .loginPs {
+ width: 268px;
+ height: 38px;
+ margin-bottom: 5px;
+ padding-left: 10px;
+ border-radius: 3px;
+ border: 1px solid #efefef;
+ background: #fafafa;
+ color: #9c9c9c;
+ font-size: 14px;
+ &:focus {
+ outline-color: gray;
+ }
+ }
+ .loginBt {
+ width: 268px;
+ height: 30px;
+ margin-top: 5px;
+ border-radius: 3px;
+ background-color: #2795f6;
+ color: #ffffff;
+ border-style: none;
+
+ &:focus {
+ outline: none;
+ }
+
+ &:disabled {
+ background-color: #b2dffc;
+ }
+ }
+ }
+ .forgetPassword{
+ display: flex;
+ justify-content: center;
+ margin-top: 20px;
+ a {
+ color: #043569; text-decoration: none;
+ }
+ }
+
+
+} | Unknown | font-family๊ฐ์ ์์ฑ์ width๋ margin์๋์ ์์ผ๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,190 @@
+import React from 'react';
+import FeedComponent from './FeedComponent/FeedComponent';
+import './Main.scss';
+import explore from '../../../images/jaeyoungLee/Main/explore.jpg';
+import heart from '../../../images/jaeyoungLee/Main/heart.jpg';
+import profile from '../../../images/jaeyoungLee/Main/profile.jpg';
+import heungminSon from '../../../images/jaeyoungLee/Main/์ํฅ๋ฏผ.jpg';
+class MainJaeyoung extends React.Component {
+ constructor () {
+ super();
+ this.state = {
+ commentFeed : [],
+ }
+ }
+
+ componentDidMount() {
+ fetch('http://localhost:3000/data/feedData.json', {
+ method: 'GET'
+ })
+ .then(res => res.json())
+ .then(data => {
+ this.setState({
+ commentFeed: data,
+ });
+ });
+ }
+
+
+
+ render(){
+ const { commentFeed } = this.state;
+ return(
+ <>
+ <nav>
+ <div className="navcontents">
+ <div className="navleft">
+ <div className="navleftcontents">
+ <span className="logo"><i className="fab fa-instagram"></i></span>
+ <h1 className="logoname">westagram</h1>
+ </div>
+ </div>
+ <div className="navcenter">
+ <div className="navcentercontents">
+ <input className="search" type="text" placeholder="๊ฒ์"/>
+ <span className="searchimg"><i className="fas fa-search"></i></span>
+ </div>
+ </div>
+ <div className="navright">
+ <div className="navrightcontents">
+ <img className="navexplore" src={explore} alt="ํํ"/>
+ <img className="navheart" src={heart} alt="ํํธ"/>
+ <img className="navprofile" src={profile} alt="ํ๋กํ"/>
+ </div>
+ </div>
+ </div>
+ </nav>
+ <div className="main">
+ <div className="feeds">
+ <div className="story">
+ <div className="storyimgbox">
+ <div className="storycontents">
+ <div className="storyprofile">
+ <div className="storylastbox">
+ <div className="storylast">
+ <img className="storyimg1" src={heungminSon} alt="ํ๋กํ1"/>
+ <p className="storyp1">์ํฅ๋ฏผ</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://instagram.famm6-1.fna.fbcdn.net/v/t51.2885-19/44884218_345707102882519_2446069589734326272_n.jpg?_nc_ht=instagram.famm6-1.fna.fbcdn.net&_nc_ohc=mhDR9_0DpXIAX_KX0iq&ccb=7-4&oh=dcbb150241d6b1336dd54a4a20417b2a&oe=608B680F&_nc_sid=712cc3&ig_cache_key=YW5vbnltb3VzX3Byb2ZpbGVfcGlj.2-ccb7-4" alt="ํ๋กํ1"/>
+ <p className="storyp1">2wo0</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/35999304_258159611658935_7092278198804676608_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=et4sZhNbgpAAX-qKBH9&ccb=7-4&oh=0b254f6fb3e4182513c3e20ed1a326d0&oe=608BC5C1&_nc_sid=48a2a6" alt="ํ๋กํ1"/>
+ <p className="storyp1">geg</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/150675895_144233967522798_7515094658452540248_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=xslO4Za0644AX9cwObZ&ccb=7-4&oh=0f5cb82fd80b51b47d74e160e228aa1c&oe=608D7B5E&_nc_sid=48a2a6" alt="ํ๋กํ1"/>
+ <p className="storyp1">h._.j</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/135771971_1881013862054625_6713353513169410837_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=SxJIiqRh4rcAX8RSLYk&ccb=7-4&oh=6dec08c37a69cb2c2a14f21bc36b5eef&oe=608C0912&_nc_sid=48a2a6" alt="ํ๋กํ1"/>
+ <p className="storyp1">idon</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/155951500_335125831259326_3729086392261698560_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=3nnTQdlVU98AX_4fVMv&ccb=7-4&oh=4a596fc0e33f2ece37634ae50d38cdde&oe=608C5901&_nc_sid=48a2a6" alt="ํ๋กํ1"/>
+ <p className="storyp1">dfewg</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/37828240_293117218102022_6759937585105076224_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=jzs6QvrGtHAAX_qFR80&ccb=7-4&oh=f4984cbce61bc445f02622a5468278b3&oe=608B09A1&_nc_sid=57d425" alt="ํ๋กํ1"/>
+ <p className="storyp1">33gg</p>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ {commentFeed.map((feed,id) =>{
+ return (
+ <FeedComponent key={feed.id} profileimg={feed.profileimg} userName={feed.userName} feedimg={feed.feedimg} feedcontent={feed.feedcontent} />
+ );
+ })}
+
+ </div>
+ <div className="main-right">
+ <div className="my_profile">
+ <img className="my_profileimg" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/141997127_1523884024669097_6148385093252095280_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=ldPmBqcpW3kAX9esSCC&ccb=7-4&oh=6503a99b1b0096ad362012fef7e72aed&oe=6085537E&_nc_sid=7b02f1" alt="ํ๋กํ"/>
+ <div className="my_info">
+ <p className="mynickname">2wo0_0</p>
+ <p className="myname">์ด์ฌ์</p>
+ </div>
+ <button className="profile_transform" disabled>์ ํ</button>
+ </div>
+ <div className="recommendation">
+ <div className="recommendation_header">
+ <p className="recommendation_left">ํ์๋์ ์ํ ์ถ์ฒ</p>
+ <p className="recommendation_right">๋ชจ๋ ๋ณด๊ธฐ</p>
+ </div>
+ <div className="recommendation_info">
+ <div className="recommendation_box">
+ <img className="friend_profile" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/156650140_116853317083347_8770042214751161261_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=-evbCZABANYAX_WcDzP&edm=AEF8tYYAAAAA&ccb=7-4&oh=5eb6e52a64b2ad8c98bff45dab473831&oe=60880D5B&_nc_sid=a9513d" alt="๋ค๋ฅธํ๋กํ"/>
+ <div className="friend_info">
+ <p className="friend_nickname">ryu_d_g</p>
+ <p className="other_friend">1996yunsi๋ ์ธ 13๋ช
์ด ํ๋ก์ฐํฉ๋๋ค</p>
+ </div>
+ <button className="follow" disabled>ํ๋ก์ฐ</button>
+ </div>
+ <div className="recommendation_box">
+ <img className="friend_profile" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/159992110_105322351555148_1839915921172216453_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=xfLIvYCwwiIAX8AJI08&ccb=7-4&oh=7bdaf0e022e88f0dd5079c1995892031&oe=608D9B9E&_nc_sid=57d425" alt="๋ค๋ฅธํ๋กํ"/>
+ <div className="friend_info">
+ <p className="friend_nickname">2s2_f</p>
+ <p className="other_friend">_sihyeon___๋ ์ธ 49๋ช
์ด ํ๋ก์ฐํฉ๋๋ค</p>
+ </div>
+ <button className="follow" disabled>ํ๋ก์ฐ</button>
+ </div>
+ <div className="recommendation_box">
+ <img className="friend_profile" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/160716680_272942871038831_8108440433038115559_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=VmeF5WmeLg4AX-jiUAL&ccb=7-4&oh=cf29d0253e8afb755a9d26ad13a6deda&oe=608D4A0C&_nc_sid=a9513d" alt="๋ค๋ฅธํ๋กํ"/>
+ <div className="friend_info">
+ <p className="friend_nickname">rdfe_g</p>
+ <p className="other_friend">111_fkdn๋ ์ธ 5๋ช
์ด ํ๋ก์ฐํฉ๋๋ค</p>
+ </div>
+ <button className="follow" disabled>ํ๋ก์ฐ</button>
+ </div>
+ <div className="recommendation_box">
+ <img className="friend_profile" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/164274433_776408706413539_3215024154205561736_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=gCCfowKp9OMAX9_NBIP&ccb=7-4&oh=afbada353869184275b4d3be70f38605&oe=608BE909&_nc_sid=a9513d" alt="๋ค๋ฅธํ๋กํ"/>
+ <div className="friend_info">
+ <p className="friend_nickname">cat_2d_g</p>
+ <p className="other_friend">cjdtkseh๋ ์ธ 15๋ช
์ด ํ๋ก์ฐํฉ๋๋ค</p>
+ </div>
+ <button className="follow" disabled>ํ๋ก์ฐ</button>
+ </div>
+ <div className="recommendation_box">
+ <img className="friend_profile" src=" https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/164520013_834814623778500_398528442563386719_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=iLm66uEJKQ4AX88GkVl&ccb=7-4&oh=4fe271ebb6f627b328cb3d24bb811776&oe=608E6098&_nc_sid=86f79a" alt="๋ค๋ฅธํ๋กํ"/>
+ <div className="friend_info">
+ <p className="friend_nickname">tksdkdnENr</p>
+ <p className="other_friend">cjfcjfgme1๋ ์ธ 32๋ช
์ด ํ๋ก์ฐํฉ๋๋ค</p>
+ </div>
+ <button className="follow" disabled>ํ๋ก์ฐ</button>
+ </div>
+ </div>
+ </div>
+ <aside>
+ <ul className="westagram_contents_box">
+ {CONTENTS.map((el,id) =>
+ <li key={id} className="westagram_contents">{el.content}</li>
+ )}
+
+ </ul>
+ <p className="westagram_facebook">ยฉ 2021 INSTAGRAM FROM FACEBOOK</p>
+ </aside>
+ </div>
+ </div>
+ </>
+ )
+ }
+}
+export default MainJaeyoung ;
+
+const CONTENTS = [
+ {id: 1, content: "์๊ฐ"},
+ {id: 2, content: "๋์๋ง"},
+ {id: 3, content: "ํ๋ณด ์ผํฐ"},
+ {id: 4, content: "API"},
+ {id: 5, content: "์ฑ์ฉ์ ๋ณด"},
+ {id: 6, content: "๊ฐ์ธ์ ๋ณด์ฒ๋ฆฌ๋ฐฉ์นจ"},
+ {id: 7, content: "์ฝ๊ด"},
+ {id: 8, content: "์์น"},
+ {id: 9, content: "์ธ๊ธฐ ๊ณ์ "},
+ {id: 10, content: "ํด์ํ๊ทธ"},
+ {id: 11, content: "์ธ์ด"},
+]
\ No newline at end of file | JavaScript | ๋ณ์๋ช
์ด ๋ช
์์ ์ด์ฌ์ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค.! |
@@ -0,0 +1,190 @@
+import React from 'react';
+import FeedComponent from './FeedComponent/FeedComponent';
+import './Main.scss';
+import explore from '../../../images/jaeyoungLee/Main/explore.jpg';
+import heart from '../../../images/jaeyoungLee/Main/heart.jpg';
+import profile from '../../../images/jaeyoungLee/Main/profile.jpg';
+import heungminSon from '../../../images/jaeyoungLee/Main/์ํฅ๋ฏผ.jpg';
+class MainJaeyoung extends React.Component {
+ constructor () {
+ super();
+ this.state = {
+ commentFeed : [],
+ }
+ }
+
+ componentDidMount() {
+ fetch('http://localhost:3000/data/feedData.json', {
+ method: 'GET'
+ })
+ .then(res => res.json())
+ .then(data => {
+ this.setState({
+ commentFeed: data,
+ });
+ });
+ }
+
+
+
+ render(){
+ const { commentFeed } = this.state;
+ return(
+ <>
+ <nav>
+ <div className="navcontents">
+ <div className="navleft">
+ <div className="navleftcontents">
+ <span className="logo"><i className="fab fa-instagram"></i></span>
+ <h1 className="logoname">westagram</h1>
+ </div>
+ </div>
+ <div className="navcenter">
+ <div className="navcentercontents">
+ <input className="search" type="text" placeholder="๊ฒ์"/>
+ <span className="searchimg"><i className="fas fa-search"></i></span>
+ </div>
+ </div>
+ <div className="navright">
+ <div className="navrightcontents">
+ <img className="navexplore" src={explore} alt="ํํ"/>
+ <img className="navheart" src={heart} alt="ํํธ"/>
+ <img className="navprofile" src={profile} alt="ํ๋กํ"/>
+ </div>
+ </div>
+ </div>
+ </nav>
+ <div className="main">
+ <div className="feeds">
+ <div className="story">
+ <div className="storyimgbox">
+ <div className="storycontents">
+ <div className="storyprofile">
+ <div className="storylastbox">
+ <div className="storylast">
+ <img className="storyimg1" src={heungminSon} alt="ํ๋กํ1"/>
+ <p className="storyp1">์ํฅ๋ฏผ</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://instagram.famm6-1.fna.fbcdn.net/v/t51.2885-19/44884218_345707102882519_2446069589734326272_n.jpg?_nc_ht=instagram.famm6-1.fna.fbcdn.net&_nc_ohc=mhDR9_0DpXIAX_KX0iq&ccb=7-4&oh=dcbb150241d6b1336dd54a4a20417b2a&oe=608B680F&_nc_sid=712cc3&ig_cache_key=YW5vbnltb3VzX3Byb2ZpbGVfcGlj.2-ccb7-4" alt="ํ๋กํ1"/>
+ <p className="storyp1">2wo0</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/35999304_258159611658935_7092278198804676608_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=et4sZhNbgpAAX-qKBH9&ccb=7-4&oh=0b254f6fb3e4182513c3e20ed1a326d0&oe=608BC5C1&_nc_sid=48a2a6" alt="ํ๋กํ1"/>
+ <p className="storyp1">geg</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/150675895_144233967522798_7515094658452540248_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=xslO4Za0644AX9cwObZ&ccb=7-4&oh=0f5cb82fd80b51b47d74e160e228aa1c&oe=608D7B5E&_nc_sid=48a2a6" alt="ํ๋กํ1"/>
+ <p className="storyp1">h._.j</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/135771971_1881013862054625_6713353513169410837_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=SxJIiqRh4rcAX8RSLYk&ccb=7-4&oh=6dec08c37a69cb2c2a14f21bc36b5eef&oe=608C0912&_nc_sid=48a2a6" alt="ํ๋กํ1"/>
+ <p className="storyp1">idon</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/155951500_335125831259326_3729086392261698560_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=3nnTQdlVU98AX_4fVMv&ccb=7-4&oh=4a596fc0e33f2ece37634ae50d38cdde&oe=608C5901&_nc_sid=48a2a6" alt="ํ๋กํ1"/>
+ <p className="storyp1">dfewg</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/37828240_293117218102022_6759937585105076224_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=jzs6QvrGtHAAX_qFR80&ccb=7-4&oh=f4984cbce61bc445f02622a5468278b3&oe=608B09A1&_nc_sid=57d425" alt="ํ๋กํ1"/>
+ <p className="storyp1">33gg</p>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ {commentFeed.map((feed,id) =>{
+ return (
+ <FeedComponent key={feed.id} profileimg={feed.profileimg} userName={feed.userName} feedimg={feed.feedimg} feedcontent={feed.feedcontent} />
+ );
+ })}
+
+ </div>
+ <div className="main-right">
+ <div className="my_profile">
+ <img className="my_profileimg" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/141997127_1523884024669097_6148385093252095280_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=ldPmBqcpW3kAX9esSCC&ccb=7-4&oh=6503a99b1b0096ad362012fef7e72aed&oe=6085537E&_nc_sid=7b02f1" alt="ํ๋กํ"/>
+ <div className="my_info">
+ <p className="mynickname">2wo0_0</p>
+ <p className="myname">์ด์ฌ์</p>
+ </div>
+ <button className="profile_transform" disabled>์ ํ</button>
+ </div>
+ <div className="recommendation">
+ <div className="recommendation_header">
+ <p className="recommendation_left">ํ์๋์ ์ํ ์ถ์ฒ</p>
+ <p className="recommendation_right">๋ชจ๋ ๋ณด๊ธฐ</p>
+ </div>
+ <div className="recommendation_info">
+ <div className="recommendation_box">
+ <img className="friend_profile" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/156650140_116853317083347_8770042214751161261_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=-evbCZABANYAX_WcDzP&edm=AEF8tYYAAAAA&ccb=7-4&oh=5eb6e52a64b2ad8c98bff45dab473831&oe=60880D5B&_nc_sid=a9513d" alt="๋ค๋ฅธํ๋กํ"/>
+ <div className="friend_info">
+ <p className="friend_nickname">ryu_d_g</p>
+ <p className="other_friend">1996yunsi๋ ์ธ 13๋ช
์ด ํ๋ก์ฐํฉ๋๋ค</p>
+ </div>
+ <button className="follow" disabled>ํ๋ก์ฐ</button>
+ </div>
+ <div className="recommendation_box">
+ <img className="friend_profile" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/159992110_105322351555148_1839915921172216453_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=xfLIvYCwwiIAX8AJI08&ccb=7-4&oh=7bdaf0e022e88f0dd5079c1995892031&oe=608D9B9E&_nc_sid=57d425" alt="๋ค๋ฅธํ๋กํ"/>
+ <div className="friend_info">
+ <p className="friend_nickname">2s2_f</p>
+ <p className="other_friend">_sihyeon___๋ ์ธ 49๋ช
์ด ํ๋ก์ฐํฉ๋๋ค</p>
+ </div>
+ <button className="follow" disabled>ํ๋ก์ฐ</button>
+ </div>
+ <div className="recommendation_box">
+ <img className="friend_profile" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/160716680_272942871038831_8108440433038115559_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=VmeF5WmeLg4AX-jiUAL&ccb=7-4&oh=cf29d0253e8afb755a9d26ad13a6deda&oe=608D4A0C&_nc_sid=a9513d" alt="๋ค๋ฅธํ๋กํ"/>
+ <div className="friend_info">
+ <p className="friend_nickname">rdfe_g</p>
+ <p className="other_friend">111_fkdn๋ ์ธ 5๋ช
์ด ํ๋ก์ฐํฉ๋๋ค</p>
+ </div>
+ <button className="follow" disabled>ํ๋ก์ฐ</button>
+ </div>
+ <div className="recommendation_box">
+ <img className="friend_profile" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/164274433_776408706413539_3215024154205561736_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=gCCfowKp9OMAX9_NBIP&ccb=7-4&oh=afbada353869184275b4d3be70f38605&oe=608BE909&_nc_sid=a9513d" alt="๋ค๋ฅธํ๋กํ"/>
+ <div className="friend_info">
+ <p className="friend_nickname">cat_2d_g</p>
+ <p className="other_friend">cjdtkseh๋ ์ธ 15๋ช
์ด ํ๋ก์ฐํฉ๋๋ค</p>
+ </div>
+ <button className="follow" disabled>ํ๋ก์ฐ</button>
+ </div>
+ <div className="recommendation_box">
+ <img className="friend_profile" src=" https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/164520013_834814623778500_398528442563386719_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=iLm66uEJKQ4AX88GkVl&ccb=7-4&oh=4fe271ebb6f627b328cb3d24bb811776&oe=608E6098&_nc_sid=86f79a" alt="๋ค๋ฅธํ๋กํ"/>
+ <div className="friend_info">
+ <p className="friend_nickname">tksdkdnENr</p>
+ <p className="other_friend">cjfcjfgme1๋ ์ธ 32๋ช
์ด ํ๋ก์ฐํฉ๋๋ค</p>
+ </div>
+ <button className="follow" disabled>ํ๋ก์ฐ</button>
+ </div>
+ </div>
+ </div>
+ <aside>
+ <ul className="westagram_contents_box">
+ {CONTENTS.map((el,id) =>
+ <li key={id} className="westagram_contents">{el.content}</li>
+ )}
+
+ </ul>
+ <p className="westagram_facebook">ยฉ 2021 INSTAGRAM FROM FACEBOOK</p>
+ </aside>
+ </div>
+ </div>
+ </>
+ )
+ }
+}
+export default MainJaeyoung ;
+
+const CONTENTS = [
+ {id: 1, content: "์๊ฐ"},
+ {id: 2, content: "๋์๋ง"},
+ {id: 3, content: "ํ๋ณด ์ผํฐ"},
+ {id: 4, content: "API"},
+ {id: 5, content: "์ฑ์ฉ์ ๋ณด"},
+ {id: 6, content: "๊ฐ์ธ์ ๋ณด์ฒ๋ฆฌ๋ฐฉ์นจ"},
+ {id: 7, content: "์ฝ๊ด"},
+ {id: 8, content: "์์น"},
+ {id: 9, content: "์ธ๊ธฐ ๊ณ์ "},
+ {id: 10, content: "ํด์ํ๊ทธ"},
+ {id: 11, content: "์ธ์ด"},
+]
\ No newline at end of file | JavaScript | ```suggestion
inputKeyPress= (e) => {
```
๊ฐ์ ์ด๋ฆ์ ์ด๋จ๊น์? ๋ฉ์๋๊ฐ ๋ง์์ง๋ฉด ํท๊ฐ๋ฆด ์ ์์ ๊ฑฐ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,412 @@
+* {
+ margin: 0;
+ padding: 0;
+}
+nav {
+ position: fixed;
+ width: 100%;
+ top: 0px;
+ left: 0px;
+ right: 0px;
+ background-color: #fff;
+ border-bottom: 1px solid #dbdbdb;
+ .navcontents {
+ width: 935px;
+ height: 54px;
+ background-color: #fff;
+ margin: 0 auto;
+ display: flex;
+ justify-content: space-between;
+ .navleft {
+ width: 360px;
+ .navleftcontents {
+ display: flex;
+ justify-content: flex-start;
+ .logo {
+ font-size: 23px;
+ margin-top: 12px;
+ }
+ .logoname {
+ border-left: 1px solid #bbbbbb;
+ font-family: "Lobster", cursive;
+ margin-left: 15px;
+ margin-top: 7px;
+ padding-left: 15px;
+ }
+ }
+ }
+ .navcenter {
+ width: 215px;
+ .navcentercontents {
+ position: relative;
+ .search {
+ width: 213px;
+ height: 26px;
+ background-color: #fafafa;
+ border: 1px solid #dbdbdb;
+ border-radius: 3px;
+ text-align: center;
+ position: absolute;
+ top: 14px;
+ }
+
+ .searchimg {
+ font-size: 10px;
+ color: #bbbbbb;
+ position: absolute;
+ top: 24px;
+ left: 83px;
+ }
+ }
+ }
+ .navright {
+ width: 360px;
+ .navrightcontents {
+ display: flex;
+ justify-content: flex-end;
+ margin-top: 14px;
+ .navexplore {
+ width: 25px;
+ height: 25px;
+ margin-right: 20px;
+ }
+
+ .navheart {
+ width: 25px;
+ height: 25px;
+ margin-right: 20px;
+ }
+
+ .navprofile {
+ width: 25px;
+ height: 25px;
+ }
+ }
+ }
+ }
+}
+
+
+
+.main {
+ border: 1px solid #fafafa;
+ background-color: #fafafa;
+ .feeds {
+ width: 935px;
+ margin: 0 auto;
+ margin-top: 84px;
+ .story {
+ width: 612px;
+ height: 116px;
+ background-color: #fff;
+ border: 1px solid #dbdbdb;
+ border-radius: 3px;
+ display: flex;
+ align-items: center;
+ .storyimgbox {
+ width: 612px;
+ height: 84px;
+ .storycontents {
+ display: flex;
+ justify-content: space-around;
+ .storylastbox {
+ display: flex;
+ justify-content: center;
+ .storylast {
+ width: 80px;
+ height: 122px;
+ .storyimg1 {
+ width: 56px;
+ height: 56px;
+ border: 1px solid #ececec;
+ border-radius: 50%;
+ padding: 3px;
+ object-fit: cover;
+ }
+
+ .storyp1 {
+ color: #8e8e8e;
+ font-size: 12px;
+ margin-left: 18px;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+
+article {
+ width: 612px;
+ height: auto;
+ background-color: #fff;
+ margin-top: 24px;
+ border: 1px solid #dbdbdb;
+ border-radius: 3px;
+ .articleheader {
+ width: 612px;
+ height: 59px;
+ border: 1px solid #dbdbdb;
+ .articleheadercontents {
+ width: 582px;
+ height: 27px;
+ margin: 15px auto 15px auto;
+ display: flex;
+ justify-content: space-between;
+ .headerimg {
+ width: 32px;
+ height: 32px;
+ border-radius: 50%;
+ object-fit: cover;
+ }
+
+ .headername {
+ width: 536px;
+ height: 26px;
+ .headerlast {
+ height: 26px;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ .hname {
+ font-size: 14px;
+ color: #262626;
+ font-weight: bold;
+ }
+ }
+ }
+ }
+ }
+ .articleimg {
+ width: 612px;
+ height: 612px;
+ object-fit: cover;
+ }
+
+ .article_button {
+ width: 582px;
+ height: 49px;
+ margin: 0 auto;
+ display: flex;
+ justify-content: space-between;
+ .article_button_left{
+ .left_button {
+ margin: 8px;
+ }
+ }
+ .article_button_right {
+ .right_button {
+ margin: 8px;
+ }
+ }
+ }
+
+ .number_of_likes {
+ width: 582px;
+ height: 18px;
+ margin: 0 auto;
+ padding-left: 5px;
+ .likes_friend {
+ font-size: 14px;
+ .like_font {
+ color: #262626;
+ font-weight: bold;
+ }
+ }
+ }
+ .friend_comment {
+ width: 582px;
+ height: auto;
+ margin: 0 auto;
+ margin-top: 8px;
+ padding-left: 5px;
+ .explanation {
+ font-size: 14px;
+ .like_font {
+ color: #262626;
+ font-weight: bold;
+ }
+ }
+ .commentBox {
+ list-style: none;
+ }
+ }
+ .time {
+ width: 598px;
+ padding-left: 18px;
+ .a_few_hours_ago {
+ font-size: 10px;
+ color: #8e8e8e;
+ }
+ }
+ .leave_comment_box {
+ border-top: 1px solid #dbdbdb;
+ margin-top: 10px;
+ .leave_comment {
+ width: 582px;
+ height: 55px;
+ margin: 0 auto;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ .smilebox {
+ padding: 8px 15px 8px 0px;
+ }
+ .inputcomment {
+ width: 510px;
+ border: 0;
+ }
+ .inputcomment:focus {
+ outline: none;
+ }
+ .posting_button {
+ background-color: #fff;
+ color: #0095f6;
+ border: 0;
+ }
+ .posting_button:focus{
+ outline: none;
+ }
+ }
+ }
+}
+
+
+
+
+.main-right {
+ width: 293px;
+ height: 612px;
+ position: fixed;
+ top: 85px;
+ left: 885px;
+ .my_profile {
+ width: 293px;
+ height: 56px;
+ margin: 18px 0px 10px 0px;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ .my_profileimg {
+ width: 56px;
+ height: 56px;
+ border-radius: 50%;
+ }
+
+ .my_info {
+ width: 202px;
+ height: 30px;
+ .mynickname {
+ width: 190px;
+ font-size: 14px;
+ font-weight: bold;
+ margin-left: 12px;
+ color: #262626;
+ }
+
+ .myname {
+ width: 190px;
+ font-size: 14px;
+ margin-left: 12px;
+ color: #8e8e8e;
+ }
+ }
+ .profile_transform {
+ font-weight: 600;
+ font-size: 12px;
+ border: 0;
+ color: #0095f6;
+ }
+ }
+ .recommendation {
+ width: 291px;
+ height: 325px;
+ .recommendation_header {
+ width: 293px;
+ height: 11px;
+ margin-top: 18px;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ .recommendation_left {
+ width: 248px;
+ font-size: 14px;
+ color: #8e8e8e;
+ font-weight: 600;
+ }
+
+ .recommendation_right {
+ width: 45px;
+ font-size: 12px;
+ color: #262626;
+ font-weight: 600;
+ }
+ }
+ .recommendation_info {
+ width: 289px;
+ height: 240px;
+ margin-top: 20px;
+ .recommendation_box {
+ width: 289px;
+ margin-bottom: 16px;
+ display: flex;
+ justify-content: space-between;
+ flex-wrap: wrap;
+ align-content: flex-start;
+ .friend_profile {
+ width: 32px;
+ height: 32px;
+ border-radius: 50%;
+ }
+
+ .friend_info {
+ width: 206px;
+ height: 28px;
+ .friend_nickname {
+ width: 205px;
+ color: #262626;
+ font-weight: bold;
+ font-size: 14px;
+ }
+
+ .other_friend {
+ width: 205px;
+ color: #8e8e8e;
+ font-weight: 400;
+ font-size: 12px;
+ }
+ }
+ .follow {
+ height: 15px;
+ font-weight: 600;
+ font-size: 12px;
+ margin-top: 10px;
+ border: 0;
+ color: #0095f6;
+ }
+ }
+ }
+ }
+ aside {
+ width: 293px;
+ height: 68px;
+ .westagram_contents_box {
+ width: 293px;
+ .westagram_contents {
+ color: #c7c7c7;
+ font-size: 11px;
+ font-weight: 400;
+ display: inline;
+ }
+ }
+ .westagram_facebook {
+ width: 205px;
+ color: #c7c7c7;
+ font-size: 11px;
+ font-weight: 400;
+ margin-top: 20px;
+ }
+ }
+}
\ No newline at end of file | Unknown | ```suggestion
.nav_center {
```
๊ฐ์ด ๋์ด์ฐ๊ธฐ๋ฅผ '-'๋ '_'๋ก ํ์ํด์ฃผ๋ฉด ์์ฑ์ฝ๊ธฐ๊ฐ ๋ ์์ํด ์ง ๊ฑฐ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,412 @@
+* {
+ margin: 0;
+ padding: 0;
+}
+nav {
+ position: fixed;
+ width: 100%;
+ top: 0px;
+ left: 0px;
+ right: 0px;
+ background-color: #fff;
+ border-bottom: 1px solid #dbdbdb;
+ .navcontents {
+ width: 935px;
+ height: 54px;
+ background-color: #fff;
+ margin: 0 auto;
+ display: flex;
+ justify-content: space-between;
+ .navleft {
+ width: 360px;
+ .navleftcontents {
+ display: flex;
+ justify-content: flex-start;
+ .logo {
+ font-size: 23px;
+ margin-top: 12px;
+ }
+ .logoname {
+ border-left: 1px solid #bbbbbb;
+ font-family: "Lobster", cursive;
+ margin-left: 15px;
+ margin-top: 7px;
+ padding-left: 15px;
+ }
+ }
+ }
+ .navcenter {
+ width: 215px;
+ .navcentercontents {
+ position: relative;
+ .search {
+ width: 213px;
+ height: 26px;
+ background-color: #fafafa;
+ border: 1px solid #dbdbdb;
+ border-radius: 3px;
+ text-align: center;
+ position: absolute;
+ top: 14px;
+ }
+
+ .searchimg {
+ font-size: 10px;
+ color: #bbbbbb;
+ position: absolute;
+ top: 24px;
+ left: 83px;
+ }
+ }
+ }
+ .navright {
+ width: 360px;
+ .navrightcontents {
+ display: flex;
+ justify-content: flex-end;
+ margin-top: 14px;
+ .navexplore {
+ width: 25px;
+ height: 25px;
+ margin-right: 20px;
+ }
+
+ .navheart {
+ width: 25px;
+ height: 25px;
+ margin-right: 20px;
+ }
+
+ .navprofile {
+ width: 25px;
+ height: 25px;
+ }
+ }
+ }
+ }
+}
+
+
+
+.main {
+ border: 1px solid #fafafa;
+ background-color: #fafafa;
+ .feeds {
+ width: 935px;
+ margin: 0 auto;
+ margin-top: 84px;
+ .story {
+ width: 612px;
+ height: 116px;
+ background-color: #fff;
+ border: 1px solid #dbdbdb;
+ border-radius: 3px;
+ display: flex;
+ align-items: center;
+ .storyimgbox {
+ width: 612px;
+ height: 84px;
+ .storycontents {
+ display: flex;
+ justify-content: space-around;
+ .storylastbox {
+ display: flex;
+ justify-content: center;
+ .storylast {
+ width: 80px;
+ height: 122px;
+ .storyimg1 {
+ width: 56px;
+ height: 56px;
+ border: 1px solid #ececec;
+ border-radius: 50%;
+ padding: 3px;
+ object-fit: cover;
+ }
+
+ .storyp1 {
+ color: #8e8e8e;
+ font-size: 12px;
+ margin-left: 18px;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+
+article {
+ width: 612px;
+ height: auto;
+ background-color: #fff;
+ margin-top: 24px;
+ border: 1px solid #dbdbdb;
+ border-radius: 3px;
+ .articleheader {
+ width: 612px;
+ height: 59px;
+ border: 1px solid #dbdbdb;
+ .articleheadercontents {
+ width: 582px;
+ height: 27px;
+ margin: 15px auto 15px auto;
+ display: flex;
+ justify-content: space-between;
+ .headerimg {
+ width: 32px;
+ height: 32px;
+ border-radius: 50%;
+ object-fit: cover;
+ }
+
+ .headername {
+ width: 536px;
+ height: 26px;
+ .headerlast {
+ height: 26px;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ .hname {
+ font-size: 14px;
+ color: #262626;
+ font-weight: bold;
+ }
+ }
+ }
+ }
+ }
+ .articleimg {
+ width: 612px;
+ height: 612px;
+ object-fit: cover;
+ }
+
+ .article_button {
+ width: 582px;
+ height: 49px;
+ margin: 0 auto;
+ display: flex;
+ justify-content: space-between;
+ .article_button_left{
+ .left_button {
+ margin: 8px;
+ }
+ }
+ .article_button_right {
+ .right_button {
+ margin: 8px;
+ }
+ }
+ }
+
+ .number_of_likes {
+ width: 582px;
+ height: 18px;
+ margin: 0 auto;
+ padding-left: 5px;
+ .likes_friend {
+ font-size: 14px;
+ .like_font {
+ color: #262626;
+ font-weight: bold;
+ }
+ }
+ }
+ .friend_comment {
+ width: 582px;
+ height: auto;
+ margin: 0 auto;
+ margin-top: 8px;
+ padding-left: 5px;
+ .explanation {
+ font-size: 14px;
+ .like_font {
+ color: #262626;
+ font-weight: bold;
+ }
+ }
+ .commentBox {
+ list-style: none;
+ }
+ }
+ .time {
+ width: 598px;
+ padding-left: 18px;
+ .a_few_hours_ago {
+ font-size: 10px;
+ color: #8e8e8e;
+ }
+ }
+ .leave_comment_box {
+ border-top: 1px solid #dbdbdb;
+ margin-top: 10px;
+ .leave_comment {
+ width: 582px;
+ height: 55px;
+ margin: 0 auto;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ .smilebox {
+ padding: 8px 15px 8px 0px;
+ }
+ .inputcomment {
+ width: 510px;
+ border: 0;
+ }
+ .inputcomment:focus {
+ outline: none;
+ }
+ .posting_button {
+ background-color: #fff;
+ color: #0095f6;
+ border: 0;
+ }
+ .posting_button:focus{
+ outline: none;
+ }
+ }
+ }
+}
+
+
+
+
+.main-right {
+ width: 293px;
+ height: 612px;
+ position: fixed;
+ top: 85px;
+ left: 885px;
+ .my_profile {
+ width: 293px;
+ height: 56px;
+ margin: 18px 0px 10px 0px;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ .my_profileimg {
+ width: 56px;
+ height: 56px;
+ border-radius: 50%;
+ }
+
+ .my_info {
+ width: 202px;
+ height: 30px;
+ .mynickname {
+ width: 190px;
+ font-size: 14px;
+ font-weight: bold;
+ margin-left: 12px;
+ color: #262626;
+ }
+
+ .myname {
+ width: 190px;
+ font-size: 14px;
+ margin-left: 12px;
+ color: #8e8e8e;
+ }
+ }
+ .profile_transform {
+ font-weight: 600;
+ font-size: 12px;
+ border: 0;
+ color: #0095f6;
+ }
+ }
+ .recommendation {
+ width: 291px;
+ height: 325px;
+ .recommendation_header {
+ width: 293px;
+ height: 11px;
+ margin-top: 18px;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ .recommendation_left {
+ width: 248px;
+ font-size: 14px;
+ color: #8e8e8e;
+ font-weight: 600;
+ }
+
+ .recommendation_right {
+ width: 45px;
+ font-size: 12px;
+ color: #262626;
+ font-weight: 600;
+ }
+ }
+ .recommendation_info {
+ width: 289px;
+ height: 240px;
+ margin-top: 20px;
+ .recommendation_box {
+ width: 289px;
+ margin-bottom: 16px;
+ display: flex;
+ justify-content: space-between;
+ flex-wrap: wrap;
+ align-content: flex-start;
+ .friend_profile {
+ width: 32px;
+ height: 32px;
+ border-radius: 50%;
+ }
+
+ .friend_info {
+ width: 206px;
+ height: 28px;
+ .friend_nickname {
+ width: 205px;
+ color: #262626;
+ font-weight: bold;
+ font-size: 14px;
+ }
+
+ .other_friend {
+ width: 205px;
+ color: #8e8e8e;
+ font-weight: 400;
+ font-size: 12px;
+ }
+ }
+ .follow {
+ height: 15px;
+ font-weight: 600;
+ font-size: 12px;
+ margin-top: 10px;
+ border: 0;
+ color: #0095f6;
+ }
+ }
+ }
+ }
+ aside {
+ width: 293px;
+ height: 68px;
+ .westagram_contents_box {
+ width: 293px;
+ .westagram_contents {
+ color: #c7c7c7;
+ font-size: 11px;
+ font-weight: 400;
+ display: inline;
+ }
+ }
+ .westagram_facebook {
+ width: 205px;
+ color: #c7c7c7;
+ font-size: 11px;
+ font-weight: 400;
+ margin-top: 20px;
+ }
+ }
+}
\ No newline at end of file | Unknown | scss์ nesting์ ๊ต์ฅํ ์ ์ ์ฉํ์ ๊ฒ ๊ฐ์์
์ด๋ฌ๋ฉด ๋์ค์ component๋จ์๋ก ๋๋ ๋ ๋ ํธํ ๊ฒ ๊ฐ์ต๋๋ค! |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.