code stringlengths 41 34.3k | lang stringclasses 8
values | review stringlengths 1 4.74k |
|---|---|---|
@@ -0,0 +1,32 @@
+package blackjack.domain.card;
+
+import blackjack.domain.card.strategy.DrawStrategy;
+import blackjack.domain.card.strategy.RandomDrawStrategy;
+import lombok.Getter;
+
+import java.util.LinkedList;
+import java.util.List;
+
+public class Deck {
+
+ private static final String ALERT_NO_CARD_LEFT = "์ฌ์ฉ ๊ฐ๋ฅํ ์นด๋๋ฅผ ๋ชจ๋ ์์งํ์์ต๋๋ค.";
+
+ @Getter
+ private final List<Card> deck;
+
+ public Deck() {
+ this.deck = new LinkedList<>(DeckFactory.createDeck());
+ }
+
+ public Card drawCard() {
+ if (deck.isEmpty()) {
+ throw new RuntimeException(ALERT_NO_CARD_LEFT);
+ }
+ return deck.remove(generateNextDrawCardIndex(new RandomDrawStrategy()));
+ }
+
+ private int generateNextDrawCardIndex(DrawStrategy drawStrategy) {
+ return drawStrategy.getNextIndex(deck);
+ }
+
+} | Java | DrawStrategy ์ธํฐํ์ด์ค๋ฅผ ๋ง๋ค๊ณ ๊ทธ๊ฒ์ ๊ตฌํํ๋ RandomDrawStrategy ํด๋์ค๋ฅผ ๋ง๋ค์์ต๋๋ค. |
@@ -0,0 +1,39 @@
+package blackjack.domain.card;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+public class DeckFactory {
+
+ private static final List<Card> cardsDeck;
+
+ static {
+ cardsDeck = createCardsDeck();
+ }
+
+ private static List<Card> createCardsDeck() {
+ List<Card> cards = new ArrayList<>();
+
+ for (Denomination denomination : Denomination.values()) {
+ cards.addAll(createCards(denomination));
+ }
+ return cards;
+ }
+
+ private static List<Card> createCards(Denomination denomination) {
+ List<Card> cards = new ArrayList<>();
+
+ for (Type type : Type.values()) {
+ cards.add(new Card(denomination, type));
+ }
+
+ return cards;
+ }
+
+ public static List<Card> createDeck() {
+ return Collections.unmodifiableList(cardsDeck);
+ }
+}
+
+ | Java | ์คํํฑ๋ธ๋ก์ผ๋ก ๋ณ๊ฒฝํ์ต๋๋ค.
๊ธฐ๋ฅ์ ๋ฑํธ๋ฅผ ์ฌ์ฉํ ์ฝ๋์ ์ ํํ ๋์ผํ๊ฑด๊ฐ์? |
@@ -0,0 +1,38 @@
+package blackjack.domain.card;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class CardTest {
+
+ @DisplayName("์นด๋ ๊ฐ์ฒด์ ์ซ์์ ์ข
๋ฅ๊ฐ์ด ๊ฐ์ผ๋ฉด ๊ฐ์ ๊ฐ์ฒด๋ก ํ๋จํ๋ค")
+ @Test
+ void equalsTest() {
+ //given, when, then
+ assertThat(new Card(Denomination.TWO, Type.DIAMOND))
+ .isEqualTo(new Card(Denomination.TWO, Type.DIAMOND));
+
+ }
+
+ @DisplayName("์นด๋ ๊ฐ์ฒด์ ์ซ์์ ์ข
๋ฅ๋ฅผ ์ถ๋ ฅํ๋ค")
+ @Test
+ void printCardTwoDiamond() {
+ //given
+ Card card = new Card(Denomination.TWO, Type.DIAMOND);
+
+ //when, then
+ assertThat(card).hasToString("2๋ค์ด์๋ชฌ๋");
+ }
+
+ @DisplayName("์นด๋ ๊ฐ์ฒด์ ์ซ์์ ์ข
๋ฅ๋ฅผ ์ถ๋ ฅํ๋ค")
+ @Test
+ void printCardAceHeart() {
+ //given
+ Card card = new Card(Denomination.ACE, Type.HEART);
+
+ //when, then
+ assertThat(card.toString()).isEqualTo("Aํํธ");
+ }
+} | Java | assert๋ฌธ์ผ๋ก ๋ฌธ์์ด์ ๋น๊ตํ ๋๋ hasToString๋ฉ์๋๋ฅผ ์ฌ์ฉํ๊ฒ ์ต๋๋ค. |
@@ -0,0 +1,102 @@
+package blackjack.domain.participant;
+
+import blackjack.domain.card.Card;
+import blackjack.domain.card.Denomination;
+import lombok.Getter;
+import org.apache.commons.lang3.StringUtils;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+
+@Getter
+public abstract class Participant {
+ private static final int DIFFERENCE_OF_ACE_SCORE = 10;
+ private static final int BLACKJACK = 21;
+ private static final int ZERO = 0;
+ private static final String CHECK_NULL_OR_EMPTY = "์ด๋ฆ์ด ๋น ์นธ ํน์ null ๊ฐ์ด ์๋์ง ํ์ธํด์ฃผ์ธ์.";
+ private static final String CHECK_CONTAINING_ONLY_LETTERS_AND_DIGITS = "์ด๋ฆ์ ํน์๋ฌธ์๋ฅผ ํฌํจํ์ง ์์ ๋ฌธ์์ ์ซ์๋ก ์ง์ ํด์ฃผ์ธ์.";
+
+ private final String name;
+ private final List<Card> cards;
+
+ protected Participant(String name) {
+ validateName(name);
+
+ this.name = name;
+ this.cards = new ArrayList<>();
+ }
+
+ private void validateName(String name) {
+ validateNullOrEmpty(name);
+ validateAlphaNumeric(name);
+ }
+
+ private void validateNullOrEmpty(String name) {
+ if (StringUtils.isBlank(name)) {
+ throw new IllegalArgumentException(CHECK_NULL_OR_EMPTY);
+ }
+ }
+
+ private void validateAlphaNumeric(String name) {
+ if (!StringUtils.isAlphanumericSpace(name)) {
+ throw new IllegalArgumentException(CHECK_CONTAINING_ONLY_LETTERS_AND_DIGITS);
+ }
+ }
+
+ protected abstract boolean drawable();
+
+ public void receiveCard(Card card) {
+ cards.add(card);
+ }
+
+ public int getCardsSum() {
+ int scoreOfAceAsEleven = sumOfCardsScore();
+ int aceCount = getAceCount();
+
+ while (canCountAceAsOne(scoreOfAceAsEleven, aceCount)) {
+ scoreOfAceAsEleven = scoreOfAceAsOne(scoreOfAceAsEleven);
+ aceCount--;
+ }
+
+ return scoreOfAceAsEleven;
+ }
+
+ private int scoreOfAceAsOne(int scoreOfAceAsEleven) {
+ return scoreOfAceAsEleven - DIFFERENCE_OF_ACE_SCORE;
+ }
+
+ private boolean canCountAceAsOne(int scoreOfAceAsEleven, int aceCount) {
+ return scoreOfAceAsEleven > BLACKJACK && aceCount > ZERO;
+ }
+
+ private int getAceCount() {
+ return (int) cards.stream()
+ .filter(Card::isAce)
+ .count();
+ }
+
+ private int sumOfCardsScore() {
+ return cards.stream()
+ .map(Card::getDenomination)
+ .mapToInt(Denomination::getScore)
+ .sum();
+ }
+
+ public boolean isBust() {
+ return getCardsSum() > BLACKJACK;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Participant that = (Participant) o;
+ return Objects.equals(name, that.name) && Objects.equals(cards, that.cards);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(name, cards);
+ }
+} | Java | ์ด ๋ถ๋ถ ์ดํด๊ฐ ์ ์ ๋๋๋ฐ์,
์ ์๊ฐ์๋ Participant๊ฐ ๊ฐ์ง ์นด๋ ๋ชฉ๋ก์ ๋ฐ๋ผ ์์ด์ค๋ฅผ 1๋ก ๊ณ์ฐํ ์ง, 11๋ก ๊ณ์ฐํ ์ง ๋ค๋ฅด๊ฒ ํ๋จํด์ผ ํ๊ธฐ ๋๋ฌธ์
Participant์ ๋ก์ง์ธ ๊ฒ ๊ฐ์ต๋๋ค.
Denomination ์ธ๋ถ์ ์กฐ๊ฑด์ ๋ฐ๋ผ 1 ํน์ 11๋ก ๊ณ์ฐ๋๊ธฐ ๋๋ฌธ์ Denomination์ ํฌํจํ ์์ ๊ตฌ์กฐ์์ ๊ฒฐ์ ํ๋ ๊ฒ ๋ง๋ค๊ณ ์๊ฐํฉ๋๋ค.
Denomination์ score๋ฅผ 1๋ก ๊ฐ์ง๋ enum์ ์ถ๊ฐํด์ ๋ฆฌํฉํ ๋ง์ ์๋ํด๋ดค๋๋ฐ ์ด๋ป๊ฒ ํด์ผ ํ ์ง ์ ๋ชจ๋ฅด๊ฒ ์ต๋๋ค. |
@@ -0,0 +1,27 @@
+package blackjack.domain.participant;
+
+import lombok.Getter;
+
+@Getter
+public class Player extends Participant {
+
+ private static final int PLAYER_DRAW_THRESHOLD = 21;
+ private static final String DEALER_NAME = "๋๋ฌ";
+ private static final String CHECK_SAME_NAME_AS_DEALER = "์ด๋ฆ์ ๋๋ฌ์ ๊ฐ์ ์ ์์ผ๋ ๋ค๋ฅธ ์ด๋ฆ์ ์ง์ ํด์ฃผ์ธ์.";
+
+ public Player(String name) {
+ super(name);
+ validateDealerNameDuplicated(name);
+ }
+
+ private void validateDealerNameDuplicated(String name) {
+ if (name.equals(DEALER_NAME)) {
+ throw new IllegalArgumentException(CHECK_SAME_NAME_AS_DEALER);
+ }
+ }
+
+ @Override
+ public boolean drawable() {
+ return getCardsSum() < PLAYER_DRAW_THRESHOLD;
+ }
+} | Java | ๋ง์ํ์ ๋ถ๋ถ์ด ๋ง๋ค๊ณ ์๊ฐํฉ๋๋ค. ๋ฌธ์์ด ์์ฑ ๋ก์ง์ view๋ก ์ด๋ํ์ต๋๋ค. |
@@ -0,0 +1,27 @@
+package blackjack.domain.participant;
+
+import lombok.Getter;
+
+@Getter
+public class Player extends Participant {
+
+ private static final int PLAYER_DRAW_THRESHOLD = 21;
+ private static final String DEALER_NAME = "๋๋ฌ";
+ private static final String CHECK_SAME_NAME_AS_DEALER = "์ด๋ฆ์ ๋๋ฌ์ ๊ฐ์ ์ ์์ผ๋ ๋ค๋ฅธ ์ด๋ฆ์ ์ง์ ํด์ฃผ์ธ์.";
+
+ public Player(String name) {
+ super(name);
+ validateDealerNameDuplicated(name);
+ }
+
+ private void validateDealerNameDuplicated(String name) {
+ if (name.equals(DEALER_NAME)) {
+ throw new IllegalArgumentException(CHECK_SAME_NAME_AS_DEALER);
+ }
+ }
+
+ @Override
+ public boolean drawable() {
+ return getCardsSum() < PLAYER_DRAW_THRESHOLD;
+ }
+} | Java | orElseThrow๋ก ์์ ํ๊ณ , ๋ฉ์ธ์ง๋ฅผ ๋ด์ ์์ธ๋ฅผ ๋์ง๋๋ก ํ์ต๋๋ค. |
@@ -1,16 +1,28 @@
package webserver;
-import java.io.DataOutputStream;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import webserver.controller.*;
+import webserver.domain.HttpRequest;
+import webserver.domain.HttpResponse;
+
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import java.util.HashMap;
+import java.util.Map;
public class RequestHandler implements Runnable {
private static final Logger logger = LoggerFactory.getLogger(RequestHandler.class);
+ private static final Map<String, Controller> controllers = new HashMap<>();
+
+ static {
+ controllers.put("/user/create", new CreateUserController());
+ controllers.put("/user/login", new LoginController());
+ controllers.put("/user/list", new ListUserController());
+ controllers.put("/user/list.html", new ListUserController());
+ }
private Socket connection;
@@ -21,35 +33,12 @@ public RequestHandler(Socket connectionSocket) {
public void run() {
logger.debug("New Client Connect! Connected IP : {}, Port : {}", connection.getInetAddress(),
connection.getPort());
-
try (InputStream in = connection.getInputStream(); OutputStream out = connection.getOutputStream()) {
- // TODO ์ฌ์ฉ์ ์์ฒญ์ ๋ํ ์ฒ๋ฆฌ๋ ์ด ๊ณณ์ ๊ตฌํํ๋ฉด ๋๋ค.
- DataOutputStream dos = new DataOutputStream(out);
- byte[] body = "Hello World".getBytes();
- response200Header(dos, body.length);
- responseBody(dos, body);
- } catch (IOException e) {
- logger.error(e.getMessage());
- }
- }
-
- private void response200Header(DataOutputStream dos, int lengthOfBodyContent) {
- try {
- dos.writeBytes("HTTP/1.1 200 OK \r\n");
- dos.writeBytes("Content-Type: text/html;charset=utf-8\r\n");
- dos.writeBytes("Content-Length: " + lengthOfBodyContent + "\r\n");
- dos.writeBytes("\r\n");
- } catch (IOException e) {
- logger.error(e.getMessage());
- }
- }
-
- private void responseBody(DataOutputStream dos, byte[] body) {
- try {
- dos.write(body, 0, body.length);
- dos.flush();
+ HttpRequest httpRequest = new HttpRequest(in);
+ HttpResponse httpResponse = new HttpResponse(out);
+ controllers.getOrDefault(httpRequest.getPath(), new DefaultController()).service(httpRequest, httpResponse);
} catch (IOException e) {
logger.error(e.getMessage());
}
}
-}
+}
\ No newline at end of file | Java | path์ ๋ง๋ Controller ์ ์ ์ข์ต๋๋ค ๐ |
@@ -0,0 +1,80 @@
+package webserver.controller;
+
+import webserver.domain.HttpRequest;
+import webserver.domain.HttpResponse;
+import webserver.domain.HttpStatusCode;
+import webserver.exceptions.InvalidRequestException;
+import webserver.exceptions.NotYetSentException;
+
+public abstract class AbstractController implements Controller {
+
+ public void service(HttpRequest request, HttpResponse response) {
+ try {
+ System.out.println(request.getMethod().name() + " " + request.getPath());
+ methodMapping(request, response);
+ } catch (Exception e) {
+ if(!response.isSent()){
+ System.out.println("์์ ์ปจํธ๋กค๋ฌ์์ ์ฒ๋ฆฌ ๋๋ฝ๋ ์์ธ ์ํฉ : " + e.getMessage());
+ e.printStackTrace();
+ response.send(HttpStatusCode.NOT_IMPLEMENTED, e.getMessage());
+ }
+ } finally {
+ if (!response.isSent()) {
+ response.send(HttpStatusCode.INTERNAL_SERVER_ERROR);
+ throw new NotYetSentException("response์ ๋ฉ์๋ send()๊ฐ ํธ์ถ๋์ง ์์์ต๋๋ค");
+ }
+ }
+ }
+
+ private void methodMapping(HttpRequest request, HttpResponse response) {
+ switch (request.getMethod()) {
+ case GET:
+ validateGetRequest(request, response);
+ doGet(request, response);
+ return;
+ case POST:
+ validatePostRequest(request, response);
+ doPost(request, response);
+ return;
+ case PUT:
+ validatePutRequest(request, response);
+ doPut(request, response);
+ return;
+ case DELETE:
+ validateDeleteRequest(request, response);
+ doDelete(request, response);
+ return;
+ default:
+ response.send(HttpStatusCode.METHOD_NOT_ALLOWED);
+ }
+ }
+
+ public void doPost(HttpRequest request, HttpResponse response) {
+ response.send(HttpStatusCode.METHOD_NOT_ALLOWED);
+ }
+
+ public void doGet(HttpRequest request, HttpResponse response) {
+ response.send(HttpStatusCode.METHOD_NOT_ALLOWED);
+ }
+
+ public void doPut(HttpRequest request, HttpResponse response) {
+ response.send(HttpStatusCode.METHOD_NOT_ALLOWED);
+ }
+
+ public void doDelete(HttpRequest request, HttpResponse response) {
+ response.send(HttpStatusCode.METHOD_NOT_ALLOWED);
+ }
+
+ // ํ์์์ ์ค๋ฒ๋ผ์ด๋ฉ ํ์ฌ ์ธํ๊ฐ์ ๊ฒ์ฆํ๋ค
+ public void validatePostRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException {
+ }
+
+ public void validateGetRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException {
+ }
+
+ public void validatePutRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException {
+ }
+
+ public void validateDeleteRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException {
+ }
+} | Java | ์ถ์ ํด๋์ค service ๋ฉ์๋์ ํ๋ฆ์ ์ ๋ฆฌํ์ฌ ํ
ํ๋ฆฟ ๋ฉ์๋ ํจํด์ผ๋ก ์ ์ฉํด์ฃผ์
จ๋ค์ ๐ ๐ฏ |
@@ -0,0 +1,21 @@
+package webserver.controller;
+
+import utils.FileIoUtils;
+import webserver.domain.HttpRequest;
+import webserver.domain.HttpResponse;
+import webserver.domain.HttpStatusCode;
+
+import java.io.IOException;
+import java.net.URISyntaxException;
+
+public class DefaultController extends AbstractController {
+ @Override
+ public void doGet(HttpRequest httpRequest, HttpResponse httpResponse) {
+ try {
+ httpResponse.send(HttpStatusCode.OK, FileIoUtils.readStaticHttpFile(httpRequest.getPath()));
+ } catch (URISyntaxException | IOException e) {
+ httpResponse.send(HttpStatusCode.NOT_FOUND);
+ }
+ }
+
+} | Java | http://localhost:8080/index.html ๋ก ์ ์ํ์ ๋ ์ ์์ ์ธ ํ์ด์ง ํธ์ถ์ด ๋์ง ์๊ณ ์์ด์.
(index ๋ฟ๋ง ์๋๋ผ ์ ์ฒด์ ์ผ๋ก ์นํ์ด์ง ์๋ต์ด ์๋ชป ๋ ๊ฒ ๊ฐ์ต๋๋ค!)
์ด ๋ถ๋ถ ํ์ธ ๋ถํ๋๋ฆฝ๋๋ค. ๊ทธ๋ฆฌ๊ณ ํด๋น ๋ฉ์๋๋ Controller์ ๊ด์ฌ์ฌ๊ฐ ์๋๊ฒ ๊ฐ์์!
์ ํธ์ฑ ํด๋์ค๋ก ๋ง๋ค์ด์ง๋ ๊ฒ์ด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,32 @@
+package webserver.controller;
+
+import webserver.domain.HttpHeader;
+import webserver.domain.HttpRequest;
+import webserver.domain.HttpResponse;
+import webserver.domain.HttpStatusCode;
+import webserver.exceptions.InvalidRequestException;
+
+import java.io.IOException;
+
+import static service.JwpService.getProfilePage;
+import static service.JwpService.isLogin;
+
+public class ListUserController extends AbstractController {
+ @Override
+ public void doGet(HttpRequest httpRequest, HttpResponse httpResponse) {
+ try {
+ httpResponse.send(HttpStatusCode.OK, getProfilePage());
+ } catch (IOException e) {
+ httpResponse.send(HttpStatusCode.INTERNAL_SERVER_ERROR, "์ฝ์ด๋ค์ด๋๋ฐ ๋ฌธ์ ๊ฐ ๋ฐ์ํ์์ต๋๋ค");
+ }
+ }
+
+ @Override
+ public void validateGetRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException {
+ if (!isLogin(request.getHeaders().get(HttpHeader.COOKIE))) {
+ response.getHeaders().add(HttpHeader.LOCATION, "/user/login.html");
+ response.send(HttpStatusCode.FOUND);
+ throw new InvalidRequestException("์๋ชป๋ ๋ก๊ทธ์ธ ์์ฒญ");
+ }
+ }
+} | Java | TemplateView๋ฅผ ๋ง๋๋ ๋ถ๋ถ๋ Controller ๋ณด๋ค๋ ๋ค๋ฅธ ๊ณณ์์ ์ฌ์ฉํ ์ ์๋๋ก ์ ํธ์ฑ ํด๋์ค๋ก ๋ถ๋ฆฌํ๋๊ฒ ์ด๋จ๊น์? |
@@ -0,0 +1,32 @@
+package webserver.controller;
+
+import webserver.domain.HttpHeader;
+import webserver.domain.HttpRequest;
+import webserver.domain.HttpResponse;
+import webserver.domain.HttpStatusCode;
+import webserver.exceptions.InvalidRequestException;
+
+import java.io.IOException;
+
+import static service.JwpService.getProfilePage;
+import static service.JwpService.isLogin;
+
+public class ListUserController extends AbstractController {
+ @Override
+ public void doGet(HttpRequest httpRequest, HttpResponse httpResponse) {
+ try {
+ httpResponse.send(HttpStatusCode.OK, getProfilePage());
+ } catch (IOException e) {
+ httpResponse.send(HttpStatusCode.INTERNAL_SERVER_ERROR, "์ฝ์ด๋ค์ด๋๋ฐ ๋ฌธ์ ๊ฐ ๋ฐ์ํ์์ต๋๋ค");
+ }
+ }
+
+ @Override
+ public void validateGetRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException {
+ if (!isLogin(request.getHeaders().get(HttpHeader.COOKIE))) {
+ response.getHeaders().add(HttpHeader.LOCATION, "/user/login.html");
+ response.send(HttpStatusCode.FOUND);
+ throw new InvalidRequestException("์๋ชป๋ ๋ก๊ทธ์ธ ์์ฒญ");
+ }
+ }
+} | Java | login ์ํ์ธ์ง ์ฌ๋ถ๋ฅผ Request๊ฐ ์ ์ ์์ง ์์๊น์? ํด๋น ํ๋์ Request์๊ฒ ์์ํด์ค์๋ค! |
@@ -0,0 +1,46 @@
+package webserver.controller;
+
+import db.DataBase;
+import model.User;
+import webserver.domain.*;
+import webserver.exceptions.InvalidRequestException;
+
+public class LoginController extends AbstractController {
+ private static final String INVALID_REQUEST_MESSAGE = "userId, password๊ฐ ํ์ํฉ๋๋ค";
+ @Override
+ public void doPost(HttpRequest httpRequest, HttpResponse httpResponse) {
+ User findUser = DataBase.findUserById(httpRequest.getParameters().get("userId"));
+ if(findUser == null){
+ sendLoginFailed(httpResponse);
+ return;
+ }
+ if (!findUser.getPassword().equals(httpRequest.getParameters().get("password"))) {
+ sendLoginFailed(httpResponse);
+ return;
+ }
+ sendLoginSucceeded(httpResponse);
+ }
+
+ @Override
+ public void validatePostRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException {
+ HttpParameters httpParameters = request.getParameters();
+ if (httpParameters.contain("userId") && httpParameters.contain("password")) {
+ return;
+ }
+ response.send(HttpStatusCode.BAD_REQUEST, INVALID_REQUEST_MESSAGE);
+ throw new InvalidRequestException(INVALID_REQUEST_MESSAGE);
+ }
+
+ private void sendLoginSucceeded(HttpResponse httpResponse) {
+ httpResponse.getHeaders().add(HttpHeader.SET_COOKIE, "logined=true; Path=/");
+ httpResponse.getHeaders().add(HttpHeader.LOCATION, "/index.html");
+ httpResponse.send(HttpStatusCode.FOUND);
+ }
+
+ private void sendLoginFailed(HttpResponse httpResponse) {
+ httpResponse.getHeaders().add(HttpHeader.SET_COOKIE, "logined=false; Path=/");
+ httpResponse.getHeaders().add(HttpHeader.LOCATION, "/user/login_failed.html");
+ httpResponse.send(HttpStatusCode.FOUND);
+ }
+
+} | Java | response header์ cookie, location ์
ํ
ํด์ฃผ๋ ๋ถ๋ถ์ Response๋ก ์ฑ
์์ ์ด๋์ํฌ ์ ์์ง ์์๊น์?
Controller์์ ๋ก๊ทธ์ธ์ฌ๋ถ์ location๋ง httpResponse์๊ฒ ๋๊ธฐ๋ฉด ์์์ ์
ํ
๋์ด์ผํ ๊ฒ ๊ฐ์์ :) |
@@ -0,0 +1,80 @@
+package webserver.domain;
+
+import utils.IOUtils;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+
+
+public class HttpRequest {
+ private final HttpHeaders headers;
+ private final HttpParameters parameters;
+ private HttpMethod method;
+ private String body;
+ private String path;
+
+ public HttpRequest(InputStream in) throws IOException {
+ headers = new HttpHeaders();
+ parameters = new HttpParameters();
+ BufferedReader reader = new BufferedReader(new InputStreamReader(in));
+
+ readFirstLine(reader);
+ readHeaders(reader);
+ if (headers.contain(HttpHeader.CONTENT_LENGTH)) {
+ body = IOUtils.readData(reader, Integer.parseInt(headers.get(HttpHeader.CONTENT_LENGTH)));
+ parameters.parseAndSet(body);
+ }
+ }
+
+ private void readFirstLine(BufferedReader reader) throws IOException {
+ String[] firstLineTokens = reader.readLine().split(" ");
+ String requestUrl = firstLineTokens[1];
+ method = HttpMethod.valueOf(firstLineTokens[0]);
+ parseUrl(requestUrl);
+ }
+
+ private void readHeaders(BufferedReader reader) throws IOException {
+ String line = reader.readLine();
+ while (isValid(line)) {
+ String[] header = line.split(": ");
+ headers.add(header[0], header[1]);
+ line = reader.readLine();
+ }
+ }
+
+ private boolean isValid(String line) {
+ return (line != null) && !"".equals(line);
+ }
+
+ private void parseUrl(String requestUrl) {
+ if (requestUrl.indexOf('?') == -1) {
+ path = requestUrl;
+ return;
+ }
+ String[] urlToken = requestUrl.split("\\?");
+ path = urlToken[0];
+ parameters.parseAndSet(urlToken[1]);
+ }
+
+ public HttpHeaders getHeaders() {
+ return headers;
+ }
+
+ public HttpParameters getParameters() {
+ return parameters;
+ }
+
+ public HttpMethod getMethod() {
+ return method;
+ }
+
+ public String getBody() {
+ return body;
+ }
+
+ public String getPath() {
+ return path;
+ }
+} | Java | Request-Line์ ํ์ฑํ ๋ 1, 0 ๊ณผ ๊ฐ์ ์๋ฏธ๋ฅผ ์ฐพ๊ธฐ ์ด๋ ค์ด ๋ก์ง์ด ์กด์ฌํ๋๋ฐ์!
firstLine์ ์คํ์ Method SP Request-URI SP HTTP-Version CRLF ์ผ๋ก ์ ์๋ฉ๋๋ค.
์คํ์ ๋งค์น ํจํด์ผ๋ก ์ ์ํ๊ณ ๊ทธ์ ๋ง๊ฒ Index ์๋ฏธ๋ฅผ ๋ถ์ฌํด์ฃผ๋๊ฑด ์ด๋จ๊น์? |
@@ -0,0 +1,21 @@
+package webserver.controller;
+
+import utils.FileIoUtils;
+import webserver.domain.HttpRequest;
+import webserver.domain.HttpResponse;
+import webserver.domain.HttpStatusCode;
+
+import java.io.IOException;
+import java.net.URISyntaxException;
+
+public class DefaultController extends AbstractController {
+ @Override
+ public void doGet(HttpRequest httpRequest, HttpResponse httpResponse) {
+ try {
+ httpResponse.send(HttpStatusCode.OK, FileIoUtils.readStaticHttpFile(httpRequest.getPath()));
+ } catch (URISyntaxException | IOException e) {
+ httpResponse.send(HttpStatusCode.NOT_FOUND);
+ }
+ }
+
+} | Java | ์นํ์ด์ง๊ฐ ์ ๋จ๋๊ฒ ์๋๋ผ์ ์์ค๋ ์ ๋ฐ์์ค๋๋ฐ ์ ๊ทธ๋ฌ๋ ์ถ์๋๋ฐ, ๋ฒ๊ทธ์๋ค์. ์ ๊ณ ์ณ์ ๋ฐ์ํ ๊ฒ์! |
@@ -0,0 +1,80 @@
+package webserver.domain;
+
+import utils.IOUtils;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+
+
+public class HttpRequest {
+ private final HttpHeaders headers;
+ private final HttpParameters parameters;
+ private HttpMethod method;
+ private String body;
+ private String path;
+
+ public HttpRequest(InputStream in) throws IOException {
+ headers = new HttpHeaders();
+ parameters = new HttpParameters();
+ BufferedReader reader = new BufferedReader(new InputStreamReader(in));
+
+ readFirstLine(reader);
+ readHeaders(reader);
+ if (headers.contain(HttpHeader.CONTENT_LENGTH)) {
+ body = IOUtils.readData(reader, Integer.parseInt(headers.get(HttpHeader.CONTENT_LENGTH)));
+ parameters.parseAndSet(body);
+ }
+ }
+
+ private void readFirstLine(BufferedReader reader) throws IOException {
+ String[] firstLineTokens = reader.readLine().split(" ");
+ String requestUrl = firstLineTokens[1];
+ method = HttpMethod.valueOf(firstLineTokens[0]);
+ parseUrl(requestUrl);
+ }
+
+ private void readHeaders(BufferedReader reader) throws IOException {
+ String line = reader.readLine();
+ while (isValid(line)) {
+ String[] header = line.split(": ");
+ headers.add(header[0], header[1]);
+ line = reader.readLine();
+ }
+ }
+
+ private boolean isValid(String line) {
+ return (line != null) && !"".equals(line);
+ }
+
+ private void parseUrl(String requestUrl) {
+ if (requestUrl.indexOf('?') == -1) {
+ path = requestUrl;
+ return;
+ }
+ String[] urlToken = requestUrl.split("\\?");
+ path = urlToken[0];
+ parameters.parseAndSet(urlToken[1]);
+ }
+
+ public HttpHeaders getHeaders() {
+ return headers;
+ }
+
+ public HttpParameters getParameters() {
+ return parameters;
+ }
+
+ public HttpMethod getMethod() {
+ return method;
+ }
+
+ public String getBody() {
+ return body;
+ }
+
+ public String getPath() {
+ return path;
+ }
+} | Java | ๋งค์น ํจํด ์ข๋ค์ ์์ง ๋ฐ์์ ๋ชปํ์์ง๋ง ๋งค์น ํจํด์ด๋ผ๋ ์์ด๋์ด ์๋ ค์ฃผ์
์ ๊ฐ์ฌํฉ๋๋ค |
@@ -0,0 +1,46 @@
+package webserver.controller;
+
+import db.DataBase;
+import model.User;
+import webserver.domain.*;
+import webserver.exceptions.InvalidRequestException;
+
+public class LoginController extends AbstractController {
+ private static final String INVALID_REQUEST_MESSAGE = "userId, password๊ฐ ํ์ํฉ๋๋ค";
+ @Override
+ public void doPost(HttpRequest httpRequest, HttpResponse httpResponse) {
+ User findUser = DataBase.findUserById(httpRequest.getParameters().get("userId"));
+ if(findUser == null){
+ sendLoginFailed(httpResponse);
+ return;
+ }
+ if (!findUser.getPassword().equals(httpRequest.getParameters().get("password"))) {
+ sendLoginFailed(httpResponse);
+ return;
+ }
+ sendLoginSucceeded(httpResponse);
+ }
+
+ @Override
+ public void validatePostRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException {
+ HttpParameters httpParameters = request.getParameters();
+ if (httpParameters.contain("userId") && httpParameters.contain("password")) {
+ return;
+ }
+ response.send(HttpStatusCode.BAD_REQUEST, INVALID_REQUEST_MESSAGE);
+ throw new InvalidRequestException(INVALID_REQUEST_MESSAGE);
+ }
+
+ private void sendLoginSucceeded(HttpResponse httpResponse) {
+ httpResponse.getHeaders().add(HttpHeader.SET_COOKIE, "logined=true; Path=/");
+ httpResponse.getHeaders().add(HttpHeader.LOCATION, "/index.html");
+ httpResponse.send(HttpStatusCode.FOUND);
+ }
+
+ private void sendLoginFailed(HttpResponse httpResponse) {
+ httpResponse.getHeaders().add(HttpHeader.SET_COOKIE, "logined=false; Path=/");
+ httpResponse.getHeaders().add(HttpHeader.LOCATION, "/user/login_failed.html");
+ httpResponse.send(HttpStatusCode.FOUND);
+ }
+
+} | Java | Response์ ๋๊ฒจ์ฃผ๋ ค๊ณ ํ์์ง๋ง Response๊ฐ ์์ํ๊ฒ HTTP ์คํ์ ๋ฐ๋ฅธ ์ ์ก๋ง ๋๋๋ก ๊ฐ๊ฒฐํ๊ฒ ์ง์ฌ์ ธ์์ด์ ์ค๊ฐ ํด๋์ค๋ฅผ ๋ง๋๋ ๋ฐฉ๋ฒ์ผ๋ก ๊ณ ๋ฏผํด๋ณด๊ณ ์์ด์. |
@@ -0,0 +1,32 @@
+package webserver.controller;
+
+import webserver.domain.HttpHeader;
+import webserver.domain.HttpRequest;
+import webserver.domain.HttpResponse;
+import webserver.domain.HttpStatusCode;
+import webserver.exceptions.InvalidRequestException;
+
+import java.io.IOException;
+
+import static service.JwpService.getProfilePage;
+import static service.JwpService.isLogin;
+
+public class ListUserController extends AbstractController {
+ @Override
+ public void doGet(HttpRequest httpRequest, HttpResponse httpResponse) {
+ try {
+ httpResponse.send(HttpStatusCode.OK, getProfilePage());
+ } catch (IOException e) {
+ httpResponse.send(HttpStatusCode.INTERNAL_SERVER_ERROR, "์ฝ์ด๋ค์ด๋๋ฐ ๋ฌธ์ ๊ฐ ๋ฐ์ํ์์ต๋๋ค");
+ }
+ }
+
+ @Override
+ public void validateGetRequest(HttpRequest request, HttpResponse response) throws InvalidRequestException {
+ if (!isLogin(request.getHeaders().get(HttpHeader.COOKIE))) {
+ response.getHeaders().add(HttpHeader.LOCATION, "/user/login.html");
+ response.send(HttpStatusCode.FOUND);
+ throw new InvalidRequestException("์๋ชป๋ ๋ก๊ทธ์ธ ์์ฒญ");
+ }
+ }
+} | Java | Request ์ ์์ํ๋ฉด ํ๋ผ๋ฏธํฐ๋ฅผ ๋งคํํ๊ณ , ๊ฐ์ ํ ๋นํ๋ Request ์ญํ ๊น์ง๋ง ๋งก๊ธด ์ํ๋ผ ์ค๊ฐ ํด๋์ค๋ฅผ ๋ง๋๋ ๋ฐฉ์์ผ๋ก ๊ณ ๋ฏผ์ ํด๋ณด์์ด์. ๊ทธ๋ฌ๋ค๊ฐ, Spring ์ ์๋ ArgumentResolver ์ ์ ์ฌํ๊ฒ, ๊ฒ์ฆ์ด ํ์ํ ๋์๋ง ์ค๋ฒ๋ผ์ด๋ฉ ํ๋๋ก AbstractController์ validate...Request ๋ผ๋ ๋ฉ์๋๋ค์ ๋ง๋ค์ด ๋ณด์์ต๋๋ค.
์ด ๊ฒฝ์ฐ, ๋ก๊ทธ์ธ์ด ํ์ํ ์ ์ฌํ ์ปจํธ๋กค๋ฌ์ ๋ํด์ ์ค๋ณต ์ฝ๋๊ฐ ์์ฑ๋๋ค๋ ๋ถ๋ด์ด ์๋๋ฐ, ๋ก๊ทธ์ธ ์๋น์ค๋ฅผ ํตํฉํ๋ ์ถ์ ๊ฐ์ฒด์ธ ๋ก๊ทธ์ธ ์ปจํธ๋กค๋ฌ๋ฅผ ๋ง๋ค๊ฑฐ๋, ๋์ค์ MVC ๋ชจ๋ธ์ธ ์ด๋
ธํ
์ด์
์ ์ ์ฉํ ๊นํ๋๋ฐ ์ด๋ฐ ๋ฐฉ์์ ์ด๋ค๊ฐ์? |
@@ -0,0 +1,45 @@
+package controller;
+
+import controller.handler.Handler;
+import exception.utils.NoFileException;
+import model.request.HttpRequest;
+import model.response.HttpResponse;
+import model.PathInfo;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public abstract class Controller {
+ private static final Logger log = LoggerFactory.getLogger( Controller.class );
+ protected final Map<PathInfo, Handler> handlers = new HashMap<>();
+ protected String basePath = "";
+
+ public void putHandler(String path, String method, Handler handler) {
+ handlers.put(new PathInfo(basePath + path, method), handler);
+ }
+
+ public void setBasePath(String basePath) {
+ this.basePath = basePath;
+ }
+
+ public boolean hasSameBasePath(String path) {
+ return path.startsWith(basePath);
+ }
+
+ public boolean handle(HttpRequest request, HttpResponse response) throws NoFileException, IOException {
+ for (Map.Entry<PathInfo, Handler> entry : handlers.entrySet()) {
+ log.info("matching {} with controller {}", request.getPath(), entry.getKey().getPath());
+
+ if (request.getPath().matches(entry.getKey().getPath())) {
+ log.info("handling {} with controller {}", request.getPath(), entry.getKey().getPath());
+ entry.getValue().handle(request, response);
+ return true;
+ }
+ }
+ return false;
+ }
+} | Java | handlers ๋ ๊ตณ์ด LinkedHashMap ์ ์ฌ์ฉํ ์ด์ ๊ฐ ์์๊น์? |
@@ -0,0 +1,30 @@
+package model;
+
+import java.util.Objects;
+
+public class PathInfo {
+ private final String path;
+ private final String method;
+
+ public PathInfo(String path, String method) {
+ this.path = path;
+ this.method = method;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ PathInfo that = (PathInfo) o;
+ return Objects.equals(path, that.path) && Objects.equals(method, that.method);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(path, method);
+ }
+
+ public String getPath() {
+ return path;
+ }
+} | Java | PathInfo ๊ฐ์ฒด๋ฅผ ๋ณ๋๋ก ์ ์ธํ์
จ๊ตฐ์ ๐ฏ |
@@ -0,0 +1,44 @@
+package controller;
+
+import controller.handler.SecuredHandler;
+import model.request.HttpRequest;
+import model.response.HttpResponse;
+import service.UserService;
+import view.View;
+
+import java.io.IOException;
+import java.io.OutputStream;
+
+public class UserController extends Controller {
+ {
+ setBasePath("/user");
+ putHandler("/create", "POST", this::handleCreate);
+ putHandler("/login", "POST", this::handleLogin);
+ putHandler("/list", "GET", new SecuredHandler(this::handleUserList));
+ putHandler("/logout", "GET", new SecuredHandler(this::handleLogout));
+ }
+
+ private UserService userService = new UserService();
+
+ public void handleCreate(HttpRequest request, HttpResponse response) {
+ userService.addUser(request.getParsedBody());
+ response.sendRedirect("/index.html");
+ }
+
+ public void handleLogin(HttpRequest request, HttpResponse response) {
+ if (!userService.login(request.getParsedBody())) {
+ response.setCookie("logined=false").sendRedirect("/user/login_failed.html");
+ return;
+ }
+ response.setCookie("logined=true").sendRedirect("/index.html");
+ }
+
+ public void handleUserList(HttpRequest request, HttpResponse response) throws IOException {
+ byte[] body = View.getUsersView(userService.findAll(), "/user/list");
+ response.sendView(body);
+ }
+
+ public void handleLogout(HttpRequest request, HttpResponse response) throws IOException {
+ response.setCookie("logined=false").sendRedirect("/index.html");
+ }
+} | Java | DataBase ์ ์ง์ ์ ๊ทผํ์ง ๋ง๊ณ ๋ณ๋์ ์๋น์ค ํด๋์ค๋ก ๋ถ๋ฆฌํด๋ณด๋ฉด ์ด๋จ๊น์? |
@@ -0,0 +1,44 @@
+package controller;
+
+import controller.handler.SecuredHandler;
+import model.request.HttpRequest;
+import model.response.HttpResponse;
+import service.UserService;
+import view.View;
+
+import java.io.IOException;
+import java.io.OutputStream;
+
+public class UserController extends Controller {
+ {
+ setBasePath("/user");
+ putHandler("/create", "POST", this::handleCreate);
+ putHandler("/login", "POST", this::handleLogin);
+ putHandler("/list", "GET", new SecuredHandler(this::handleUserList));
+ putHandler("/logout", "GET", new SecuredHandler(this::handleLogout));
+ }
+
+ private UserService userService = new UserService();
+
+ public void handleCreate(HttpRequest request, HttpResponse response) {
+ userService.addUser(request.getParsedBody());
+ response.sendRedirect("/index.html");
+ }
+
+ public void handleLogin(HttpRequest request, HttpResponse response) {
+ if (!userService.login(request.getParsedBody())) {
+ response.setCookie("logined=false").sendRedirect("/user/login_failed.html");
+ return;
+ }
+ response.setCookie("logined=true").sendRedirect("/index.html");
+ }
+
+ public void handleUserList(HttpRequest request, HttpResponse response) throws IOException {
+ byte[] body = View.getUsersView(userService.findAll(), "/user/list");
+ response.sendView(body);
+ }
+
+ public void handleLogout(HttpRequest request, HttpResponse response) throws IOException {
+ response.setCookie("logined=false").sendRedirect("/index.html");
+ }
+} | Java | ์์ ๋ง์ฐฌ๊ฐ์ง๋ก ์ง์ DataBase ์ ์ ๊ทผํ๊ธฐ ๋ณด๋ค ์๋น์ค ๊ฐ์ฒด๋ฅผ ์ฌ์ฉํ๋ ๋ฐฉ๋ฒ์ ์ด๋จ๊น์?
๋๊ฒจ์ค ๊ฐ์ ๊ธฐ๋ฐ์ผ๋ก ๋ก๊ทธ์ธ ๋์๋์ง ๋์ง ์์๋์ง ์ฌ๋ถ๋ฅผ boolean ๊ฐ์ผ๋ก ์กฐํํ ์ ์๋ค๋ฉด
์ข ๋ ๊ฐ๊ฒฐํ ์ฝ๋๋ก ๊ฐ์ ํ ์ ์์๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,45 @@
+package controller;
+
+import controller.handler.Handler;
+import exception.utils.NoFileException;
+import model.request.HttpRequest;
+import model.response.HttpResponse;
+import model.PathInfo;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public abstract class Controller {
+ private static final Logger log = LoggerFactory.getLogger( Controller.class );
+ protected final Map<PathInfo, Handler> handlers = new HashMap<>();
+ protected String basePath = "";
+
+ public void putHandler(String path, String method, Handler handler) {
+ handlers.put(new PathInfo(basePath + path, method), handler);
+ }
+
+ public void setBasePath(String basePath) {
+ this.basePath = basePath;
+ }
+
+ public boolean hasSameBasePath(String path) {
+ return path.startsWith(basePath);
+ }
+
+ public boolean handle(HttpRequest request, HttpResponse response) throws NoFileException, IOException {
+ for (Map.Entry<PathInfo, Handler> entry : handlers.entrySet()) {
+ log.info("matching {} with controller {}", request.getPath(), entry.getKey().getPath());
+
+ if (request.getPath().matches(entry.getKey().getPath())) {
+ log.info("handling {} with controller {}", request.getPath(), entry.getKey().getPath());
+ entry.getValue().handle(request, response);
+ return true;
+ }
+ }
+ return false;
+ }
+} | Java | handle ๋ฉ์๋์ ์ฒซ๋ฒ์งธ ์ธ์๋ HttpRequest ์ธ๋ฐ, ๋๋ฒ์งธ ์ธ์๋ OutputStream ์ด๋ค์.
HttpRequest / HttpResponse ํํ๊ฐ ๋ ์ ํฉํด ๋ณด์
๋๋ค ๐ |
@@ -0,0 +1,66 @@
+package controller;
+
+import controller.error.ErrorHandlerFactory;
+import controller.handler.Handler;
+import exception.utils.NoFileException;
+import model.request.HttpRequest;
+import model.response.HttpResponse;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import webserver.RequestHandler;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.Socket;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class ControllerManager {
+ private static final Logger log = LoggerFactory.getLogger(RequestHandler.class);
+ private static final List<Controller> controllers = new ArrayList<>();
+ static {
+ registerController(new ViewController());
+ registerController(new UserController());
+ }
+
+ public static void registerController(Controller controller) {
+ controllers.add(controller);
+ }
+
+ public static void runControllers(Socket connection) {
+ try (InputStream in = connection.getInputStream(); OutputStream out = connection.getOutputStream()) {
+ HttpRequest httpRequest = HttpRequest.of(in);
+ HttpResponse httpResponse = HttpResponse.of(out);
+ handleRequest(httpRequest, httpResponse);
+ } catch (IOException e) {
+ log.error("{} {}", e.getMessage(), e.getStackTrace());
+ }
+ }
+
+ private static void handleRequest(HttpRequest httpRequest, HttpResponse httpResponse) {
+ List<Controller> selectedControllers = controllers.stream()
+ .filter(controller -> controller.hasSameBasePath(httpRequest.getPath()))
+ .collect(Collectors.toList());
+ try {
+ for (Controller controller : selectedControllers) {
+ if (controller.handle(httpRequest, httpResponse)) return;
+ }
+
+ defaultHandle(httpRequest, httpResponse);
+ } catch (NoFileException | IOException | RuntimeException e) {
+ Handler errorHandler = ErrorHandlerFactory.getHandler(e);
+ try {
+ errorHandler.handle(httpRequest, httpResponse);
+ log.warn(e.getMessage());
+ } catch (Exception handleError) {
+ log.error("{} {}", handleError.getMessage(), handleError.getStackTrace());
+ }
+ }
+ }
+
+ public static void defaultHandle(HttpRequest request, HttpResponse response) throws NoFileException {
+ response.forward("./templates", request.getPath());
+ }
+} | Java | ์ปจํธ๋กค๋ฌ ๋งค๋์ ๊น์ง ์์ฑํ์
จ๋ค์ ๐ |
@@ -1,16 +1,48 @@
package model;
+import exception.user.WrongEmailException;
+import exception.user.WrongIdException;
+import exception.user.WrongNameException;
+import exception.user.WrongPasswordException;
+
public class User {
- private String userId;
- private String password;
- private String name;
- private String email;
+ private final String userId;
+ private final String password;
+ private final String name;
+ private final String email;
public User(String userId, String password, String name, String email) {
- this.userId = userId;
- this.password = password;
- this.name = name;
- this.email = email;
+ this.userId = validateId(userId);
+ this.password = validatePw(password);
+ this.name = validateName(name);
+ this.email = validateEmail(email.replace("%40", "@"));
+ }
+
+ private String validatePw(String password) {
+ if(!password.matches("^[\\w]{1,30}$")){
+ throw new WrongPasswordException();
+ }
+ return password;
+ }
+
+ private String validateId(String userId) {
+ if(!userId.matches("^[\\w]{1,30}$"))
+ throw new WrongIdException();
+ return userId;
+ }
+
+ private String validateName(String name) {
+ if (!name.matches("^[\\w๊ฐ-ํฃ]{1,30}$")) {
+ throw new WrongNameException();
+ }
+ return name;
+ }
+
+ private String validateEmail(String email) {
+ if(!email.matches("^[\\w]{1,30}@[\\w]{1,30}.[\\w]{1,30}$")){
+ throw new WrongEmailException();
+ }
+ return email;
}
public String getUserId() { | Java | validation ๋ก์ง์ ์ถ๊ฐํ์ ๊ฒ์ ๊ธ์ ์ ์
๋๋ค.
๋ค๋ง User ๊ฐ์ฒด๊ฐ ์ธ์คํด์คํ ๋ ๋๋ง๋ค validate ๋ฉ์๋๊ฐ ํธ์ถ๋๊ฒ ๋๋๋ฐ์.
User ๋ผ๋ ๋๋ฉ์ธ ๋ชจ๋ธ์ด ๊ฐ์ถ๊ณ ์์ด์ผํ ํ์์ ์ธ validation ์ธ์ง
์๋๋ฉด ์๋ก์ด User ๋ฅผ ์์ฑํ๋ ์ฌ์ฉ์์ ์์ฒญ์์๋ง ํ์ํ validation ์ธ์ง์ ๋ฐ๋ผ์
User ๊ฐ์ฒด์์ ์ฒ๋ฆฌํ๋๊ฒ ์ ํฉํ ์๋ ์๊ณ / Controller ์์ญ์์ ์ฒ๋ฆฌํ๋ ๊ฒ์ด ๋ ๋์ ์๋ ์์ต๋๋ค.
์ด๋ถ๋ถ์ ํ๋ฒ ๊ณ ๋ฏผํด๋ด์ฃผ์ธ์ ๐ |
@@ -0,0 +1,7 @@
+package exception.utils;
+
+public class NoFileException extends Exception {
+ public NoFileException(String path) {
+ super(path + " ํ์ผ์ ์ฐพ์ ์ ์์ต๋๋ค.");
+ }
+} | Java | NoFIleException ๊ณผ ๊ฐ์ ๊ฒฝ์ฐ์๋ ์ด๋ค ํ์ผ์ ์ฐพ์ ์ ์๋์ง ํ์๋ ์ ์๊ฒ ๊ฐ์ ๋๋ฉด ๋ ์ข๊ฒ ์ต๋๋ค. |
@@ -0,0 +1,30 @@
+package controller;
+
+import exception.utils.NoFileException;
+import model.request.HttpRequest;
+import model.response.HttpResponse;
+
+import java.io.IOException;
+import java.io.OutputStream;
+
+public class ViewController extends Controller {
+
+ {
+ setBasePath("");
+ putHandler("/js/.*", "GET", this::handleFile);
+ putHandler("/css/.*", "GET", this::handleFile);
+ putHandler("/fonts/.*", "GET", this::handleFile);
+ putHandler("/favicon.ico", "GET", this::handleFile);
+ putHandler("/index.html", "GET", this::handleView);
+ putHandler("/", "GET", this::handleView);
+ }
+
+ public void handleFile(HttpRequest request, HttpResponse response) throws NoFileException {
+ response.forward("./static", request.getPath());
+ }
+
+ public void handleView(HttpRequest request, HttpResponse response) throws NoFileException {
+ response.forward("./templates",
+ (request.getPath().equals("/") ? "/index.html" : request.getPath()));
+ }
+} | Java | 
Fonts ํ์ผ์ด ๋ก๋ฉ๋์ง ์๋ ํ์์ด ์์ต๋๋ค. ํ์ธ ๋ถํ๋๋ ค์ :smile |
@@ -0,0 +1,45 @@
+package controller;
+
+import controller.handler.Handler;
+import exception.utils.NoFileException;
+import model.request.HttpRequest;
+import model.response.HttpResponse;
+import model.PathInfo;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public abstract class Controller {
+ private static final Logger log = LoggerFactory.getLogger( Controller.class );
+ protected final Map<PathInfo, Handler> handlers = new HashMap<>();
+ protected String basePath = "";
+
+ public void putHandler(String path, String method, Handler handler) {
+ handlers.put(new PathInfo(basePath + path, method), handler);
+ }
+
+ public void setBasePath(String basePath) {
+ this.basePath = basePath;
+ }
+
+ public boolean hasSameBasePath(String path) {
+ return path.startsWith(basePath);
+ }
+
+ public boolean handle(HttpRequest request, HttpResponse response) throws NoFileException, IOException {
+ for (Map.Entry<PathInfo, Handler> entry : handlers.entrySet()) {
+ log.info("matching {} with controller {}", request.getPath(), entry.getKey().getPath());
+
+ if (request.getPath().matches(entry.getKey().getPath())) {
+ log.info("handling {} with controller {}", request.getPath(), entry.getKey().getPath());
+ entry.getValue().handle(request, response);
+ return true;
+ }
+ }
+ return false;
+ }
+} | Java | Handlers ๊ฐ ์์๋ฅผ ๊ธฐ๋ฐ์ผ๋ก ๋ฑ๋ก๋์ด์ผ ํ ํ์๊ฐ ์๋ค๋ฉด ์ฐจํ์ ์ค์ํ๊ธฐ ์ฌ์ด ๊ตฌ์กฐ ์
๋๋ค.
path ๋ฅผ ๊ธฐ๋ฐ์ผ๋ก ๋์ํ handler ๊ฐ ๋ค๋ฅธ ๋ฐฉ์์ผ๋ก ๋งค์นญ๋ ์๋ ์์์ง ๊ณ ๋ฏผํด๋ด์ฃผ์ธ์ ๐ |
@@ -0,0 +1,85 @@
+package model.request;
+
+import utils.IOUtils;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+
+public class HttpRequest {
+ private HttpRequestLine httpRequestLine;
+ private HttpRequestHeader httpRequestHeader;
+
+ private String body = "";
+
+ private HttpRequest(BufferedReader br) throws IOException {
+ String line = br.readLine();
+ httpRequestLine = new HttpRequestLine(line);
+ httpRequestHeader = new HttpRequestHeader(br);
+ setBody(br);
+ }
+
+ public static HttpRequest of(InputStream in) throws IOException {
+ return new HttpRequest(new BufferedReader(new InputStreamReader(in)));
+ }
+
+ private void setBody(BufferedReader br) throws IOException {
+ while(br.ready()){
+ body = IOUtils.readData(br, Integer.parseInt(getHeader("Content-Length")));
+ }
+ }
+
+ public String getBody() {
+ return body;
+ }
+
+ public Map<String, String> getParsedBody(){
+ Map<String, String> parsedBody = new HashMap<>();
+ String[] queryParams = body.split("&");
+ Arrays.stream(queryParams).forEach((param) -> {
+ String[] args = param.split("=", 2);
+ parsedBody.put(args[0].trim(), args[1].trim());
+ });
+ return parsedBody;
+ }
+
+ public String getCookie(String cookieParam){
+ Map<String, String> parsedCookie = new HashMap<>();
+ String cookieHeader = getHeader("Cookie");
+
+ String[] cookies = cookieHeader.split(";");
+ Arrays.stream(cookies).forEach((cookie) -> {
+ String[] args = cookie.split("=", 2);
+ parsedCookie.put(args[0].trim(), args[1].trim());
+ });
+ return parsedCookie.get(cookieParam);
+ }
+
+ public Map<String, String> getHeaderMap() {
+ return httpRequestHeader.getHeaderMap();
+ }
+
+ public String getHeader(String key){
+ return httpRequestHeader.getHeader(key);
+ }
+
+ public String getMethod() {
+ return httpRequestLine.getMethod();
+ }
+
+ public String getPath() {
+ return httpRequestLine.getPath();
+ }
+
+ public String getProtocol() {
+ return httpRequestLine.getProtocol();
+ }
+
+ public Map<String, String> getQueryParameterMap() {
+ return httpRequestLine.getQueryParameterMap();
+ }
+} | Java | InputStream ์ ๋ฐ์์ HttpRequest ์ธ์คํด์ค๋ฅผ ์์ฑํ๋ static method ๋ก ๋ณ๊ฒฝํด๋ณด๋๊ฑด ์ด๋จ๊น์? |
@@ -1,7 +1,128 @@
+import { useNavigate } from 'react-router-dom';
+import { useState } from 'react';
import './Login.scss';
function Login() {
- return <></>;
+ // const [idState, setIdState] = useState('');
+ // const [passwordValue, setPasswordValue] = useState('');
+ // const [disabled, setDisabled] = useState(true);
+ // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' });
+
+ const navigate = useNavigate();
+ const [loginValues, setLoginValues] = useState({
+ id: '',
+ password: '',
+ });
+
+ const handleInputValue = e => {
+ const { name, value } = e.target;
+ setLoginValues({ ...loginValues, [name]: value });
+ };
+
+ // const { type, value } = event.target;
+
+ // function handleLogin(event) {
+ // if (type === 'text') {
+ // setIdState(value);
+ // } else if (type === 'password') {
+ // setPasswordValue(value);
+ // }
+ // handleButton();
+ // }
+
+ // const checkId = idValue => {
+ // return idValue.includes('@') ? true : false;
+ // };
+
+ // const checkPw = pwValue => {
+ // return pwValue.length >= 5 ? true : false;
+ // };
+
+ // const handleButton = () => {
+ // const isValidId = checkId(state);
+ // const isValidPw = checkPw(passwordValue);
+
+ // if (isValidId && isValidPw) {
+ // buttonColor(true);
+ // } else {
+ // buttonColor(false);
+ // }
+ // };
+
+ // const buttonColor = btnValid => {
+ // setDisabled(!btnValid);
+ // setStyle({
+ // opacity: btnValid ? 1 : 0.5,
+ // cursor: btnValid ? 'pointer' : 'default',
+ // });
+ // };
+
+ const goToMain = () => {
+ fetch('http://10.58.4.238:8000/users/login', {
+ method: 'POST',
+ body: JSON.stringify({
+ email: loginValues.id,
+ password: loginValues.password,
+ // name: '๋์',
+ // phone_number: '010-1111-111',
+ }),
+ })
+ .then(response => response.json())
+ .then(result => {
+ // console.log(result);
+ if (result.token) {
+ //localStorage.setItem('token', result.token);
+ alert('ํ์ํฉ๋๋ค!');
+ navigate('/main-han');
+ } else if (result.message === 'INVALID_USER') {
+ alert('ID์ PW๋ฅผ ํ์ธํด์ฃผ์ธ์.');
+ }
+ });
+ };
+
+ const isInputValid =
+ loginValues.id.includes('@') &&
+ loginValues.id.length >= 6 &&
+ loginValues.password.length >= 6;
+ // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6);
+ // console.log(loginValues.password.length >= 6);
+ // console.log(isInputValid);
+
+ return (
+ <div className="login">
+ <form className="loginBox">
+ <h1>Westagram</h1>
+ <input
+ id="id"
+ name="id"
+ className="userId"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={handleInputValue}
+ />
+ <input
+ id="password"
+ name="password"
+ className="userPassword"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={handleInputValue}
+ />
+ <button
+ type="button"
+ className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`}
+ onClick={goToMain}
+ disabled={!isInputValid}
+ //style={style}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div className="findPassword">
+ <a href="#">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </form>
+ </div>
+ );
}
export default Login; | JavaScript | ```suggestion
className={`loginBtn ${
idValue.indexOf('@') > -1 && pwValue.length >= 5
? 'loginBtnLive'
: ''
}`}
```
className์ ๋์ ์ฌ์ฉ์ ์ ์ฉํ๋ฉด ์ข์ ๊ฒ ๊ฐ์์
์ธ๋ผ์ธ ์คํ์ผ์ ์ฐ์ ์์๊ฐ ๋์์, ํ์์ด class๋ฅผ ์์ ํ์ ๋
class๊ฐ ์ ์ฉ์ด ์๋๋ ๋ฌธ์ ๊ฐ ์๋ค๊ณ ํด์.
์กฐ๊ฑด ์ฐ์ฐ์๋ฅผ ํ์ฉํด์ className์ ๋์ ์ผ๋ก ์ธ ์ ์์
className={์๋ ํด๋์ค +ํ์ฑํ ํด๋์ค <-- ์กฐ๊ฑด ์ฐ์ฐ์๋ก ํด๋์ค ์ถ๊ฐ ์ฌ๋ถ ๊ฒฐ์ } |
@@ -1,7 +1,128 @@
+import { useNavigate } from 'react-router-dom';
+import { useState } from 'react';
import './Login.scss';
function Login() {
- return <></>;
+ // const [idState, setIdState] = useState('');
+ // const [passwordValue, setPasswordValue] = useState('');
+ // const [disabled, setDisabled] = useState(true);
+ // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' });
+
+ const navigate = useNavigate();
+ const [loginValues, setLoginValues] = useState({
+ id: '',
+ password: '',
+ });
+
+ const handleInputValue = e => {
+ const { name, value } = e.target;
+ setLoginValues({ ...loginValues, [name]: value });
+ };
+
+ // const { type, value } = event.target;
+
+ // function handleLogin(event) {
+ // if (type === 'text') {
+ // setIdState(value);
+ // } else if (type === 'password') {
+ // setPasswordValue(value);
+ // }
+ // handleButton();
+ // }
+
+ // const checkId = idValue => {
+ // return idValue.includes('@') ? true : false;
+ // };
+
+ // const checkPw = pwValue => {
+ // return pwValue.length >= 5 ? true : false;
+ // };
+
+ // const handleButton = () => {
+ // const isValidId = checkId(state);
+ // const isValidPw = checkPw(passwordValue);
+
+ // if (isValidId && isValidPw) {
+ // buttonColor(true);
+ // } else {
+ // buttonColor(false);
+ // }
+ // };
+
+ // const buttonColor = btnValid => {
+ // setDisabled(!btnValid);
+ // setStyle({
+ // opacity: btnValid ? 1 : 0.5,
+ // cursor: btnValid ? 'pointer' : 'default',
+ // });
+ // };
+
+ const goToMain = () => {
+ fetch('http://10.58.4.238:8000/users/login', {
+ method: 'POST',
+ body: JSON.stringify({
+ email: loginValues.id,
+ password: loginValues.password,
+ // name: '๋์',
+ // phone_number: '010-1111-111',
+ }),
+ })
+ .then(response => response.json())
+ .then(result => {
+ // console.log(result);
+ if (result.token) {
+ //localStorage.setItem('token', result.token);
+ alert('ํ์ํฉ๋๋ค!');
+ navigate('/main-han');
+ } else if (result.message === 'INVALID_USER') {
+ alert('ID์ PW๋ฅผ ํ์ธํด์ฃผ์ธ์.');
+ }
+ });
+ };
+
+ const isInputValid =
+ loginValues.id.includes('@') &&
+ loginValues.id.length >= 6 &&
+ loginValues.password.length >= 6;
+ // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6);
+ // console.log(loginValues.password.length >= 6);
+ // console.log(isInputValid);
+
+ return (
+ <div className="login">
+ <form className="loginBox">
+ <h1>Westagram</h1>
+ <input
+ id="id"
+ name="id"
+ className="userId"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={handleInputValue}
+ />
+ <input
+ id="password"
+ name="password"
+ className="userPassword"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={handleInputValue}
+ />
+ <button
+ type="button"
+ className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`}
+ onClick={goToMain}
+ disabled={!isInputValid}
+ //style={style}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div className="findPassword">
+ <a href="#">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </form>
+ </div>
+ );
}
export default Login; | JavaScript | className ๋์ ์ฌ์ฉ์ ํ๊ฒ ๋๋ฉด
style ์คํ
์ดํธ๊ฐ ํ์์๊ฒ ๋๋ค๊ณ ํด์!
disabled๋ state๋ก ๋จ๊ฒจ๋์ง ๊ณ ๋ฏผํด๋ณด๋ผ๊ณ ํ์ญ๋๋ค (from ๋ฉํ ๋..) |
@@ -1,7 +1,128 @@
+import { useNavigate } from 'react-router-dom';
+import { useState } from 'react';
import './Login.scss';
function Login() {
- return <></>;
+ // const [idState, setIdState] = useState('');
+ // const [passwordValue, setPasswordValue] = useState('');
+ // const [disabled, setDisabled] = useState(true);
+ // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' });
+
+ const navigate = useNavigate();
+ const [loginValues, setLoginValues] = useState({
+ id: '',
+ password: '',
+ });
+
+ const handleInputValue = e => {
+ const { name, value } = e.target;
+ setLoginValues({ ...loginValues, [name]: value });
+ };
+
+ // const { type, value } = event.target;
+
+ // function handleLogin(event) {
+ // if (type === 'text') {
+ // setIdState(value);
+ // } else if (type === 'password') {
+ // setPasswordValue(value);
+ // }
+ // handleButton();
+ // }
+
+ // const checkId = idValue => {
+ // return idValue.includes('@') ? true : false;
+ // };
+
+ // const checkPw = pwValue => {
+ // return pwValue.length >= 5 ? true : false;
+ // };
+
+ // const handleButton = () => {
+ // const isValidId = checkId(state);
+ // const isValidPw = checkPw(passwordValue);
+
+ // if (isValidId && isValidPw) {
+ // buttonColor(true);
+ // } else {
+ // buttonColor(false);
+ // }
+ // };
+
+ // const buttonColor = btnValid => {
+ // setDisabled(!btnValid);
+ // setStyle({
+ // opacity: btnValid ? 1 : 0.5,
+ // cursor: btnValid ? 'pointer' : 'default',
+ // });
+ // };
+
+ const goToMain = () => {
+ fetch('http://10.58.4.238:8000/users/login', {
+ method: 'POST',
+ body: JSON.stringify({
+ email: loginValues.id,
+ password: loginValues.password,
+ // name: '๋์',
+ // phone_number: '010-1111-111',
+ }),
+ })
+ .then(response => response.json())
+ .then(result => {
+ // console.log(result);
+ if (result.token) {
+ //localStorage.setItem('token', result.token);
+ alert('ํ์ํฉ๋๋ค!');
+ navigate('/main-han');
+ } else if (result.message === 'INVALID_USER') {
+ alert('ID์ PW๋ฅผ ํ์ธํด์ฃผ์ธ์.');
+ }
+ });
+ };
+
+ const isInputValid =
+ loginValues.id.includes('@') &&
+ loginValues.id.length >= 6 &&
+ loginValues.password.length >= 6;
+ // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6);
+ // console.log(loginValues.password.length >= 6);
+ // console.log(isInputValid);
+
+ return (
+ <div className="login">
+ <form className="loginBox">
+ <h1>Westagram</h1>
+ <input
+ id="id"
+ name="id"
+ className="userId"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={handleInputValue}
+ />
+ <input
+ id="password"
+ name="password"
+ className="userPassword"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={handleInputValue}
+ />
+ <button
+ type="button"
+ className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`}
+ onClick={goToMain}
+ disabled={!isInputValid}
+ //style={style}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div className="findPassword">
+ <a href="#">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </form>
+ </div>
+ );
}
export default Login; | JavaScript | className ๋์ ์ฌ์ฉ์ ํ๊ฒ ๋๋ฉด
์ ํจ์ฑ ๊ฒ์ฌ ๊ด๋ จ ํจ์๋ฅผ ๋ค ์ง์๋ ๋ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -1,7 +1,128 @@
+import { useNavigate } from 'react-router-dom';
+import { useState } from 'react';
import './Login.scss';
function Login() {
- return <></>;
+ // const [idState, setIdState] = useState('');
+ // const [passwordValue, setPasswordValue] = useState('');
+ // const [disabled, setDisabled] = useState(true);
+ // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' });
+
+ const navigate = useNavigate();
+ const [loginValues, setLoginValues] = useState({
+ id: '',
+ password: '',
+ });
+
+ const handleInputValue = e => {
+ const { name, value } = e.target;
+ setLoginValues({ ...loginValues, [name]: value });
+ };
+
+ // const { type, value } = event.target;
+
+ // function handleLogin(event) {
+ // if (type === 'text') {
+ // setIdState(value);
+ // } else if (type === 'password') {
+ // setPasswordValue(value);
+ // }
+ // handleButton();
+ // }
+
+ // const checkId = idValue => {
+ // return idValue.includes('@') ? true : false;
+ // };
+
+ // const checkPw = pwValue => {
+ // return pwValue.length >= 5 ? true : false;
+ // };
+
+ // const handleButton = () => {
+ // const isValidId = checkId(state);
+ // const isValidPw = checkPw(passwordValue);
+
+ // if (isValidId && isValidPw) {
+ // buttonColor(true);
+ // } else {
+ // buttonColor(false);
+ // }
+ // };
+
+ // const buttonColor = btnValid => {
+ // setDisabled(!btnValid);
+ // setStyle({
+ // opacity: btnValid ? 1 : 0.5,
+ // cursor: btnValid ? 'pointer' : 'default',
+ // });
+ // };
+
+ const goToMain = () => {
+ fetch('http://10.58.4.238:8000/users/login', {
+ method: 'POST',
+ body: JSON.stringify({
+ email: loginValues.id,
+ password: loginValues.password,
+ // name: '๋์',
+ // phone_number: '010-1111-111',
+ }),
+ })
+ .then(response => response.json())
+ .then(result => {
+ // console.log(result);
+ if (result.token) {
+ //localStorage.setItem('token', result.token);
+ alert('ํ์ํฉ๋๋ค!');
+ navigate('/main-han');
+ } else if (result.message === 'INVALID_USER') {
+ alert('ID์ PW๋ฅผ ํ์ธํด์ฃผ์ธ์.');
+ }
+ });
+ };
+
+ const isInputValid =
+ loginValues.id.includes('@') &&
+ loginValues.id.length >= 6 &&
+ loginValues.password.length >= 6;
+ // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6);
+ // console.log(loginValues.password.length >= 6);
+ // console.log(isInputValid);
+
+ return (
+ <div className="login">
+ <form className="loginBox">
+ <h1>Westagram</h1>
+ <input
+ id="id"
+ name="id"
+ className="userId"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={handleInputValue}
+ />
+ <input
+ id="password"
+ name="password"
+ className="userPassword"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={handleInputValue}
+ />
+ <button
+ type="button"
+ className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`}
+ onClick={goToMain}
+ disabled={!isInputValid}
+ //style={style}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div className="findPassword">
+ <a href="#">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </form>
+ </div>
+ );
}
export default Login; | JavaScript | ```suggestion
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import './Login.scss';
```
scss๋ฅผ ๋ฐ์ผ๋ก ๋ด๋ ค์ฃผ๋ฉด ์ข์๊ฑฐ๊ฐ๋ค์ |
@@ -1,7 +1,128 @@
+import { useNavigate } from 'react-router-dom';
+import { useState } from 'react';
import './Login.scss';
function Login() {
- return <></>;
+ // const [idState, setIdState] = useState('');
+ // const [passwordValue, setPasswordValue] = useState('');
+ // const [disabled, setDisabled] = useState(true);
+ // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' });
+
+ const navigate = useNavigate();
+ const [loginValues, setLoginValues] = useState({
+ id: '',
+ password: '',
+ });
+
+ const handleInputValue = e => {
+ const { name, value } = e.target;
+ setLoginValues({ ...loginValues, [name]: value });
+ };
+
+ // const { type, value } = event.target;
+
+ // function handleLogin(event) {
+ // if (type === 'text') {
+ // setIdState(value);
+ // } else if (type === 'password') {
+ // setPasswordValue(value);
+ // }
+ // handleButton();
+ // }
+
+ // const checkId = idValue => {
+ // return idValue.includes('@') ? true : false;
+ // };
+
+ // const checkPw = pwValue => {
+ // return pwValue.length >= 5 ? true : false;
+ // };
+
+ // const handleButton = () => {
+ // const isValidId = checkId(state);
+ // const isValidPw = checkPw(passwordValue);
+
+ // if (isValidId && isValidPw) {
+ // buttonColor(true);
+ // } else {
+ // buttonColor(false);
+ // }
+ // };
+
+ // const buttonColor = btnValid => {
+ // setDisabled(!btnValid);
+ // setStyle({
+ // opacity: btnValid ? 1 : 0.5,
+ // cursor: btnValid ? 'pointer' : 'default',
+ // });
+ // };
+
+ const goToMain = () => {
+ fetch('http://10.58.4.238:8000/users/login', {
+ method: 'POST',
+ body: JSON.stringify({
+ email: loginValues.id,
+ password: loginValues.password,
+ // name: '๋์',
+ // phone_number: '010-1111-111',
+ }),
+ })
+ .then(response => response.json())
+ .then(result => {
+ // console.log(result);
+ if (result.token) {
+ //localStorage.setItem('token', result.token);
+ alert('ํ์ํฉ๋๋ค!');
+ navigate('/main-han');
+ } else if (result.message === 'INVALID_USER') {
+ alert('ID์ PW๋ฅผ ํ์ธํด์ฃผ์ธ์.');
+ }
+ });
+ };
+
+ const isInputValid =
+ loginValues.id.includes('@') &&
+ loginValues.id.length >= 6 &&
+ loginValues.password.length >= 6;
+ // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6);
+ // console.log(loginValues.password.length >= 6);
+ // console.log(isInputValid);
+
+ return (
+ <div className="login">
+ <form className="loginBox">
+ <h1>Westagram</h1>
+ <input
+ id="id"
+ name="id"
+ className="userId"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={handleInputValue}
+ />
+ <input
+ id="password"
+ name="password"
+ className="userPassword"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={handleInputValue}
+ />
+ <button
+ type="button"
+ className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`}
+ onClick={goToMain}
+ disabled={!isInputValid}
+ //style={style}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div className="findPassword">
+ <a href="#">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </form>
+ </div>
+ );
}
export default Login; | JavaScript | ํ
๋ฐ์ผ๋ก ๋ถ์ฌ์ฃผ๋๊ฒ ์ข์ง ์์๊น์? |
@@ -1,8 +1,43 @@
-import './Main.scss';
+import { useState, useEffect } from 'react';
+import Nav from '../../../components/Nav/Nav';
+import Feed from './Feed';
+import MainRight from './MainRight';
import '../../../styles/variables.scss';
+import './Main.scss';
function Main() {
- return <></>;
+ const [articles, setArticles] = useState([]);
+
+ useEffect(() => {
+ fetch('http://localhost:3000/data/younghyunHan/feedData.json')
+ .then(res => res.json())
+ .then(data => {
+ setArticles(data);
+ });
+ }, []);
+
+ return (
+ <div className="main">
+ <Nav />
+ <main>
+ <div className="feeds">
+ {articles.map((content, index) => {
+ return (
+ <div key={index}>
+ <Feed
+ userName={content.userName}
+ feedImg={content.feedImg}
+ userMan={content.userMan}
+ profileLogo={content.profileLogo}
+ />
+ </div>
+ );
+ })}
+ </div>
+ <MainRight />
+ </main>
+ </div>
+ );
}
export default Main; | JavaScript | ์ปดํฌ๋ํธ ์ด๋ฆ์ Feed ๋ก ๋ฐ๊ฟ๋ณด๋ฉด ์ข์ ๊ฒ ๊ฐ์์!!
์ด๋ฆ์ ์๋ฏธ๋ฅผ ๋ ๋ด์์ฃผ๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค |
@@ -1,8 +1,43 @@
-import './Main.scss';
+import { useState, useEffect } from 'react';
+import Nav from '../../../components/Nav/Nav';
+import Feed from './Feed';
+import MainRight from './MainRight';
import '../../../styles/variables.scss';
+import './Main.scss';
function Main() {
- return <></>;
+ const [articles, setArticles] = useState([]);
+
+ useEffect(() => {
+ fetch('http://localhost:3000/data/younghyunHan/feedData.json')
+ .then(res => res.json())
+ .then(data => {
+ setArticles(data);
+ });
+ }, []);
+
+ return (
+ <div className="main">
+ <Nav />
+ <main>
+ <div className="feeds">
+ {articles.map((content, index) => {
+ return (
+ <div key={index}>
+ <Feed
+ userName={content.userName}
+ feedImg={content.feedImg}
+ userMan={content.userMan}
+ profileLogo={content.profileLogo}
+ />
+ </div>
+ );
+ })}
+ </div>
+ <MainRight />
+ </main>
+ </div>
+ );
}
export default Main; | JavaScript | mainRight๋ ์ปดํฌ๋ํธ๋ก ๋ง๋ค์ด์ฃผ๋ฉด ์ข์ ๊ฒ ๊ฐ์์
์ด๋ ๊ฒ ํด์ฃผ๋ฉด main.js ๋ด์ฉ, scss ๋ด์ฉ๋ ๋ ๊ฐ๋จํด์ง ๊ฒ ๊ฐ์!
```suggestion
<MainRight />
``` |
@@ -1,8 +1,43 @@
-import './Main.scss';
+import { useState, useEffect } from 'react';
+import Nav from '../../../components/Nav/Nav';
+import Feed from './Feed';
+import MainRight from './MainRight';
import '../../../styles/variables.scss';
+import './Main.scss';
function Main() {
- return <></>;
+ const [articles, setArticles] = useState([]);
+
+ useEffect(() => {
+ fetch('http://localhost:3000/data/younghyunHan/feedData.json')
+ .then(res => res.json())
+ .then(data => {
+ setArticles(data);
+ });
+ }, []);
+
+ return (
+ <div className="main">
+ <Nav />
+ <main>
+ <div className="feeds">
+ {articles.map((content, index) => {
+ return (
+ <div key={index}>
+ <Feed
+ userName={content.userName}
+ feedImg={content.feedImg}
+ userMan={content.userMan}
+ profileLogo={content.profileLogo}
+ />
+ </div>
+ );
+ })}
+ </div>
+ <MainRight />
+ </main>
+ </div>
+ );
}
export default Main; | JavaScript | ```suggestion
<Footer />
```
์ปดํฌ๋ํธ๋ก ๋ถ๋ฆฌํด์ฃผ๊ณ , footer ์๋ฉํฑ ํ๊ทธ๋ฅผ ์ฌ์ฉํด๋ณด๋ฉด ์ข์ ๋ฏ! |
@@ -1,8 +1,43 @@
-import './Main.scss';
+import { useState, useEffect } from 'react';
+import Nav from '../../../components/Nav/Nav';
+import Feed from './Feed';
+import MainRight from './MainRight';
import '../../../styles/variables.scss';
+import './Main.scss';
function Main() {
- return <></>;
+ const [articles, setArticles] = useState([]);
+
+ useEffect(() => {
+ fetch('http://localhost:3000/data/younghyunHan/feedData.json')
+ .then(res => res.json())
+ .then(data => {
+ setArticles(data);
+ });
+ }, []);
+
+ return (
+ <div className="main">
+ <Nav />
+ <main>
+ <div className="feeds">
+ {articles.map((content, index) => {
+ return (
+ <div key={index}>
+ <Feed
+ userName={content.userName}
+ feedImg={content.feedImg}
+ userMan={content.userMan}
+ profileLogo={content.profileLogo}
+ />
+ </div>
+ );
+ })}
+ </div>
+ <MainRight />
+ </main>
+ </div>
+ );
}
export default Main; | JavaScript | ๊ฐ ๋ฉ๋ด๋ฅผ JS ํ์ผ์ ์ ์ฅํ๊ณ ,
map ๋ฉ์๋๋ก ์ถ๋ ฅํด์ฃผ๋ ๋ฐฉ์์ผ๋ก ์์ ํด๋ณด๋ฉด ์ข์ ๋ฏํด์ฉ |
@@ -0,0 +1,16 @@
+.main {
+ background-color: #fafafa;
+
+ main {
+ display: flex;
+ justify-content: center;
+ align-items: flex-start;
+ margin: 0px 8px 8px 8px;
+
+ .feeds {
+ width: 750px;
+ padding-top: 80px;
+ padding-bottom: 30px;
+ }
+ }
+} | Unknown | ์ด๋ฐ ์ ํ์ ํ์ฉ์ผ๋ก ์คํฌ๋กค ๊ฐ์ถ์ ๋ถ๋ถ ์ข๋ค์.. |
@@ -1,8 +1,43 @@
-import './Main.scss';
+import { useState, useEffect } from 'react';
+import Nav from '../../../components/Nav/Nav';
+import Feed from './Feed';
+import MainRight from './MainRight';
import '../../../styles/variables.scss';
+import './Main.scss';
function Main() {
- return <></>;
+ const [articles, setArticles] = useState([]);
+
+ useEffect(() => {
+ fetch('http://localhost:3000/data/younghyunHan/feedData.json')
+ .then(res => res.json())
+ .then(data => {
+ setArticles(data);
+ });
+ }, []);
+
+ return (
+ <div className="main">
+ <Nav />
+ <main>
+ <div className="feeds">
+ {articles.map((content, index) => {
+ return (
+ <div key={index}>
+ <Feed
+ userName={content.userName}
+ feedImg={content.feedImg}
+ userMan={content.userMan}
+ profileLogo={content.profileLogo}
+ />
+ </div>
+ );
+ })}
+ </div>
+ <MainRight />
+ </main>
+ </div>
+ );
}
export default Main; | JavaScript | feedcontainer ์ feed |
@@ -1,7 +1,49 @@
import './Nav.scss';
+import '../../styles/variables.scss';
+import { Link } from 'react-router-dom';
function Nav() {
- return <></>;
+ return (
+ <div className="nav">
+ <nav className="navbar">
+ <div className="navbarLeft1">
+ <div className="navbarLeft1Inner">
+ <Link to="/" className="navbarItem logoImg">
+ <img alt="logoIcon" className="navIcon" src="/images/logo.png" />
+ </Link>
+ <Link to="/" className="navbarItem logoFont">
+ Westagram
+ </Link>
+ </div>
+ </div>
+ <div className="navbarLeft2">
+ <div className="searchWrapper navbarItem">
+ <img alt="searchIcon" src="/images/search.png" />
+ <input placeholder="๊ฒ์" />
+ </div>
+ </div>
+ <div className="navbarRight">
+ <Link to="/" className="navbarItem">
+ <img
+ alt="exploreIcon"
+ className="navIcon"
+ src="/images/explore.png"
+ />
+ </Link>
+ <Link to="/" className="navbarItem">
+ <img alt="heartIcon" className="navIcon" src="/images/heart.png" />
+ </Link>
+ <Link to="/" className="navbarItem">
+ <img
+ alt="profileIcon"
+ className="navIcon"
+ src="/images/profile.png"
+ />
+ </Link>
+ </div>
+ </nav>
+ </div>
+ );
}
export default Nav; | JavaScript | ๊ณตํต ํ์ผ |
@@ -1,7 +1,128 @@
+import { useNavigate } from 'react-router-dom';
+import { useState } from 'react';
import './Login.scss';
function Login() {
- return <></>;
+ // const [idState, setIdState] = useState('');
+ // const [passwordValue, setPasswordValue] = useState('');
+ // const [disabled, setDisabled] = useState(true);
+ // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' });
+
+ const navigate = useNavigate();
+ const [loginValues, setLoginValues] = useState({
+ id: '',
+ password: '',
+ });
+
+ const handleInputValue = e => {
+ const { name, value } = e.target;
+ setLoginValues({ ...loginValues, [name]: value });
+ };
+
+ // const { type, value } = event.target;
+
+ // function handleLogin(event) {
+ // if (type === 'text') {
+ // setIdState(value);
+ // } else if (type === 'password') {
+ // setPasswordValue(value);
+ // }
+ // handleButton();
+ // }
+
+ // const checkId = idValue => {
+ // return idValue.includes('@') ? true : false;
+ // };
+
+ // const checkPw = pwValue => {
+ // return pwValue.length >= 5 ? true : false;
+ // };
+
+ // const handleButton = () => {
+ // const isValidId = checkId(state);
+ // const isValidPw = checkPw(passwordValue);
+
+ // if (isValidId && isValidPw) {
+ // buttonColor(true);
+ // } else {
+ // buttonColor(false);
+ // }
+ // };
+
+ // const buttonColor = btnValid => {
+ // setDisabled(!btnValid);
+ // setStyle({
+ // opacity: btnValid ? 1 : 0.5,
+ // cursor: btnValid ? 'pointer' : 'default',
+ // });
+ // };
+
+ const goToMain = () => {
+ fetch('http://10.58.4.238:8000/users/login', {
+ method: 'POST',
+ body: JSON.stringify({
+ email: loginValues.id,
+ password: loginValues.password,
+ // name: '๋์',
+ // phone_number: '010-1111-111',
+ }),
+ })
+ .then(response => response.json())
+ .then(result => {
+ // console.log(result);
+ if (result.token) {
+ //localStorage.setItem('token', result.token);
+ alert('ํ์ํฉ๋๋ค!');
+ navigate('/main-han');
+ } else if (result.message === 'INVALID_USER') {
+ alert('ID์ PW๋ฅผ ํ์ธํด์ฃผ์ธ์.');
+ }
+ });
+ };
+
+ const isInputValid =
+ loginValues.id.includes('@') &&
+ loginValues.id.length >= 6 &&
+ loginValues.password.length >= 6;
+ // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6);
+ // console.log(loginValues.password.length >= 6);
+ // console.log(isInputValid);
+
+ return (
+ <div className="login">
+ <form className="loginBox">
+ <h1>Westagram</h1>
+ <input
+ id="id"
+ name="id"
+ className="userId"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={handleInputValue}
+ />
+ <input
+ id="password"
+ name="password"
+ className="userPassword"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={handleInputValue}
+ />
+ <button
+ type="button"
+ className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`}
+ onClick={goToMain}
+ disabled={!isInputValid}
+ //style={style}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div className="findPassword">
+ <a href="#">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </form>
+ </div>
+ );
}
export default Login; | JavaScript | state๋ผ๋ ๋ช
์นญ์ด ๋ฌด์จ ๋ฐ์ดํฐ๋ฅผ ๊ด๋ฆฌํ๋์ง ์ ์ ์์. ๋ช
ํํ ๋ช
์นญ์ผ๋ก ์์ |
@@ -1,7 +1,128 @@
+import { useNavigate } from 'react-router-dom';
+import { useState } from 'react';
import './Login.scss';
function Login() {
- return <></>;
+ // const [idState, setIdState] = useState('');
+ // const [passwordValue, setPasswordValue] = useState('');
+ // const [disabled, setDisabled] = useState(true);
+ // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' });
+
+ const navigate = useNavigate();
+ const [loginValues, setLoginValues] = useState({
+ id: '',
+ password: '',
+ });
+
+ const handleInputValue = e => {
+ const { name, value } = e.target;
+ setLoginValues({ ...loginValues, [name]: value });
+ };
+
+ // const { type, value } = event.target;
+
+ // function handleLogin(event) {
+ // if (type === 'text') {
+ // setIdState(value);
+ // } else if (type === 'password') {
+ // setPasswordValue(value);
+ // }
+ // handleButton();
+ // }
+
+ // const checkId = idValue => {
+ // return idValue.includes('@') ? true : false;
+ // };
+
+ // const checkPw = pwValue => {
+ // return pwValue.length >= 5 ? true : false;
+ // };
+
+ // const handleButton = () => {
+ // const isValidId = checkId(state);
+ // const isValidPw = checkPw(passwordValue);
+
+ // if (isValidId && isValidPw) {
+ // buttonColor(true);
+ // } else {
+ // buttonColor(false);
+ // }
+ // };
+
+ // const buttonColor = btnValid => {
+ // setDisabled(!btnValid);
+ // setStyle({
+ // opacity: btnValid ? 1 : 0.5,
+ // cursor: btnValid ? 'pointer' : 'default',
+ // });
+ // };
+
+ const goToMain = () => {
+ fetch('http://10.58.4.238:8000/users/login', {
+ method: 'POST',
+ body: JSON.stringify({
+ email: loginValues.id,
+ password: loginValues.password,
+ // name: '๋์',
+ // phone_number: '010-1111-111',
+ }),
+ })
+ .then(response => response.json())
+ .then(result => {
+ // console.log(result);
+ if (result.token) {
+ //localStorage.setItem('token', result.token);
+ alert('ํ์ํฉ๋๋ค!');
+ navigate('/main-han');
+ } else if (result.message === 'INVALID_USER') {
+ alert('ID์ PW๋ฅผ ํ์ธํด์ฃผ์ธ์.');
+ }
+ });
+ };
+
+ const isInputValid =
+ loginValues.id.includes('@') &&
+ loginValues.id.length >= 6 &&
+ loginValues.password.length >= 6;
+ // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6);
+ // console.log(loginValues.password.length >= 6);
+ // console.log(isInputValid);
+
+ return (
+ <div className="login">
+ <form className="loginBox">
+ <h1>Westagram</h1>
+ <input
+ id="id"
+ name="id"
+ className="userId"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={handleInputValue}
+ />
+ <input
+ id="password"
+ name="password"
+ className="userPassword"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={handleInputValue}
+ />
+ <button
+ type="button"
+ className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`}
+ onClick={goToMain}
+ disabled={!isInputValid}
+ //style={style}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div className="findPassword">
+ <a href="#">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </form>
+ </div>
+ );
}
export default Login; | JavaScript | disabled, style ๋ฑ์ state๋ก ๋ง๋ค ํ์ ์์.
[๋ฆฌ์กํธ๋ก ์ฌ๊ณ ํ๊ธฐ](https://ko.reactjs.org/docs/thinking-in-react.html) ์ฐธ๊ณ
1. ๋ถ๋ชจ๋ก๋ถํฐ props๋ฅผ ํตํด ์ ๋ฌ๋ฉ๋๊น? ๊ทธ๋ฌ๋ฉด ํ์คํ state๊ฐ ์๋๋๋ค.
2. ์๊ฐ์ด ์ง๋๋ ๋ณํ์ง ์๋์? ๊ทธ๋ฌ๋ฉด ํ์คํ state๊ฐ ์๋๋๋ค.
3. ์ปดํฌ๋ํธ ์์ ๋ค๋ฅธ state๋ props๋ฅผ ๊ฐ์ง๊ณ ๊ณ์ฐ ๊ฐ๋ฅํ๊ฐ์? ๊ทธ๋ ๋ค๋ฉด state๊ฐ ์๋๋๋ค. |
@@ -1,7 +1,128 @@
+import { useNavigate } from 'react-router-dom';
+import { useState } from 'react';
import './Login.scss';
function Login() {
- return <></>;
+ // const [idState, setIdState] = useState('');
+ // const [passwordValue, setPasswordValue] = useState('');
+ // const [disabled, setDisabled] = useState(true);
+ // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' });
+
+ const navigate = useNavigate();
+ const [loginValues, setLoginValues] = useState({
+ id: '',
+ password: '',
+ });
+
+ const handleInputValue = e => {
+ const { name, value } = e.target;
+ setLoginValues({ ...loginValues, [name]: value });
+ };
+
+ // const { type, value } = event.target;
+
+ // function handleLogin(event) {
+ // if (type === 'text') {
+ // setIdState(value);
+ // } else if (type === 'password') {
+ // setPasswordValue(value);
+ // }
+ // handleButton();
+ // }
+
+ // const checkId = idValue => {
+ // return idValue.includes('@') ? true : false;
+ // };
+
+ // const checkPw = pwValue => {
+ // return pwValue.length >= 5 ? true : false;
+ // };
+
+ // const handleButton = () => {
+ // const isValidId = checkId(state);
+ // const isValidPw = checkPw(passwordValue);
+
+ // if (isValidId && isValidPw) {
+ // buttonColor(true);
+ // } else {
+ // buttonColor(false);
+ // }
+ // };
+
+ // const buttonColor = btnValid => {
+ // setDisabled(!btnValid);
+ // setStyle({
+ // opacity: btnValid ? 1 : 0.5,
+ // cursor: btnValid ? 'pointer' : 'default',
+ // });
+ // };
+
+ const goToMain = () => {
+ fetch('http://10.58.4.238:8000/users/login', {
+ method: 'POST',
+ body: JSON.stringify({
+ email: loginValues.id,
+ password: loginValues.password,
+ // name: '๋์',
+ // phone_number: '010-1111-111',
+ }),
+ })
+ .then(response => response.json())
+ .then(result => {
+ // console.log(result);
+ if (result.token) {
+ //localStorage.setItem('token', result.token);
+ alert('ํ์ํฉ๋๋ค!');
+ navigate('/main-han');
+ } else if (result.message === 'INVALID_USER') {
+ alert('ID์ PW๋ฅผ ํ์ธํด์ฃผ์ธ์.');
+ }
+ });
+ };
+
+ const isInputValid =
+ loginValues.id.includes('@') &&
+ loginValues.id.length >= 6 &&
+ loginValues.password.length >= 6;
+ // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6);
+ // console.log(loginValues.password.length >= 6);
+ // console.log(isInputValid);
+
+ return (
+ <div className="login">
+ <form className="loginBox">
+ <h1>Westagram</h1>
+ <input
+ id="id"
+ name="id"
+ className="userId"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={handleInputValue}
+ />
+ <input
+ id="password"
+ name="password"
+ className="userPassword"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={handleInputValue}
+ />
+ <button
+ type="button"
+ className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`}
+ onClick={goToMain}
+ disabled={!isInputValid}
+ //style={style}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div className="findPassword">
+ <a href="#">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </form>
+ </div>
+ );
}
export default Login; | JavaScript | - ๊ธฐ๋ฅ์ ํจ์๋ก ๋ถ๋ฆฌํ๋ ๋ถ๋ถ์ ์ข์
- ์ผํญ์ฐ์ฐ์๋ก ์ฌ์ฉํ ํ์ ์์ด, ์กฐ๊ฑด ์์ฒด๋ก boolean์ด ๋ ์ ์์
```suggestion
const checkId = idValue => {
return idValue.includes('@');
};
const checkPw = pwValue => {
return pwValue.length >= 5;
};
```
- ์ถ๊ฐ์ ์ผ๋ก,
```js
const isInputValid = idValue.includes('@') && pwValue.length >= 5
```
์ด๋ฐ ์์ผ๋ก ํ๊บผ๋ฒ์ ๋ณ์๋ก ๋ง๋ค์ด ์ฒ๋ฆฌํ ์๋ ์์ |
@@ -1,7 +1,128 @@
+import { useNavigate } from 'react-router-dom';
+import { useState } from 'react';
import './Login.scss';
function Login() {
- return <></>;
+ // const [idState, setIdState] = useState('');
+ // const [passwordValue, setPasswordValue] = useState('');
+ // const [disabled, setDisabled] = useState(true);
+ // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' });
+
+ const navigate = useNavigate();
+ const [loginValues, setLoginValues] = useState({
+ id: '',
+ password: '',
+ });
+
+ const handleInputValue = e => {
+ const { name, value } = e.target;
+ setLoginValues({ ...loginValues, [name]: value });
+ };
+
+ // const { type, value } = event.target;
+
+ // function handleLogin(event) {
+ // if (type === 'text') {
+ // setIdState(value);
+ // } else if (type === 'password') {
+ // setPasswordValue(value);
+ // }
+ // handleButton();
+ // }
+
+ // const checkId = idValue => {
+ // return idValue.includes('@') ? true : false;
+ // };
+
+ // const checkPw = pwValue => {
+ // return pwValue.length >= 5 ? true : false;
+ // };
+
+ // const handleButton = () => {
+ // const isValidId = checkId(state);
+ // const isValidPw = checkPw(passwordValue);
+
+ // if (isValidId && isValidPw) {
+ // buttonColor(true);
+ // } else {
+ // buttonColor(false);
+ // }
+ // };
+
+ // const buttonColor = btnValid => {
+ // setDisabled(!btnValid);
+ // setStyle({
+ // opacity: btnValid ? 1 : 0.5,
+ // cursor: btnValid ? 'pointer' : 'default',
+ // });
+ // };
+
+ const goToMain = () => {
+ fetch('http://10.58.4.238:8000/users/login', {
+ method: 'POST',
+ body: JSON.stringify({
+ email: loginValues.id,
+ password: loginValues.password,
+ // name: '๋์',
+ // phone_number: '010-1111-111',
+ }),
+ })
+ .then(response => response.json())
+ .then(result => {
+ // console.log(result);
+ if (result.token) {
+ //localStorage.setItem('token', result.token);
+ alert('ํ์ํฉ๋๋ค!');
+ navigate('/main-han');
+ } else if (result.message === 'INVALID_USER') {
+ alert('ID์ PW๋ฅผ ํ์ธํด์ฃผ์ธ์.');
+ }
+ });
+ };
+
+ const isInputValid =
+ loginValues.id.includes('@') &&
+ loginValues.id.length >= 6 &&
+ loginValues.password.length >= 6;
+ // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6);
+ // console.log(loginValues.password.length >= 6);
+ // console.log(isInputValid);
+
+ return (
+ <div className="login">
+ <form className="loginBox">
+ <h1>Westagram</h1>
+ <input
+ id="id"
+ name="id"
+ className="userId"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={handleInputValue}
+ />
+ <input
+ id="password"
+ name="password"
+ className="userPassword"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={handleInputValue}
+ />
+ <button
+ type="button"
+ className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`}
+ onClick={goToMain}
+ disabled={!isInputValid}
+ //style={style}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div className="findPassword">
+ <a href="#">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </form>
+ </div>
+ );
}
export default Login; | JavaScript | ๋ช
์นญ๋ง ๋ดค์ ๋๋ id ๋ถ๋ถ๋ง ๊ด๋ฆฌํ๋ ํจ์์ธ ๊ฒ ๊ฐ์๋ฐ, ๋์์ ๋ณด๋ฉด ์๋. ์์ |
@@ -1,7 +1,128 @@
+import { useNavigate } from 'react-router-dom';
+import { useState } from 'react';
import './Login.scss';
function Login() {
- return <></>;
+ // const [idState, setIdState] = useState('');
+ // const [passwordValue, setPasswordValue] = useState('');
+ // const [disabled, setDisabled] = useState(true);
+ // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' });
+
+ const navigate = useNavigate();
+ const [loginValues, setLoginValues] = useState({
+ id: '',
+ password: '',
+ });
+
+ const handleInputValue = e => {
+ const { name, value } = e.target;
+ setLoginValues({ ...loginValues, [name]: value });
+ };
+
+ // const { type, value } = event.target;
+
+ // function handleLogin(event) {
+ // if (type === 'text') {
+ // setIdState(value);
+ // } else if (type === 'password') {
+ // setPasswordValue(value);
+ // }
+ // handleButton();
+ // }
+
+ // const checkId = idValue => {
+ // return idValue.includes('@') ? true : false;
+ // };
+
+ // const checkPw = pwValue => {
+ // return pwValue.length >= 5 ? true : false;
+ // };
+
+ // const handleButton = () => {
+ // const isValidId = checkId(state);
+ // const isValidPw = checkPw(passwordValue);
+
+ // if (isValidId && isValidPw) {
+ // buttonColor(true);
+ // } else {
+ // buttonColor(false);
+ // }
+ // };
+
+ // const buttonColor = btnValid => {
+ // setDisabled(!btnValid);
+ // setStyle({
+ // opacity: btnValid ? 1 : 0.5,
+ // cursor: btnValid ? 'pointer' : 'default',
+ // });
+ // };
+
+ const goToMain = () => {
+ fetch('http://10.58.4.238:8000/users/login', {
+ method: 'POST',
+ body: JSON.stringify({
+ email: loginValues.id,
+ password: loginValues.password,
+ // name: '๋์',
+ // phone_number: '010-1111-111',
+ }),
+ })
+ .then(response => response.json())
+ .then(result => {
+ // console.log(result);
+ if (result.token) {
+ //localStorage.setItem('token', result.token);
+ alert('ํ์ํฉ๋๋ค!');
+ navigate('/main-han');
+ } else if (result.message === 'INVALID_USER') {
+ alert('ID์ PW๋ฅผ ํ์ธํด์ฃผ์ธ์.');
+ }
+ });
+ };
+
+ const isInputValid =
+ loginValues.id.includes('@') &&
+ loginValues.id.length >= 6 &&
+ loginValues.password.length >= 6;
+ // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6);
+ // console.log(loginValues.password.length >= 6);
+ // console.log(isInputValid);
+
+ return (
+ <div className="login">
+ <form className="loginBox">
+ <h1>Westagram</h1>
+ <input
+ id="id"
+ name="id"
+ className="userId"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={handleInputValue}
+ />
+ <input
+ id="password"
+ name="password"
+ className="userPassword"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={handleInputValue}
+ />
+ <button
+ type="button"
+ className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`}
+ onClick={goToMain}
+ disabled={!isInputValid}
+ //style={style}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div className="findPassword">
+ <a href="#">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </form>
+ </div>
+ );
}
export default Login; | JavaScript | ๊ตฌ์กฐ๋ถํดํ ๋น!
```suggestion
const { type, value } = event.target;
if (type === 'text') {
setState(value);
} else if (type === 'password') {
setPasswordValue(value);
}
``` |
@@ -1,7 +1,128 @@
+import { useNavigate } from 'react-router-dom';
+import { useState } from 'react';
import './Login.scss';
function Login() {
- return <></>;
+ // const [idState, setIdState] = useState('');
+ // const [passwordValue, setPasswordValue] = useState('');
+ // const [disabled, setDisabled] = useState(true);
+ // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' });
+
+ const navigate = useNavigate();
+ const [loginValues, setLoginValues] = useState({
+ id: '',
+ password: '',
+ });
+
+ const handleInputValue = e => {
+ const { name, value } = e.target;
+ setLoginValues({ ...loginValues, [name]: value });
+ };
+
+ // const { type, value } = event.target;
+
+ // function handleLogin(event) {
+ // if (type === 'text') {
+ // setIdState(value);
+ // } else if (type === 'password') {
+ // setPasswordValue(value);
+ // }
+ // handleButton();
+ // }
+
+ // const checkId = idValue => {
+ // return idValue.includes('@') ? true : false;
+ // };
+
+ // const checkPw = pwValue => {
+ // return pwValue.length >= 5 ? true : false;
+ // };
+
+ // const handleButton = () => {
+ // const isValidId = checkId(state);
+ // const isValidPw = checkPw(passwordValue);
+
+ // if (isValidId && isValidPw) {
+ // buttonColor(true);
+ // } else {
+ // buttonColor(false);
+ // }
+ // };
+
+ // const buttonColor = btnValid => {
+ // setDisabled(!btnValid);
+ // setStyle({
+ // opacity: btnValid ? 1 : 0.5,
+ // cursor: btnValid ? 'pointer' : 'default',
+ // });
+ // };
+
+ const goToMain = () => {
+ fetch('http://10.58.4.238:8000/users/login', {
+ method: 'POST',
+ body: JSON.stringify({
+ email: loginValues.id,
+ password: loginValues.password,
+ // name: '๋์',
+ // phone_number: '010-1111-111',
+ }),
+ })
+ .then(response => response.json())
+ .then(result => {
+ // console.log(result);
+ if (result.token) {
+ //localStorage.setItem('token', result.token);
+ alert('ํ์ํฉ๋๋ค!');
+ navigate('/main-han');
+ } else if (result.message === 'INVALID_USER') {
+ alert('ID์ PW๋ฅผ ํ์ธํด์ฃผ์ธ์.');
+ }
+ });
+ };
+
+ const isInputValid =
+ loginValues.id.includes('@') &&
+ loginValues.id.length >= 6 &&
+ loginValues.password.length >= 6;
+ // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6);
+ // console.log(loginValues.password.length >= 6);
+ // console.log(isInputValid);
+
+ return (
+ <div className="login">
+ <form className="loginBox">
+ <h1>Westagram</h1>
+ <input
+ id="id"
+ name="id"
+ className="userId"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={handleInputValue}
+ />
+ <input
+ id="password"
+ name="password"
+ className="userPassword"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={handleInputValue}
+ />
+ <button
+ type="button"
+ className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`}
+ onClick={goToMain}
+ disabled={!isInputValid}
+ //style={style}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div className="findPassword">
+ <a href="#">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </form>
+ </div>
+ );
}
export default Login; | JavaScript | JS๋ก ๊ตฌํํ๋ ๋ฐฉ์ ๊ทธ๋๋ก ํ์
จ๋๋ฐ, ๊ธฐ์กด state๋ก ๊ณ์ฐ์ด ๊ฐ๋ฅํ๊ธฐ ๋๋ฌธ์ ๋ถํ์ํ state |
@@ -1,7 +1,128 @@
+import { useNavigate } from 'react-router-dom';
+import { useState } from 'react';
import './Login.scss';
function Login() {
- return <></>;
+ // const [idState, setIdState] = useState('');
+ // const [passwordValue, setPasswordValue] = useState('');
+ // const [disabled, setDisabled] = useState(true);
+ // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' });
+
+ const navigate = useNavigate();
+ const [loginValues, setLoginValues] = useState({
+ id: '',
+ password: '',
+ });
+
+ const handleInputValue = e => {
+ const { name, value } = e.target;
+ setLoginValues({ ...loginValues, [name]: value });
+ };
+
+ // const { type, value } = event.target;
+
+ // function handleLogin(event) {
+ // if (type === 'text') {
+ // setIdState(value);
+ // } else if (type === 'password') {
+ // setPasswordValue(value);
+ // }
+ // handleButton();
+ // }
+
+ // const checkId = idValue => {
+ // return idValue.includes('@') ? true : false;
+ // };
+
+ // const checkPw = pwValue => {
+ // return pwValue.length >= 5 ? true : false;
+ // };
+
+ // const handleButton = () => {
+ // const isValidId = checkId(state);
+ // const isValidPw = checkPw(passwordValue);
+
+ // if (isValidId && isValidPw) {
+ // buttonColor(true);
+ // } else {
+ // buttonColor(false);
+ // }
+ // };
+
+ // const buttonColor = btnValid => {
+ // setDisabled(!btnValid);
+ // setStyle({
+ // opacity: btnValid ? 1 : 0.5,
+ // cursor: btnValid ? 'pointer' : 'default',
+ // });
+ // };
+
+ const goToMain = () => {
+ fetch('http://10.58.4.238:8000/users/login', {
+ method: 'POST',
+ body: JSON.stringify({
+ email: loginValues.id,
+ password: loginValues.password,
+ // name: '๋์',
+ // phone_number: '010-1111-111',
+ }),
+ })
+ .then(response => response.json())
+ .then(result => {
+ // console.log(result);
+ if (result.token) {
+ //localStorage.setItem('token', result.token);
+ alert('ํ์ํฉ๋๋ค!');
+ navigate('/main-han');
+ } else if (result.message === 'INVALID_USER') {
+ alert('ID์ PW๋ฅผ ํ์ธํด์ฃผ์ธ์.');
+ }
+ });
+ };
+
+ const isInputValid =
+ loginValues.id.includes('@') &&
+ loginValues.id.length >= 6 &&
+ loginValues.password.length >= 6;
+ // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6);
+ // console.log(loginValues.password.length >= 6);
+ // console.log(isInputValid);
+
+ return (
+ <div className="login">
+ <form className="loginBox">
+ <h1>Westagram</h1>
+ <input
+ id="id"
+ name="id"
+ className="userId"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={handleInputValue}
+ />
+ <input
+ id="password"
+ name="password"
+ className="userPassword"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={handleInputValue}
+ />
+ <button
+ type="button"
+ className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`}
+ onClick={goToMain}
+ disabled={!isInputValid}
+ //style={style}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div className="findPassword">
+ <a href="#">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </form>
+ </div>
+ );
}
export default Login; | JavaScript | ๊นํ์ง ๋ฉํ ๋ ๋ฆฌ๋ทฐ ๋ฐ์ํ๊ธฐ |
@@ -1,7 +1,128 @@
+import { useNavigate } from 'react-router-dom';
+import { useState } from 'react';
import './Login.scss';
function Login() {
- return <></>;
+ // const [idState, setIdState] = useState('');
+ // const [passwordValue, setPasswordValue] = useState('');
+ // const [disabled, setDisabled] = useState(true);
+ // const [style, setStyle] = useState({ opacity: 0.5, cursor: 'default' });
+
+ const navigate = useNavigate();
+ const [loginValues, setLoginValues] = useState({
+ id: '',
+ password: '',
+ });
+
+ const handleInputValue = e => {
+ const { name, value } = e.target;
+ setLoginValues({ ...loginValues, [name]: value });
+ };
+
+ // const { type, value } = event.target;
+
+ // function handleLogin(event) {
+ // if (type === 'text') {
+ // setIdState(value);
+ // } else if (type === 'password') {
+ // setPasswordValue(value);
+ // }
+ // handleButton();
+ // }
+
+ // const checkId = idValue => {
+ // return idValue.includes('@') ? true : false;
+ // };
+
+ // const checkPw = pwValue => {
+ // return pwValue.length >= 5 ? true : false;
+ // };
+
+ // const handleButton = () => {
+ // const isValidId = checkId(state);
+ // const isValidPw = checkPw(passwordValue);
+
+ // if (isValidId && isValidPw) {
+ // buttonColor(true);
+ // } else {
+ // buttonColor(false);
+ // }
+ // };
+
+ // const buttonColor = btnValid => {
+ // setDisabled(!btnValid);
+ // setStyle({
+ // opacity: btnValid ? 1 : 0.5,
+ // cursor: btnValid ? 'pointer' : 'default',
+ // });
+ // };
+
+ const goToMain = () => {
+ fetch('http://10.58.4.238:8000/users/login', {
+ method: 'POST',
+ body: JSON.stringify({
+ email: loginValues.id,
+ password: loginValues.password,
+ // name: '๋์',
+ // phone_number: '010-1111-111',
+ }),
+ })
+ .then(response => response.json())
+ .then(result => {
+ // console.log(result);
+ if (result.token) {
+ //localStorage.setItem('token', result.token);
+ alert('ํ์ํฉ๋๋ค!');
+ navigate('/main-han');
+ } else if (result.message === 'INVALID_USER') {
+ alert('ID์ PW๋ฅผ ํ์ธํด์ฃผ์ธ์.');
+ }
+ });
+ };
+
+ const isInputValid =
+ loginValues.id.includes('@') &&
+ loginValues.id.length >= 6 &&
+ loginValues.password.length >= 6;
+ // console.log(loginValues.id.includes('@') && loginValues.id.length >= 6);
+ // console.log(loginValues.password.length >= 6);
+ // console.log(isInputValid);
+
+ return (
+ <div className="login">
+ <form className="loginBox">
+ <h1>Westagram</h1>
+ <input
+ id="id"
+ name="id"
+ className="userId"
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ onChange={handleInputValue}
+ />
+ <input
+ id="password"
+ name="password"
+ className="userPassword"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ onChange={handleInputValue}
+ />
+ <button
+ type="button"
+ className={`loginButton ${isInputValid ? 'loginBtnLive' : ''}`}
+ onClick={goToMain}
+ disabled={!isInputValid}
+ //style={style}
+ >
+ ๋ก๊ทธ์ธ
+ </button>
+ <div className="findPassword">
+ <a href="#">๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</a>
+ </div>
+ </form>
+ </div>
+ );
}
export default Login; | JavaScript | +์ผํญ์ฐ์ฐ์์ ์กฐ๊ฑด์ ์ ๋ฆฌ๋ทฐ์ฒ๋ผ ๋ณ์๋ก ๋ง๋ค์ด์ ์ฌ์ฉํ๊ธฐ |
@@ -0,0 +1,14 @@
+import './Comment.scss';
+
+function Comment({ userName, content }) {
+ return (
+ <div className="comment">
+ <p>
+ <strong className="commentMan">{userName}</strong>
+ {content}
+ </p>
+ </div>
+ );
+}
+
+export default Comment; | JavaScript | ๋งค๊ฐ๋ณ์ ์๋ฆฌ์์ ๊ตฌ์กฐ๋ถํดํ ๋น ๊ตณ |
@@ -0,0 +1,102 @@
+import { useState, useEffect } from 'react';
+import './Feed.scss';
+import Comment from './Comment';
+
+function Feed(props) {
+ const [comment, setComment] = useState('');
+ const [addCommentList, setAddCommentList] = useState([]);
+ const [cmtContList, setCmtContList] = useState([]);
+ const userName = 'test01';
+
+ const onChange = event => {
+ setComment(event.target.value);
+ };
+
+ const addComment = event => {
+ event.preventDefault();
+ setAddCommentList([
+ ...addCommentList,
+ {
+ name: userName,
+ content: comment,
+ },
+ ]);
+ setComment('');
+ };
+
+ useEffect(() => {
+ fetch('http://localhost:3000/data/younghyunHan/commentData.json')
+ .then(res => res.json())
+ .then(data => {
+ setCmtContList(data);
+ });
+ }, []);
+
+ return (
+ <article className="feed">
+ <div className="feedTop">
+ <div className="feedTopOne">
+ <div className="profileLogo">
+ <img className="profileLogoImg" src={props.profileLogo} />
+ </div>
+ <div className="profileName">
+ <div className="profileNameOne">{props.userName}</div>
+ <span className="profileNameTwo">Wecode - ์์ฝ๋</span>
+ </div>
+ </div>
+ <i className="fas fa-ellipsis-h" />
+ </div>
+ <img alt="ํผ๋ ์ด๋ฏธ์ง" className="feedImg" src={props.feedImg} />
+ <div className="feedThree">
+ <div>
+ <i className="far fa-heart" />
+ <i className="far fa-comment" />
+ <i className="fas fa-upload" />
+ </div>
+ <i className="far fa-bookmark" />
+ </div>
+ <div className="feedFour">
+ <img alt="์ข์์ ๋๋ฅธ ์ฌ๋" className="man" src={props.userMan} />
+ <span className="feedFourWord">seungyoun_iain</span>
+ ์ธ
+ <span className="feedFourWordTwo">4๋ช
</span>์ด ์ข์ํฉ๋๋ค.
+ </div>
+ <div className="feedFive">
+ <span className="feedFiveWord">wecode_bootcamp</span>"์์ฝ๋๋ ๋จ์
+ ๊ต์ก์
์ฒด๊ฐ ์๋ ๊ฐ๋ฐ์ ์ปค๋ฎค๋ํฐ์
๋๋ค. Wecode์์ ๋ฐฐ์ฐ๊ณ ์ ๋ ์ด 5๊ฐ
+ ํ์ฌ์์ ์คํผ๋ฅผ ๋ฐ์์ต๋๋ค.
+ </div>
+ <div className="comment">
+ {cmtContList.map(content => {
+ return (
+ <Comment
+ key={content.id}
+ userName={content.userName}
+ content={content.content}
+ />
+ );
+ })}
+ {addCommentList.map((content, index) => {
+ return (
+ <div key={index}>
+ <Comment content={content.content} userName={content.name} />
+ </div>
+ );
+ })}
+ </div>
+ <span className="postTime">54๋ถ ์ </span>
+ <form className="commentSection" onSubmit={addComment}>
+ <input
+ type="text"
+ placeholder="๋๊ธ ๋ฌ๊ธฐ..."
+ className="comment"
+ onChange={onChange}
+ value={comment}
+ />
+ <button className="postButton">๊ฒ์</button>
+ </form>
+ </article>
+ );
+}
+
+export default Feed; | JavaScript | - ์ฌํ ๋น๋์ง ์๋ ๋ณ์๋ const๋ก ์ ์ธํ๊ธฐ
- ์ด ๋ถ๋ถ์ ๋ณ์ ์ ์ธ๋ณด๋จ ๊ตฌ์กฐ๋ถํดํ ๋น ์ ์ฉํ๊ธฐ |
@@ -0,0 +1,102 @@
+import { useState, useEffect } from 'react';
+import './Feed.scss';
+import Comment from './Comment';
+
+function Feed(props) {
+ const [comment, setComment] = useState('');
+ const [addCommentList, setAddCommentList] = useState([]);
+ const [cmtContList, setCmtContList] = useState([]);
+ const userName = 'test01';
+
+ const onChange = event => {
+ setComment(event.target.value);
+ };
+
+ const addComment = event => {
+ event.preventDefault();
+ setAddCommentList([
+ ...addCommentList,
+ {
+ name: userName,
+ content: comment,
+ },
+ ]);
+ setComment('');
+ };
+
+ useEffect(() => {
+ fetch('http://localhost:3000/data/younghyunHan/commentData.json')
+ .then(res => res.json())
+ .then(data => {
+ setCmtContList(data);
+ });
+ }, []);
+
+ return (
+ <article className="feed">
+ <div className="feedTop">
+ <div className="feedTopOne">
+ <div className="profileLogo">
+ <img className="profileLogoImg" src={props.profileLogo} />
+ </div>
+ <div className="profileName">
+ <div className="profileNameOne">{props.userName}</div>
+ <span className="profileNameTwo">Wecode - ์์ฝ๋</span>
+ </div>
+ </div>
+ <i className="fas fa-ellipsis-h" />
+ </div>
+ <img alt="ํผ๋ ์ด๋ฏธ์ง" className="feedImg" src={props.feedImg} />
+ <div className="feedThree">
+ <div>
+ <i className="far fa-heart" />
+ <i className="far fa-comment" />
+ <i className="fas fa-upload" />
+ </div>
+ <i className="far fa-bookmark" />
+ </div>
+ <div className="feedFour">
+ <img alt="์ข์์ ๋๋ฅธ ์ฌ๋" className="man" src={props.userMan} />
+ <span className="feedFourWord">seungyoun_iain</span>
+ ์ธ
+ <span className="feedFourWordTwo">4๋ช
</span>์ด ์ข์ํฉ๋๋ค.
+ </div>
+ <div className="feedFive">
+ <span className="feedFiveWord">wecode_bootcamp</span>"์์ฝ๋๋ ๋จ์
+ ๊ต์ก์
์ฒด๊ฐ ์๋ ๊ฐ๋ฐ์ ์ปค๋ฎค๋ํฐ์
๋๋ค. Wecode์์ ๋ฐฐ์ฐ๊ณ ์ ๋ ์ด 5๊ฐ
+ ํ์ฌ์์ ์คํผ๋ฅผ ๋ฐ์์ต๋๋ค.
+ </div>
+ <div className="comment">
+ {cmtContList.map(content => {
+ return (
+ <Comment
+ key={content.id}
+ userName={content.userName}
+ content={content.content}
+ />
+ );
+ })}
+ {addCommentList.map((content, index) => {
+ return (
+ <div key={index}>
+ <Comment content={content.content} userName={content.name} />
+ </div>
+ );
+ })}
+ </div>
+ <span className="postTime">54๋ถ ์ </span>
+ <form className="commentSection" onSubmit={addComment}>
+ <input
+ type="text"
+ placeholder="๋๊ธ ๋ฌ๊ธฐ..."
+ className="comment"
+ onChange={onChange}
+ value={comment}
+ />
+ <button className="postButton">๊ฒ์</button>
+ </form>
+ </article>
+ );
+}
+
+export default Feed; | JavaScript | - input์ value๊ฐ ๋ค์ด์ค๋ ๋ถ๋ถ์ธ๋ฐ, ์ด๊ธฐ๊ฐ์ด string์ด ์๋ ๋ฐฐ์ด์ด ๋ค์ด์์
- cmtContents๋ผ๋ ๋ณ์๋ช
๊ณผ ๋ฐฐ์ด์ธ ์ด๊ธฐ๊ฐ์ ์กฐํฉ์ด ๋ฐฐ์ด ๋ฐ์ดํฐ๋ฅผ ์ฐ์์ํด
- ๋ช
ํํ์ง๋ง ๊ฐ๊ฒฐํ state๋ช
์ผ๋ก ์์ . ex) `comment` / `commentList` |
@@ -0,0 +1,102 @@
+import { useState, useEffect } from 'react';
+import './Feed.scss';
+import Comment from './Comment';
+
+function Feed(props) {
+ const [comment, setComment] = useState('');
+ const [addCommentList, setAddCommentList] = useState([]);
+ const [cmtContList, setCmtContList] = useState([]);
+ const userName = 'test01';
+
+ const onChange = event => {
+ setComment(event.target.value);
+ };
+
+ const addComment = event => {
+ event.preventDefault();
+ setAddCommentList([
+ ...addCommentList,
+ {
+ name: userName,
+ content: comment,
+ },
+ ]);
+ setComment('');
+ };
+
+ useEffect(() => {
+ fetch('http://localhost:3000/data/younghyunHan/commentData.json')
+ .then(res => res.json())
+ .then(data => {
+ setCmtContList(data);
+ });
+ }, []);
+
+ return (
+ <article className="feed">
+ <div className="feedTop">
+ <div className="feedTopOne">
+ <div className="profileLogo">
+ <img className="profileLogoImg" src={props.profileLogo} />
+ </div>
+ <div className="profileName">
+ <div className="profileNameOne">{props.userName}</div>
+ <span className="profileNameTwo">Wecode - ์์ฝ๋</span>
+ </div>
+ </div>
+ <i className="fas fa-ellipsis-h" />
+ </div>
+ <img alt="ํผ๋ ์ด๋ฏธ์ง" className="feedImg" src={props.feedImg} />
+ <div className="feedThree">
+ <div>
+ <i className="far fa-heart" />
+ <i className="far fa-comment" />
+ <i className="fas fa-upload" />
+ </div>
+ <i className="far fa-bookmark" />
+ </div>
+ <div className="feedFour">
+ <img alt="์ข์์ ๋๋ฅธ ์ฌ๋" className="man" src={props.userMan} />
+ <span className="feedFourWord">seungyoun_iain</span>
+ ์ธ
+ <span className="feedFourWordTwo">4๋ช
</span>์ด ์ข์ํฉ๋๋ค.
+ </div>
+ <div className="feedFive">
+ <span className="feedFiveWord">wecode_bootcamp</span>"์์ฝ๋๋ ๋จ์
+ ๊ต์ก์
์ฒด๊ฐ ์๋ ๊ฐ๋ฐ์ ์ปค๋ฎค๋ํฐ์
๋๋ค. Wecode์์ ๋ฐฐ์ฐ๊ณ ์ ๋ ์ด 5๊ฐ
+ ํ์ฌ์์ ์คํผ๋ฅผ ๋ฐ์์ต๋๋ค.
+ </div>
+ <div className="comment">
+ {cmtContList.map(content => {
+ return (
+ <Comment
+ key={content.id}
+ userName={content.userName}
+ content={content.content}
+ />
+ );
+ })}
+ {addCommentList.map((content, index) => {
+ return (
+ <div key={index}>
+ <Comment content={content.content} userName={content.name} />
+ </div>
+ );
+ })}
+ </div>
+ <span className="postTime">54๋ถ ์ </span>
+ <form className="commentSection" onSubmit={addComment}>
+ <input
+ type="text"
+ placeholder="๋๊ธ ๋ฌ๊ธฐ..."
+ className="comment"
+ onChange={onChange}
+ value={comment}
+ />
+ <button className="postButton">๊ฒ์</button>
+ </form>
+ </article>
+ );
+}
+
+export default Feed; | JavaScript | ํจ์๋ช
์์ !
- comment๋ฅผ ์ถ๊ฐํ๋ ์ญํ ์ ํ๋ ํจ์
- ์ํฐํค๋ฅผ ์ณค์ ๋ ์ ํจ์๋ฅผ ์คํ์ํค๋ ํจ์
๋ก ๋ถํ ํ๋ฉด ์ข์ ๋ฏ |
@@ -0,0 +1,102 @@
+import { useState, useEffect } from 'react';
+import './Feed.scss';
+import Comment from './Comment';
+
+function Feed(props) {
+ const [comment, setComment] = useState('');
+ const [addCommentList, setAddCommentList] = useState([]);
+ const [cmtContList, setCmtContList] = useState([]);
+ const userName = 'test01';
+
+ const onChange = event => {
+ setComment(event.target.value);
+ };
+
+ const addComment = event => {
+ event.preventDefault();
+ setAddCommentList([
+ ...addCommentList,
+ {
+ name: userName,
+ content: comment,
+ },
+ ]);
+ setComment('');
+ };
+
+ useEffect(() => {
+ fetch('http://localhost:3000/data/younghyunHan/commentData.json')
+ .then(res => res.json())
+ .then(data => {
+ setCmtContList(data);
+ });
+ }, []);
+
+ return (
+ <article className="feed">
+ <div className="feedTop">
+ <div className="feedTopOne">
+ <div className="profileLogo">
+ <img className="profileLogoImg" src={props.profileLogo} />
+ </div>
+ <div className="profileName">
+ <div className="profileNameOne">{props.userName}</div>
+ <span className="profileNameTwo">Wecode - ์์ฝ๋</span>
+ </div>
+ </div>
+ <i className="fas fa-ellipsis-h" />
+ </div>
+ <img alt="ํผ๋ ์ด๋ฏธ์ง" className="feedImg" src={props.feedImg} />
+ <div className="feedThree">
+ <div>
+ <i className="far fa-heart" />
+ <i className="far fa-comment" />
+ <i className="fas fa-upload" />
+ </div>
+ <i className="far fa-bookmark" />
+ </div>
+ <div className="feedFour">
+ <img alt="์ข์์ ๋๋ฅธ ์ฌ๋" className="man" src={props.userMan} />
+ <span className="feedFourWord">seungyoun_iain</span>
+ ์ธ
+ <span className="feedFourWordTwo">4๋ช
</span>์ด ์ข์ํฉ๋๋ค.
+ </div>
+ <div className="feedFive">
+ <span className="feedFiveWord">wecode_bootcamp</span>"์์ฝ๋๋ ๋จ์
+ ๊ต์ก์
์ฒด๊ฐ ์๋ ๊ฐ๋ฐ์ ์ปค๋ฎค๋ํฐ์
๋๋ค. Wecode์์ ๋ฐฐ์ฐ๊ณ ์ ๋ ์ด 5๊ฐ
+ ํ์ฌ์์ ์คํผ๋ฅผ ๋ฐ์์ต๋๋ค.
+ </div>
+ <div className="comment">
+ {cmtContList.map(content => {
+ return (
+ <Comment
+ key={content.id}
+ userName={content.userName}
+ content={content.content}
+ />
+ );
+ })}
+ {addCommentList.map((content, index) => {
+ return (
+ <div key={index}>
+ <Comment content={content.content} userName={content.name} />
+ </div>
+ );
+ })}
+ </div>
+ <span className="postTime">54๋ถ ์ </span>
+ <form className="commentSection" onSubmit={addComment}>
+ <input
+ type="text"
+ placeholder="๋๊ธ ๋ฌ๊ธฐ..."
+ className="comment"
+ onChange={onChange}
+ value={comment}
+ />
+ <button className="postButton">๊ฒ์</button>
+ </form>
+ </article>
+ );
+}
+
+export default Feed; | JavaScript | ๋์ผํ ์คํ์ผ์ ๊ฐ์ง๋ ๋ถ๋ถ์ธ๋ฐ, one two three ์ด๋ฐ ์์ผ๋ก ๋ํ๋ผ ํ์ ์์ด ๋ด์ฉ์ ํฌ๊ดํ๋ ๋ช
์นญ์ ๋์ผํ className์ผ๋ก ์ฌ์ฉ |
@@ -0,0 +1,132 @@
+.feed {
+ background-color: white;
+ margin-bottom: 50px;
+
+ .feedTop {
+ display: flex;
+ justify-content: space-between;
+ position: relative;
+ padding: 10px;
+
+ .feedTopOne {
+ display: flex;
+ align-items: center;
+
+ .profileLogo {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ height: 35px;
+ width: 35px;
+ margin-right: 10px;
+ color: white;
+ background-color: black;
+ border-radius: 50%;
+ font-size: 7px;
+ font-weight: bold;
+ overflow: hidden; // ๋ถ๋ชจ div๋งํผ ์ด๋ฏธ์ง ์๋ฆ
+
+ .profileLogoImg {
+ width: 100%;
+ height: 100%;
+ object-fit: cover; // ๊ฐ๋ก, ์ธ๋ก ๋น์จ์ด ์ ๋ง์ผ๋ฉด ๋ฑ ๋ง๊ฒ ์ ์ฐ๊ทธ๋ฌ์ง๊ฒ ๋ง์ถฐ์ค.
+ }
+ }
+
+ .profileNameOne {
+ margin-bottom: 0px;
+ font-size: 15px;
+ font-weight: bold;
+ }
+
+ .profileNameTwo {
+ color: #a3a49a;
+ font-size: 12px;
+ font-weight: bold;
+ }
+ }
+
+ .fa-ellipsis-h {
+ position: absolute;
+ right: 20px;
+ top: 20px;
+ }
+ }
+
+ .feedImg {
+ width: 100%;
+ height: 500px;
+ }
+
+ .feedThree {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: 10px;
+ font-size: 25px;
+
+ .fa-heart,
+ .fa-comment {
+ margin-right: 10px;
+ }
+ }
+
+ .feedFour {
+ display: flex;
+ align-items: center;
+ padding: 0px 10px 10px 10px;
+
+ .man {
+ width: 20px;
+ height: 20px;
+ margin-right: 10px;
+ border-radius: 50%;
+ } // ์ ์ฝ๋ ์ฒ๋ผ ํ๋ ค๋ฉด div๋ก ์ด๋ฏธ์ง ํ๋ฒ ๋ ๊ฐ์จ์ ๊ทธ div์ overflow:hidden ์ฃผ๊ณ
+ // imgํ์ผ์ width: 100%, height: 100%, object-fit: cover์ฃผ๋ฉด ๋จ
+
+ .feedFourWord,
+ .feedFourWordTwo {
+ font-weight: bold;
+ }
+ }
+
+ .feedFive {
+ padding: 0px 10px 3px 10px;
+
+ .feedFiveWord {
+ font-weight: bold;
+ }
+ }
+
+ .comment {
+ padding-top: 5px;
+ padding-left: 5px;
+ padding-bottom: 5px;
+ }
+
+ .postTime {
+ display: inline-block;
+ padding: 10px 10px 15px 10px;
+ color: #9c9c9c;
+ }
+
+ .commentSection {
+ position: relative;
+
+ .comment {
+ width: 100%;
+ padding: 15px 10px;
+ border: 1px solid #f3f3f3;
+ }
+
+ .postButton {
+ position: absolute;
+ bottom: 13px;
+ right: 20px;
+ color: #c5e1fc;
+ background-color: white;
+ border: 1px solid white;
+ font-size: 15px;
+ }
+ }
+} | Unknown | - article ํ๊ทธ๊ฐ ์๋๋ผ feed๋ผ๋ className์ผ๋ก nestingํ๊ธฐ
- ์ต์์ div๋ฅผ article๋ก ๋ฐ๊พธ๊ณ 1 depth ์ค์ด๋ฉด ๋ ๋ฏ |
@@ -6,13 +6,14 @@ import ReviewContent from "./ReviewContent";
import ArrowDown from "@/assets/images/icons/arrow_down.svg";
import MenuCircle from "@/assets/images/icons/menu-circle.svg";
import Dropdown from "@/components/common/Dropdown";
+import useReviewModals from "@/hooks/review/useReviewModals";
import { type ReviewInfoProps } from "@/types/review";
import { type RatingStyle } from "@/types/review";
export default function Review({ reviewInfo }: ReviewInfoProps) {
const router = useRouter();
+ const { handleDeleteClick } = useReviewModals();
const [isOpen, setIsOpen] = useState(false);
-
const reviewTextStyle: RatingStyle = {
0: "text-purple-200",
1: "text-blue-200",
@@ -37,7 +38,7 @@ export default function Review({ reviewInfo }: ReviewInfoProps) {
};
const handleClickDelete = () => {
- alert("๋ฆฌ๋ทฐ ์ญ์ ์
๋๋ค.");
+ handleDeleteClick(reviewInfo.reviewId);
};
const handleClickDetail = (e: React.MouseEvent<HTMLButtonElement>) => {
@@ -48,8 +49,7 @@ export default function Review({ reviewInfo }: ReviewInfoProps) {
return (
<div
className='rounded-[12px] bg-gray-900 p-4'
- onClick={handleClickReview}
- aria-label={"routeMeet"}
+ onClick={reviewInfo.isMyReview ? handleClickReview : undefined}
>
<div className='relative'>
<div className='flex justify-between'> | Unknown | @ITHPARK ๋ฆฌ๋ทฐ ์ญ์ api ์ฐ๊ฒฐํ๋ฉด์ ํด๋น ์ปดํฌ๋ํธ ์ผ๋ถ ์์ ๋์์ต๋๋ค! |
@@ -11,6 +11,8 @@ export interface ReviewInfo {
isMyWritten?: boolean;
eventId?: number;
eventType?: string;
+ reviewId: number;
+ editable?: boolean;
}
export interface ReviewInfoProps { | TypeScript | ๋ฆฌ๋ทฐ ํ์
์ `reviewId`, `editable` ์ถ๊ฐํ์ต๋๋ค |
@@ -0,0 +1,109 @@
+package chess.domain.board;
+
+import chess.domain.command.MoveOptions;
+import chess.domain.piece.Color;
+import chess.domain.piece.Piece;
+import chess.domain.player.Player;
+import chess.domain.player.Position;
+
+import java.util.Collection;
+
+public class Board {
+ private final Player white;
+ private final Player black;
+
+ public Board() {
+ this.white = new Player(Color.WHITE);
+ this.black = new Player(Color.BLACK);
+ }
+
+ public void move(final MoveOptions moveOptions, final boolean isWhiteTurn) {
+ Player player = currentPlayer(isWhiteTurn);
+ Player enemy = currentPlayer(!isWhiteTurn);
+ Position source = moveOptions.getSource();
+ Position target = moveOptions.getTarget();
+
+ validate(player, enemy, source, target);
+
+ enemy.removePieceOn(target);
+ movePiece(player, source, target);
+ }
+
+ private Player currentPlayer(final boolean isWhiteTurn) {
+ if (isWhiteTurn) {
+ return white;
+ }
+ return black;
+ }
+
+ private void validate(final Player player, final Player enemy, final Position source, final Position target) {
+ validateSourceOwner(enemy, source);
+ validateSamePosition(source, target);
+ validateTarget(player, target);
+ validateKingMovable(player, enemy, source, target);
+ }
+
+ private void validateSourceOwner(final Player enemy, final Position source) {
+ if (enemy.hasPieceOn(source)) {
+ throw new IllegalArgumentException("์์ ์ ๊ธฐ๋ฌผ๋ง ์์ง์ผ ์ ์์ต๋๋ค.");
+ }
+ }
+
+ private void validateSamePosition(final Position source, final Position target) {
+ if (source.equals(target)) {
+ throw new IllegalArgumentException("์ถ๋ฐ ์์น์ ๋์ฐฉ ์์น๊ฐ ๊ฐ์ ์ ์์ต๋๋ค.");
+ }
+ }
+
+ private void validateTarget(final Player player, final Position target) {
+ if (player.hasPieceOn(target)) {
+ throw new IllegalArgumentException("๊ฐ์ ์์์ ๊ธฐ๋ฌผ์ ๊ณต๊ฒฉํ ์ ์์ต๋๋ค.");
+ }
+ }
+
+ private void validateKingMovable(final Player player, final Player enemy, final Position source, final Position target) {
+ if (player.hasKingOn(source) && enemy.canAttack(target)) {
+ throw new IllegalArgumentException("ํน์ ์๋๋ฐฉ์ด ๊ณต๊ฒฉ ๊ฐ๋ฅํ ์์น๋ก ์ด๋ํ ์ ์์ต๋๋ค.");
+ }
+ }
+
+ private void movePiece(final Player player, final Position source, final Position target) {
+ Collection<Position> paths = player.findPaths(source, target);
+ validatePathsEmpty(paths);
+ player.update(source, target);
+ }
+
+ private void validatePathsEmpty(final Collection<Position> paths) {
+ boolean isWhiteBlocked = paths.stream()
+ .anyMatch(white::hasPieceOn);
+ boolean isBlackBlocked = paths.stream()
+ .anyMatch(black::hasPieceOn);
+
+ if (isWhiteBlocked || isBlackBlocked) {
+ throw new IllegalArgumentException("๊ธฐ๋ฌผ์ ํต๊ณผํ์ฌ ์ด๋ํ ์ ์์ต๋๋ค.");
+ }
+ }
+
+ public Piece findBy(final Position position) {
+ if (white.hasPieceOn(position)) {
+ return white.findPieceBy(position);
+ }
+
+ return black.findPieceBy(position);
+ }
+
+ public boolean isEmpty(final Position position) {
+ return !white.hasPieceOn(position) && !black.hasPieceOn(position);
+ }
+
+ public Status getStatus() {
+ double whiteScore = white.sumScores();
+ double blackScore = black.sumScores();
+
+ return new Status(whiteScore, blackScore, white.isKingDead(), black.isKingDead());
+ }
+
+ public boolean isEnd() {
+ return white.isKingDead() || black.isKingDead();
+ }
+} | Java | ์ ์ ๊ณ์ฐ์ ๋ํ ๋ช
๋ น์ด(`status`) ์ ์ฉ์ด ์๋์ด ์๋ ๊ฒ ๊ฐ์์! :) |
@@ -0,0 +1,58 @@
+package chess.domain.command;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+
+public enum Command {
+
+ START("start"),
+ END("end"),
+ MOVE("move"),
+ STATUS("status");
+
+ private static final Map<String, Command> COMMANDS = createCommands();
+
+ private static Map<String, Command> createCommands() {
+ Map<String, Command> commands = new HashMap<>();
+
+ Arrays.stream(values())
+ .forEach(command -> commands.put(command.command, command));
+
+ return commands;
+ }
+
+ private final String command;
+
+ Command(final String command) {
+ this.command = command;
+ }
+
+ public static Command of(final String command) {
+ Command foundCommand = COMMANDS.get(command);
+
+ if (foundCommand == null) {
+ throw new IllegalArgumentException("์ ํจํ์ง ์์ ๋ช
๋ น์ด์
๋๋ค.");
+ }
+
+ return foundCommand;
+ }
+
+ public void validateInitialCommand() {
+ if (isStatus() || isMove()) {
+ throw new IllegalArgumentException(String.format("%s ๋๋ %s๋ฅผ ์
๋ ฅํด์ฃผ์ธ์.", START.command, END.command));
+ }
+ }
+
+ public boolean isEnd() {
+ return this.equals(END);
+ }
+
+ public boolean isMove() {
+ return this.equals(MOVE);
+ }
+
+ public boolean isStatus() {
+ return this.equals(STATUS);
+ }
+} | Java | Command๋ Enum์ผ๋ก ๊ด๋ฆฌํด๋ณด๋ฉด ์ด๋จ๊น์? :) |
@@ -0,0 +1,127 @@
+package chess.domain.player;
+
+import chess.domain.board.File;
+import chess.domain.piece.Color;
+import chess.domain.piece.Piece;
+import chess.domain.piece.PieceFactory;
+import chess.domain.piece.PieceResolver;
+
+import java.util.Collection;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+public class Player {
+
+ private final Map<Position, Piece> pieces;
+ private final AttackRange attackRange;
+
+ public Player(final Color color) {
+ pieces = new HashMap<>(PieceFactory.createPieces(color));
+ attackRange = new AttackRange(pieces);
+ }
+
+ public double sumScores() {
+ double pawnScores = calculatePawnScores();
+ double scoresExceptPawn = calculateScoresExceptPawn();
+
+ return pawnScores + scoresExceptPawn;
+ }
+
+ private double calculatePawnScores() {
+ List<Position> pawnPositions = findPawnPositions();
+ Map<File, Integer> pawnCountsOnSameFile = extractPawnCountsOnSameFile(pawnPositions);
+
+ return pawnCountsOnSameFile.values()
+ .stream()
+ .mapToDouble(PieceResolver::sumPawnScores)
+ .sum();
+ }
+
+ private List<Position> findPawnPositions() {
+ return pieces.keySet()
+ .stream()
+ .filter(position -> {
+ Piece piece = pieces.get(position);
+ return piece.isPawn();
+ })
+ .collect(Collectors.toList());
+ }
+
+ private Map<File, Integer> extractPawnCountsOnSameFile(final List<Position> pawnPositions) {
+ Map<File, Integer> pawnCountOnSameFile = new EnumMap<>(File.class);
+
+ pawnPositions.stream()
+ .map(Position::getFile)
+ .forEach(file -> pawnCountOnSameFile.put(file, pawnCountOnSameFile.getOrDefault(file, 0) + 1));
+
+ return pawnCountOnSameFile;
+ }
+
+ private double calculateScoresExceptPawn() {
+ return pieces.values()
+ .stream()
+ .filter(Piece::isNotPawn)
+ .mapToDouble(PieceResolver::findScoreBy)
+ .sum();
+ }
+
+ public Collection<Position> findPaths(final Position source, final Position target) {
+ Piece sourcePiece = findPieceBy(source);
+
+ return sourcePiece.findPath(source, target);
+ }
+
+ public Piece findPieceBy(final Position position) {
+ if (isEmptyOn(position)) {
+ throw new IllegalArgumentException("ํด๋น ์์น์ ๊ธฐ๋ฌผ์ด ์กด์ฌํ์ง ์์ต๋๋ค.");
+ }
+
+ return pieces.get(position);
+ }
+
+ private boolean isEmptyOn(final Position position) {
+ return !pieces.containsKey(position);
+ }
+
+ public void update(final Position source, final Position target) {
+ Piece sourcePiece = findPieceBy(source);
+ movePiece(source, target, sourcePiece);
+ attackRange.update(source, target, sourcePiece);
+ }
+
+ private void movePiece(final Position source, final Position target, final Piece sourcePiece) {
+ pieces.put(target, sourcePiece);
+ pieces.remove(source);
+ }
+
+ public boolean hasKingOn(final Position position) {
+ Piece piece = findPieceBy(position);
+
+ return piece.isKing();
+ }
+
+ public boolean isKingDead() {
+ return pieces.values().stream()
+ .noneMatch(Piece::isKing);
+ }
+
+ public boolean canAttack(final Position position) {
+ return attackRange.contains(position);
+ }
+
+ public void removePieceOn(final Position position) {
+ if (isEmptyOn(position)) {
+ return;
+ }
+
+ attackRange.remove(position, pieces.get(position));
+ pieces.remove(position);
+ }
+
+ public boolean hasPieceOn(final Position position) {
+ return pieces.containsKey(position);
+ }
+} | Java | ์ ๋ ๋ถ์ ์ฐ์ฐ์(`!`)๋ฅผ ์ฌ๋งํ๋ฉด ํผํ๋๋ฐ์ ใ
ใ
๊ฐ๋
์ฑ์ ๋ฌธ์ ๋ ์๊ณ , ์ฝ๋ ์ฌ๋์ด ํ๋ฒ ๋ ํด์์ ํด์ผํ๊ธฐ ๋๋ฌธ์ ๋ฉ์๋๋ฅผ ์ ๊ณตํ๋ ์ชฝ์์ ํ๋ฒ ๋ ์ถ์ํ์ํค๋ฉด ์ข์ ๊ฒ ๊ฐ์์ ใ
ใ
`piece.isNotPawn()` |
@@ -0,0 +1,127 @@
+package chess.domain.player;
+
+import chess.domain.board.File;
+import chess.domain.piece.Color;
+import chess.domain.piece.Piece;
+import chess.domain.piece.PieceFactory;
+import chess.domain.piece.PieceResolver;
+
+import java.util.Collection;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+public class Player {
+
+ private final Map<Position, Piece> pieces;
+ private final AttackRange attackRange;
+
+ public Player(final Color color) {
+ pieces = new HashMap<>(PieceFactory.createPieces(color));
+ attackRange = new AttackRange(pieces);
+ }
+
+ public double sumScores() {
+ double pawnScores = calculatePawnScores();
+ double scoresExceptPawn = calculateScoresExceptPawn();
+
+ return pawnScores + scoresExceptPawn;
+ }
+
+ private double calculatePawnScores() {
+ List<Position> pawnPositions = findPawnPositions();
+ Map<File, Integer> pawnCountsOnSameFile = extractPawnCountsOnSameFile(pawnPositions);
+
+ return pawnCountsOnSameFile.values()
+ .stream()
+ .mapToDouble(PieceResolver::sumPawnScores)
+ .sum();
+ }
+
+ private List<Position> findPawnPositions() {
+ return pieces.keySet()
+ .stream()
+ .filter(position -> {
+ Piece piece = pieces.get(position);
+ return piece.isPawn();
+ })
+ .collect(Collectors.toList());
+ }
+
+ private Map<File, Integer> extractPawnCountsOnSameFile(final List<Position> pawnPositions) {
+ Map<File, Integer> pawnCountOnSameFile = new EnumMap<>(File.class);
+
+ pawnPositions.stream()
+ .map(Position::getFile)
+ .forEach(file -> pawnCountOnSameFile.put(file, pawnCountOnSameFile.getOrDefault(file, 0) + 1));
+
+ return pawnCountOnSameFile;
+ }
+
+ private double calculateScoresExceptPawn() {
+ return pieces.values()
+ .stream()
+ .filter(Piece::isNotPawn)
+ .mapToDouble(PieceResolver::findScoreBy)
+ .sum();
+ }
+
+ public Collection<Position> findPaths(final Position source, final Position target) {
+ Piece sourcePiece = findPieceBy(source);
+
+ return sourcePiece.findPath(source, target);
+ }
+
+ public Piece findPieceBy(final Position position) {
+ if (isEmptyOn(position)) {
+ throw new IllegalArgumentException("ํด๋น ์์น์ ๊ธฐ๋ฌผ์ด ์กด์ฌํ์ง ์์ต๋๋ค.");
+ }
+
+ return pieces.get(position);
+ }
+
+ private boolean isEmptyOn(final Position position) {
+ return !pieces.containsKey(position);
+ }
+
+ public void update(final Position source, final Position target) {
+ Piece sourcePiece = findPieceBy(source);
+ movePiece(source, target, sourcePiece);
+ attackRange.update(source, target, sourcePiece);
+ }
+
+ private void movePiece(final Position source, final Position target, final Piece sourcePiece) {
+ pieces.put(target, sourcePiece);
+ pieces.remove(source);
+ }
+
+ public boolean hasKingOn(final Position position) {
+ Piece piece = findPieceBy(position);
+
+ return piece.isKing();
+ }
+
+ public boolean isKingDead() {
+ return pieces.values().stream()
+ .noneMatch(Piece::isKing);
+ }
+
+ public boolean canAttack(final Position position) {
+ return attackRange.contains(position);
+ }
+
+ public void removePieceOn(final Position position) {
+ if (isEmptyOn(position)) {
+ return;
+ }
+
+ attackRange.remove(position, pieces.get(position));
+ pieces.remove(position);
+ }
+
+ public boolean hasPieceOn(final Position position) {
+ return pieces.containsKey(position);
+ }
+} | Java | ์์๋ ๋ถ์ ์ฐ์ฐ์ ํผ๋๋ฐฑ์ ๋จ๊ฒผ๋๋ฐ์, ์ฌ๊ธฐ๋ ํ๋ฒ๋ ์ถ์ํ์ํค๋ฉด ์ข์ ๊ฒ ๊ฐ์์ ใ
ใ
์ ์ฒด์ ์ผ๋ก ํ๋ฒ ๋ ์ฒดํฌํด๋ด๋ ์ข๊ฒ ๋ค์ :) |
@@ -0,0 +1,109 @@
+package chess.domain.board;
+
+import chess.domain.command.MoveOptions;
+import chess.domain.piece.Color;
+import chess.domain.piece.Piece;
+import chess.domain.player.Player;
+import chess.domain.player.Position;
+
+import java.util.Collection;
+
+public class Board {
+ private final Player white;
+ private final Player black;
+
+ public Board() {
+ this.white = new Player(Color.WHITE);
+ this.black = new Player(Color.BLACK);
+ }
+
+ public void move(final MoveOptions moveOptions, final boolean isWhiteTurn) {
+ Player player = currentPlayer(isWhiteTurn);
+ Player enemy = currentPlayer(!isWhiteTurn);
+ Position source = moveOptions.getSource();
+ Position target = moveOptions.getTarget();
+
+ validate(player, enemy, source, target);
+
+ enemy.removePieceOn(target);
+ movePiece(player, source, target);
+ }
+
+ private Player currentPlayer(final boolean isWhiteTurn) {
+ if (isWhiteTurn) {
+ return white;
+ }
+ return black;
+ }
+
+ private void validate(final Player player, final Player enemy, final Position source, final Position target) {
+ validateSourceOwner(enemy, source);
+ validateSamePosition(source, target);
+ validateTarget(player, target);
+ validateKingMovable(player, enemy, source, target);
+ }
+
+ private void validateSourceOwner(final Player enemy, final Position source) {
+ if (enemy.hasPieceOn(source)) {
+ throw new IllegalArgumentException("์์ ์ ๊ธฐ๋ฌผ๋ง ์์ง์ผ ์ ์์ต๋๋ค.");
+ }
+ }
+
+ private void validateSamePosition(final Position source, final Position target) {
+ if (source.equals(target)) {
+ throw new IllegalArgumentException("์ถ๋ฐ ์์น์ ๋์ฐฉ ์์น๊ฐ ๊ฐ์ ์ ์์ต๋๋ค.");
+ }
+ }
+
+ private void validateTarget(final Player player, final Position target) {
+ if (player.hasPieceOn(target)) {
+ throw new IllegalArgumentException("๊ฐ์ ์์์ ๊ธฐ๋ฌผ์ ๊ณต๊ฒฉํ ์ ์์ต๋๋ค.");
+ }
+ }
+
+ private void validateKingMovable(final Player player, final Player enemy, final Position source, final Position target) {
+ if (player.hasKingOn(source) && enemy.canAttack(target)) {
+ throw new IllegalArgumentException("ํน์ ์๋๋ฐฉ์ด ๊ณต๊ฒฉ ๊ฐ๋ฅํ ์์น๋ก ์ด๋ํ ์ ์์ต๋๋ค.");
+ }
+ }
+
+ private void movePiece(final Player player, final Position source, final Position target) {
+ Collection<Position> paths = player.findPaths(source, target);
+ validatePathsEmpty(paths);
+ player.update(source, target);
+ }
+
+ private void validatePathsEmpty(final Collection<Position> paths) {
+ boolean isWhiteBlocked = paths.stream()
+ .anyMatch(white::hasPieceOn);
+ boolean isBlackBlocked = paths.stream()
+ .anyMatch(black::hasPieceOn);
+
+ if (isWhiteBlocked || isBlackBlocked) {
+ throw new IllegalArgumentException("๊ธฐ๋ฌผ์ ํต๊ณผํ์ฌ ์ด๋ํ ์ ์์ต๋๋ค.");
+ }
+ }
+
+ public Piece findBy(final Position position) {
+ if (white.hasPieceOn(position)) {
+ return white.findPieceBy(position);
+ }
+
+ return black.findPieceBy(position);
+ }
+
+ public boolean isEmpty(final Position position) {
+ return !white.hasPieceOn(position) && !black.hasPieceOn(position);
+ }
+
+ public Status getStatus() {
+ double whiteScore = white.sumScores();
+ double blackScore = black.sumScores();
+
+ return new Status(whiteScore, blackScore, white.isKingDead(), black.isKingDead());
+ }
+
+ public boolean isEnd() {
+ return white.isKingDead() || black.isKingDead();
+ }
+} | Java | ์.. ํ์ด๋ถ repo์์ pullํ๊ณ ํธ์๋ฅผ ์ํ์๋ค์ ์ฃ์กํฉ๋๋คใ
ใ
๋ฐ์ํ์์ต๋๋ค! |
@@ -0,0 +1,127 @@
+package chess.domain.player;
+
+import chess.domain.board.File;
+import chess.domain.piece.Color;
+import chess.domain.piece.Piece;
+import chess.domain.piece.PieceFactory;
+import chess.domain.piece.PieceResolver;
+
+import java.util.Collection;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+public class Player {
+
+ private final Map<Position, Piece> pieces;
+ private final AttackRange attackRange;
+
+ public Player(final Color color) {
+ pieces = new HashMap<>(PieceFactory.createPieces(color));
+ attackRange = new AttackRange(pieces);
+ }
+
+ public double sumScores() {
+ double pawnScores = calculatePawnScores();
+ double scoresExceptPawn = calculateScoresExceptPawn();
+
+ return pawnScores + scoresExceptPawn;
+ }
+
+ private double calculatePawnScores() {
+ List<Position> pawnPositions = findPawnPositions();
+ Map<File, Integer> pawnCountsOnSameFile = extractPawnCountsOnSameFile(pawnPositions);
+
+ return pawnCountsOnSameFile.values()
+ .stream()
+ .mapToDouble(PieceResolver::sumPawnScores)
+ .sum();
+ }
+
+ private List<Position> findPawnPositions() {
+ return pieces.keySet()
+ .stream()
+ .filter(position -> {
+ Piece piece = pieces.get(position);
+ return piece.isPawn();
+ })
+ .collect(Collectors.toList());
+ }
+
+ private Map<File, Integer> extractPawnCountsOnSameFile(final List<Position> pawnPositions) {
+ Map<File, Integer> pawnCountOnSameFile = new EnumMap<>(File.class);
+
+ pawnPositions.stream()
+ .map(Position::getFile)
+ .forEach(file -> pawnCountOnSameFile.put(file, pawnCountOnSameFile.getOrDefault(file, 0) + 1));
+
+ return pawnCountOnSameFile;
+ }
+
+ private double calculateScoresExceptPawn() {
+ return pieces.values()
+ .stream()
+ .filter(Piece::isNotPawn)
+ .mapToDouble(PieceResolver::findScoreBy)
+ .sum();
+ }
+
+ public Collection<Position> findPaths(final Position source, final Position target) {
+ Piece sourcePiece = findPieceBy(source);
+
+ return sourcePiece.findPath(source, target);
+ }
+
+ public Piece findPieceBy(final Position position) {
+ if (isEmptyOn(position)) {
+ throw new IllegalArgumentException("ํด๋น ์์น์ ๊ธฐ๋ฌผ์ด ์กด์ฌํ์ง ์์ต๋๋ค.");
+ }
+
+ return pieces.get(position);
+ }
+
+ private boolean isEmptyOn(final Position position) {
+ return !pieces.containsKey(position);
+ }
+
+ public void update(final Position source, final Position target) {
+ Piece sourcePiece = findPieceBy(source);
+ movePiece(source, target, sourcePiece);
+ attackRange.update(source, target, sourcePiece);
+ }
+
+ private void movePiece(final Position source, final Position target, final Piece sourcePiece) {
+ pieces.put(target, sourcePiece);
+ pieces.remove(source);
+ }
+
+ public boolean hasKingOn(final Position position) {
+ Piece piece = findPieceBy(position);
+
+ return piece.isKing();
+ }
+
+ public boolean isKingDead() {
+ return pieces.values().stream()
+ .noneMatch(Piece::isKing);
+ }
+
+ public boolean canAttack(final Position position) {
+ return attackRange.contains(position);
+ }
+
+ public void removePieceOn(final Position position) {
+ if (isEmptyOn(position)) {
+ return;
+ }
+
+ attackRange.remove(position, pieces.get(position));
+ pieces.remove(position);
+ }
+
+ public boolean hasPieceOn(final Position position) {
+ return pieces.containsKey(position);
+ }
+} | Java | ๋ต๋ต! ํด๋น ํผ๋๋ฐฑ ์ฝ์ ํ ๋ถ์ ์ฐ์ฐ์ ์ฌ์ฉํ๋ ๊ณณ ๋ชจ๋ ์์ ํด์ฃผ์์ต๋๋ค :) |
@@ -0,0 +1,58 @@
+package chess.domain.command;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+
+public enum Command {
+
+ START("start"),
+ END("end"),
+ MOVE("move"),
+ STATUS("status");
+
+ private static final Map<String, Command> COMMANDS = createCommands();
+
+ private static Map<String, Command> createCommands() {
+ Map<String, Command> commands = new HashMap<>();
+
+ Arrays.stream(values())
+ .forEach(command -> commands.put(command.command, command));
+
+ return commands;
+ }
+
+ private final String command;
+
+ Command(final String command) {
+ this.command = command;
+ }
+
+ public static Command of(final String command) {
+ Command foundCommand = COMMANDS.get(command);
+
+ if (foundCommand == null) {
+ throw new IllegalArgumentException("์ ํจํ์ง ์์ ๋ช
๋ น์ด์
๋๋ค.");
+ }
+
+ return foundCommand;
+ }
+
+ public void validateInitialCommand() {
+ if (isStatus() || isMove()) {
+ throw new IllegalArgumentException(String.format("%s ๋๋ %s๋ฅผ ์
๋ ฅํด์ฃผ์ธ์.", START.command, END.command));
+ }
+ }
+
+ public boolean isEnd() {
+ return this.equals(END);
+ }
+
+ public boolean isMove() {
+ return this.equals(MOVE);
+ }
+
+ public boolean isStatus() {
+ return this.equals(STATUS);
+ }
+} | Java | ์์๋ค์ด๊ธฐ ๋๋ฌธ์ Enum์ผ๋ก ๊ด๋ฆฌํ๋ ํธ์ด ๋ ์ข๊ฒ ๋ค์!
Enum ๊ฐ์ฒด๋ก ์์ ํ์์ต๋๋ค :) |
@@ -0,0 +1,93 @@
+const context = describe;
+
+describe('์ํ๋ชฉ๋ก API ํ
์คํธ', () => {
+ context('์ธ๊ธฐ ์ํ๋ชฉ๋ก 1ํ์ด์ง๋ฅผ ์กฐํํ๋ฉด', () => {
+ it('20๊ฐ์ ๋ชฉ๋ก์ ๋ฐํํ๋ค.', () => {
+ const baseUrl = 'https://api.themoviedb.org/3/movie/popular';
+ const param = new URLSearchParams({
+ api_key: Cypress.env('API_KEY'),
+ language: 'ko-KR',
+ page: 1,
+ });
+
+ cy.request('GET', `${baseUrl}?${param}`).as('popularMovies');
+
+ cy.get('@popularMovies').its('status').should('eq', 200);
+ cy.get('@popularMovies').its('body.results').should('have.length', 20);
+ });
+ });
+});
+
+describe('์ํ๋ชฉ๋ก e2e ํ
์คํธ', () => {
+ beforeEach(() => {
+ const baseUrl = 'https://api.themoviedb.org/3/movie/popular';
+ const param = new URLSearchParams({
+ api_key: Cypress.env('API_KEY'),
+ language: 'ko-KR',
+ page: 1,
+ });
+
+ cy.intercept(
+ {
+ method: 'GET',
+ url: `${baseUrl}?${param}`,
+ },
+ { fixture: 'movie-popular.json' }
+ ).as('popularMovies');
+
+ cy.visit('http://localhost:8080');
+ });
+
+ context('์ํ ๋ชฉ๋ก ์กฐํ ์', () => {
+ it('800ms ๋์ Skeleton UI๊ฐ ๋
ธ์ถ๋์๋ค๊ฐ ์ฌ๋ผ์ง๋ค.', () => {
+ cy.wait('@popularMovies');
+ cy.get('.skeleton').should('have.length', 60);
+ cy.wait(800);
+ cy.get('.skeleton').should('have.length', 0);
+ });
+ });
+
+ context('ํ์ด์ง ์ง์
์ ์ธ๊ธฐ์ํ ๋ชฉ๋ก 1ํ์ด์ง๋ฅผ ์กฐํํ๋ฉด', () => {
+ it('20๊ฐ์ .item-card๊ฐ ๋
ธ์ถ๋๋ค.', () => {
+ cy.get('.item-card').should('have.length', 20);
+ });
+ });
+
+ context('๋๋ณด๊ธฐ ๋ฒํผ์ ํด๋ฆญํ๋ฉด', () => {
+ it('40๊ฐ์ item-card ๋
ธ์ถ๋๋ค.', () => {
+ cy.get('.btn').click();
+ cy.get('.item-card').should('have.length', 40);
+ });
+ });
+});
+
+describe('์งง์ ์ํ๋ชฉ๋ก e2e ํ
์คํธ', () => {
+ beforeEach(() => {
+ const baseUrl = 'https://api.themoviedb.org/3/movie/popular';
+ const param = new URLSearchParams({
+ api_key: Cypress.env('API_KEY'),
+ language: 'ko-KR',
+ page: 1,
+ });
+
+ cy.intercept(
+ {
+ method: 'GET',
+ url: `${baseUrl}?${param}`,
+ },
+ { fixture: 'movie-popular-short.json' }
+ ).as('popularMovies');
+
+ cy.visit('http://localhost:8080');
+ });
+
+ context('total_pages ๊ฐ 1์ธ ์ธ๊ธฐ์ํ ๋ชฉ๋ก 1ํ์ด์ง๋ฅผ ์กฐํํ๋ฉด', () => {
+ it('18๊ฐ์ .item-card๊ฐ ๋
ธ์ถ๋๋ค.', () => {
+ cy.get('.item-card').should('have.length', 18);
+ });
+
+ it('๋ ๋ณด๊ธฐ ๋ฒํผ์ด ๋
ธ์ถ๋์ง ์๋๋ค.', () => {
+ cy.contains('๋๋ณด๊ธฐ').should('not.exist');
+ });
+ });
+}); | JavaScript | ํน์ 18๊ฐ์ธ ์ด์ ๊ฐ ์์๊น์? |
@@ -0,0 +1,10 @@
+์ํ ๋ชฉ๋ก API
+- ์ธ๊ธฐ ์ํ๋ชฉ๋ก 1ํ์ด์ง๋ฅผ ์กฐํํ๋ฉด 20๊ฐ์ ๋ชฉ๋ก์ ๋ฐํํ๋ค.
+
+ํ์ด์ง
+- ํ์ด์ง๋ฅผ ์ฆ๊ฐํ ์ ์๋ค.
+
+UI
+- ๋๋ณด๊ธฐ ๋ฒํผ์ ๋๋ฅด๋ฉด ๋ค์ ์ํ ๋ชฉ๋ก์ ๋ถ๋ฌ์จ๋ค.
+- ์ํ ๋ชฉ๋ก์ ํ์ด์ง ๋์ ๋๋ฌํ ๊ฒฝ์ฐ์๋ ๋๋ณด๊ธฐ ๋ฒํผ์ ํ๋ฉด์ ์ถ๋ ฅํ์ง ์๋๋ค.
+- ์ํ ๋ชฉ๋ก ์์ดํ
์ Skeleton UI๋ฅผ ๊ฐ์ง๋ค. | Unknown | ํ์ด์ง๋ฅผ ์ด๊ธฐํํ ์ ์๋ ๊ธฐ๋ฅ์ด ์์๊น์?
โ ์๋์ ์ฝ๋ฉํธ๋ค๊ณผ ๋ชฉ์ ์ ์ด์ด์ง๋๋ค! |
@@ -0,0 +1,18 @@
+const DEFAULT_SEARCH_PARAMS = {
+ api_key: process.env.API_KEY,
+ language: 'ko-KR',
+};
+const MOVIE_BASE_URL = 'https://api.themoviedb.org/3/movie';
+
+export async function getPopularMovie(page) {
+ const param = new URLSearchParams({
+ ...DEFAULT_SEARCH_PARAMS,
+ page,
+ });
+
+ const response = await fetch(`${MOVIE_BASE_URL}/popular?${param}`);
+ if (response.ok) {
+ return response.json();
+ }
+ return { results: [] };
+} | JavaScript | ์กฐ๊ธ ํน์ดํ ๋ฐฉ์์ธ ๊ฒ ๊ฐ๊ธดํ๋ฐ์! ์ด๋ ๊ฒ ๊ฐ์ฒด๋ก ๋ฌถ์ด์ export ํ์ ์ด์ ๊ฐ ์์ผ์ ๊ฐ์? |
@@ -0,0 +1,12 @@
+import PageHandler from './PageHandler';
+import { getPopularMovie } from '../api/movie';
+
+export async function getNextPopularMovieList() {
+ const { page, done } = PageHandler.next();
+ const { results } = await getPopularMovie(page);
+ return {
+ page,
+ done,
+ nextMovieList: results,
+ };
+} | JavaScript | ์์ง ๊ตฌํ๋์ง ์์ ๊ธฐ๋ฅ์ ๋ํ ํจ์๋ฅผ ๋จผ์ ์์ฑํด๋์ ์ด์ ๊ฐ ์์๊น์?! |
@@ -0,0 +1,12 @@
+import PageHandler from './PageHandler';
+import { getPopularMovie } from '../api/movie';
+
+export async function getNextPopularMovieList() {
+ const { page, done } = PageHandler.next();
+ const { results } = await getPopularMovie(page);
+ return {
+ page,
+ done,
+ nextMovieList: results,
+ };
+} | JavaScript | ํธ๋ค๋ฌ ํจ์์์ UI๋ฅผ ์กฐ์ํด์ฃผ๊ณ ์๋ค์! ์ฒ์์ `if (PageHandler.getCurrentPage() !== total_pages)` ์กฐ๊ฑด์ด UI ์ ๊ด๋ จ์ด ์๋ค๊ณ ์๊ฐํ๋๋ฐ ๊ฐ๊ฐ ๋ชฉ์ ์ด ๋ค๋ฅด๋ค์.
์ฌ๊ธฐ์ ์ด ํธ๋ค๋ฌ ํจ์์ ๋ํด์ ๋ ๊ฐ์ง๋ฅผ ๊ณ ๋ฏผํด๋ณด๋ฉด ์ข์ ๊ฒ ๊ฐ์์!
1. `onClickMoreButton` ๋ผ๋ ์ด๋ฆ์ด ํด๋น ํจ์๊ฐ ๋ฌด์์ ํ๋์ง ๋๋ฌ๋ผ ์ ์๋๊ฐ?
2. UI ์กฐ์๊ณผ ๋๋ฉ์ธ ๋ก์ง์ ํจ๊ป ๋๋ ๊ฒ ๋ง์๊น? |
@@ -0,0 +1,42 @@
+const MOVIE_TOTAL_PAGE_LIMIT = 500;
+
+const INITIAL_VALUE = {
+ page: 1,
+ totalPages: MOVIE_TOTAL_PAGE_LIMIT,
+};
+
+function PageEventHandler() {
+ let attr = { ...INITIAL_VALUE };
+
+ return {
+ next() {
+ if (!this.hasNextPage()) {
+ return {
+ page: attr.page,
+ done: true,
+ };
+ }
+ attr.page = attr.page + 1;
+
+ return {
+ page: attr.page,
+ done: !this.hasNextPage(),
+ };
+ },
+ getCurrentPage() {
+ return attr.page;
+ },
+ setTotalPages(totalPages) {
+ if (totalPages > MOVIE_TOTAL_PAGE_LIMIT) {
+ return;
+ }
+ attr.totalPages = totalPages;
+ },
+ hasNextPage() {
+ return attr.page < attr.totalPages;
+ },
+ };
+}
+
+const PageHandler = PageEventHandler();
+export default PageHandler; | JavaScript | ๋ง์ฐฌ๊ฐ์ง๋ก ์ฌ์ฉํ์ง ์๋ ๊ธฐ๋ฅ๋ค์ ๋ํ ๊ตฌํ๋ค์ด ์๋ ๊ฒ ๊ฐ์๋ฐ์!
์ ๊ฑฐํ์ง ์๊ณ ๋จ๊ฒจ ๋์ผ์ ์ด์ ๊ฐ ์์ผ์ค๊น์? |
@@ -0,0 +1,12 @@
+import PageHandler from './PageHandler';
+import { getPopularMovie } from '../api/movie';
+
+export async function getNextPopularMovieList() {
+ const { page, done } = PageHandler.next();
+ const { results } = await getPopularMovie(page);
+ return {
+ page,
+ done,
+ nextMovieList: results,
+ };
+} | JavaScript | ์กฐ๊ธ ๋ ์๋๋ฅผ ์ ๋ฌ๋๋ฆฌ์๋ฉด!
`onClickMoreButton`์ ํด๋ฆญ + ํน์ ๋ฒํผ + ํธ๋ค๋ฌ๋ผ๋ ๊ฒ๋ง ๋๋ฌ๋์ง,
์ด ํจ์๊ฐ ์ค์ ๋ก ์ด๋ค ํ๋์ ํ๋ ์ง๋ ์ ํ ์๋ ค ์ฃผ์ง ๋ชปํ๊ณ ์์ต๋๋ค! |
@@ -0,0 +1,93 @@
+const context = describe;
+
+describe('์ํ๋ชฉ๋ก API ํ
์คํธ', () => {
+ context('์ธ๊ธฐ ์ํ๋ชฉ๋ก 1ํ์ด์ง๋ฅผ ์กฐํํ๋ฉด', () => {
+ it('20๊ฐ์ ๋ชฉ๋ก์ ๋ฐํํ๋ค.', () => {
+ const baseUrl = 'https://api.themoviedb.org/3/movie/popular';
+ const param = new URLSearchParams({
+ api_key: Cypress.env('API_KEY'),
+ language: 'ko-KR',
+ page: 1,
+ });
+
+ cy.request('GET', `${baseUrl}?${param}`).as('popularMovies');
+
+ cy.get('@popularMovies').its('status').should('eq', 200);
+ cy.get('@popularMovies').its('body.results').should('have.length', 20);
+ });
+ });
+});
+
+describe('์ํ๋ชฉ๋ก e2e ํ
์คํธ', () => {
+ beforeEach(() => {
+ const baseUrl = 'https://api.themoviedb.org/3/movie/popular';
+ const param = new URLSearchParams({
+ api_key: Cypress.env('API_KEY'),
+ language: 'ko-KR',
+ page: 1,
+ });
+
+ cy.intercept(
+ {
+ method: 'GET',
+ url: `${baseUrl}?${param}`,
+ },
+ { fixture: 'movie-popular.json' }
+ ).as('popularMovies');
+
+ cy.visit('http://localhost:8080');
+ });
+
+ context('์ํ ๋ชฉ๋ก ์กฐํ ์', () => {
+ it('800ms ๋์ Skeleton UI๊ฐ ๋
ธ์ถ๋์๋ค๊ฐ ์ฌ๋ผ์ง๋ค.', () => {
+ cy.wait('@popularMovies');
+ cy.get('.skeleton').should('have.length', 60);
+ cy.wait(800);
+ cy.get('.skeleton').should('have.length', 0);
+ });
+ });
+
+ context('ํ์ด์ง ์ง์
์ ์ธ๊ธฐ์ํ ๋ชฉ๋ก 1ํ์ด์ง๋ฅผ ์กฐํํ๋ฉด', () => {
+ it('20๊ฐ์ .item-card๊ฐ ๋
ธ์ถ๋๋ค.', () => {
+ cy.get('.item-card').should('have.length', 20);
+ });
+ });
+
+ context('๋๋ณด๊ธฐ ๋ฒํผ์ ํด๋ฆญํ๋ฉด', () => {
+ it('40๊ฐ์ item-card ๋
ธ์ถ๋๋ค.', () => {
+ cy.get('.btn').click();
+ cy.get('.item-card').should('have.length', 40);
+ });
+ });
+});
+
+describe('์งง์ ์ํ๋ชฉ๋ก e2e ํ
์คํธ', () => {
+ beforeEach(() => {
+ const baseUrl = 'https://api.themoviedb.org/3/movie/popular';
+ const param = new URLSearchParams({
+ api_key: Cypress.env('API_KEY'),
+ language: 'ko-KR',
+ page: 1,
+ });
+
+ cy.intercept(
+ {
+ method: 'GET',
+ url: `${baseUrl}?${param}`,
+ },
+ { fixture: 'movie-popular-short.json' }
+ ).as('popularMovies');
+
+ cy.visit('http://localhost:8080');
+ });
+
+ context('total_pages ๊ฐ 1์ธ ์ธ๊ธฐ์ํ ๋ชฉ๋ก 1ํ์ด์ง๋ฅผ ์กฐํํ๋ฉด', () => {
+ it('18๊ฐ์ .item-card๊ฐ ๋
ธ์ถ๋๋ค.', () => {
+ cy.get('.item-card').should('have.length', 18);
+ });
+
+ it('๋ ๋ณด๊ธฐ ๋ฒํผ์ด ๋
ธ์ถ๋์ง ์๋๋ค.', () => {
+ cy.contains('๋๋ณด๊ธฐ').should('not.exist');
+ });
+ });
+}); | JavaScript | ์ธ๊ธฐ ์ํ๋ชฉ๋ก ๋ฐ์ดํฐ๊ฐ 18๊ฐ๋ฐ์ ์์ ๋ 20๊ฐ๋ฅผ ๊ทธ๋ฆฌ์ง ์๊ณ ๊ฐ์๋ฅผ ์ฌ๋ฐ๋ฅด๊ฒ ํ์ํ๋์ง ํ
์คํธํ๊ธฐ ์ํด ์ถ๊ฐํด๋ณด์์ต๋๋ค! |
@@ -0,0 +1,18 @@
+const DEFAULT_SEARCH_PARAMS = {
+ api_key: process.env.API_KEY,
+ language: 'ko-KR',
+};
+const MOVIE_BASE_URL = 'https://api.themoviedb.org/3/movie';
+
+export async function getPopularMovie(page) {
+ const param = new URLSearchParams({
+ ...DEFAULT_SEARCH_PARAMS,
+ page,
+ });
+
+ const response = await fetch(`${MOVIE_BASE_URL}/popular?${param}`);
+ if (response.ok) {
+ return response.json();
+ }
+ return { results: [] };
+} | JavaScript | ์ฌ๋ฌ๊ฐ์ ํจ์๋ฅผ ๋ฌถ์ด์ ๋ด๋ณด๋ด๊ธฐ ์ํด์ ์์๊ฐ์ ์ข
์ข
์ฌ์ฉํด์์๋๋ฐ์!
์ฌ๊ธฐ์๋ ํ๋์ ํจ์๋ง ๋ด๋ณด๋ด๊ธฐ์ ์ ๊ฑฐํด๋ณด์์ต๋๋ค..!
ํน์ ์ฌ๋ฌ๊ฐ์ ํจ์๋ฅผ export ํด์ผํ ๋ ์ด๋ค ๋ฐฉ์์ ์ฌ์ฉํ์๊ณ ์ ํธํ์๋์ง ์ฌ์ญ์ด๋ด๋ ๋ ๊น์? |
@@ -0,0 +1,12 @@
+import PageHandler from './PageHandler';
+import { getPopularMovie } from '../api/movie';
+
+export async function getNextPopularMovieList() {
+ const { page, done } = PageHandler.next();
+ const { results } = await getPopularMovie(page);
+ return {
+ page,
+ done,
+ nextMovieList: results,
+ };
+} | JavaScript | figma๋ฅผ ๋ณด๊ณ modal ์ฌ์ฉ๋ถ๋ถ์ด ์์ด ๋ฏธ๋ฆฌ ์์ฑํด๋ ๊ฒ์ธ๋ฐ ๋ง์ํด์ฃผ์ ๊ฒ์ฒ๋ผ ์ ์ง๋ณด์์ ์ด๋ ค์์ ์ค ์ ์๊ฒ ๋ค์..!
๋ช
์ฌํ๋๋ก ํ๊ฒ ์ต๋๋ค! ํด๋น ๋ถ๋ถ์ ์ ๊ฑฐํ์์ต๋๋ค. ๊ฐ์ฌํฉ๋๋ค! ๐ |
@@ -0,0 +1,12 @@
+import PageHandler from './PageHandler';
+import { getPopularMovie } from '../api/movie';
+
+export async function getNextPopularMovieList() {
+ const { page, done } = PageHandler.next();
+ const { results } = await getPopularMovie(page);
+ return {
+ page,
+ done,
+ nextMovieList: results,
+ };
+} | JavaScript | `onClickMoreButton`์ `getNextPopularMovieList`๋ก ๋ณ๊ฒฝํ๋ฉด์ ์ญํ ์ ๋ถ๋ฆฌํด๋ณด์์ต๋๋ค! |
@@ -0,0 +1,42 @@
+const MOVIE_TOTAL_PAGE_LIMIT = 500;
+
+const INITIAL_VALUE = {
+ page: 1,
+ totalPages: MOVIE_TOTAL_PAGE_LIMIT,
+};
+
+function PageEventHandler() {
+ let attr = { ...INITIAL_VALUE };
+
+ return {
+ next() {
+ if (!this.hasNextPage()) {
+ return {
+ page: attr.page,
+ done: true,
+ };
+ }
+ attr.page = attr.page + 1;
+
+ return {
+ page: attr.page,
+ done: !this.hasNextPage(),
+ };
+ },
+ getCurrentPage() {
+ return attr.page;
+ },
+ setTotalPages(totalPages) {
+ if (totalPages > MOVIE_TOTAL_PAGE_LIMIT) {
+ return;
+ }
+ attr.totalPages = totalPages;
+ },
+ hasNextPage() {
+ return attr.page < attr.totalPages;
+ },
+ };
+}
+
+const PageHandler = PageEventHandler();
+export default PageHandler; | JavaScript | ์ ๊ฑฐํ์์ต๋๋ค! ์ด์ ๋ ์์ ๋ง์๋๋ฆฐ ์ด์ ์ ๋์ผํฉ๋๋ค!
๊ผผ๊ผผํ ๋ฆฌ๋ทฐํด์ฃผ์
์ ๊ฐ์ฌ๋๋ฆฝ๋๋ค ๐ |
@@ -0,0 +1,12 @@
+import PageHandler from './PageHandler';
+import { getPopularMovie } from '../api/movie';
+
+export async function getNextPopularMovieList() {
+ const { page, done } = PageHandler.next();
+ const { results } = await getPopularMovie(page);
+ return {
+ page,
+ done,
+ nextMovieList: results,
+ };
+} | JavaScript | ์... ์ด ๋ถ๋ถ์ ์ ๊ฐ ์๋ํ ๋ฐ์๋ ์กฐ๊ธ ๋ค๋ฅด๊ฒ ๋ณ๊ฒฝ๋ ๊ฒ ๊ฐ์ต๋๋ค!
์ ๊ฐ ์์ฌ ์ฝ๋๋ฅผ ์์ด๊ฐ๋ฉฐ ์ด๋ ์ ๋ ๋ณ๊ฒฝํด๋ณผ๊ฒ์! |
@@ -0,0 +1,18 @@
+export class LoadingHandler {
+ #loading;
+ constructor(initialValue) {
+ this.#loading = initialValue;
+ }
+
+ start() {
+ this.#loading = true;
+ }
+
+ end() {
+ this.#loading = false;
+ }
+
+ isLoading() {
+ return this.#loading;
+ }
+} | JavaScript | ์ฌ์ฉ์ฒ๋ฅผ ๋ณด๋ฉด, ๋ก๋ฉ ์ํ ์์ฒด๋ฅผ ํ์ฉํ๋ ๊ฒฝ์ฐ๊ฐ ํ ๋ฒ ๋ฐ์ ์๊ณ ,
start(), end() ์คํ๊ณผ ํจ๊ป DOM ์กฐ์ ๋ก์ง์ด ํจ๊ป ์ค๋ ๊ฒ ๊ฐ์์!
์ฌ๊ธฐ์ DOM ์กฐ์๋ ๊ฐ์ด ํด์ฃผ๊ณ , ์
๋ ฅ์ผ๋ก ์กฐ์ํ ์์๋ฅผ ๊ฐ์ด ๋ฐ์ผ๋ฉด ๋ ์์ง์ฑ์ด ๋์ ์ฝ๋๊ฐ ๋ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,18 @@
+const DEFAULT_SEARCH_PARAMS = {
+ api_key: process.env.API_KEY,
+ language: 'ko-KR',
+};
+const MOVIE_BASE_URL = 'https://api.themoviedb.org/3/movie';
+
+export async function getPopularMovie(page) {
+ const param = new URLSearchParams({
+ ...DEFAULT_SEARCH_PARAMS,
+ page,
+ });
+
+ const response = await fetch(`${MOVIE_BASE_URL}/popular?${param}`);
+ if (response.ok) {
+ return response.json();
+ }
+ return { results: [] };
+} | JavaScript | ์ฌ๋ฌ๊ฐ์ ํจ์๋ฅผ ๋ฌถ์ด์ ๋ด๋ณด๋ด๊ธฐ ์ํจ์ด๋ค
-> ์ปจ๋ฒค์
๋ง ๋ง๋ค๋ฉด ์ด๋ค ๋ฐฉํฅ์ด๋ ์๊ด ์๋ค๊ณ ์๊ฐํฉ๋๋ค!
๋ค๋ง, ์ ๋ ํ๋์ ํจ์์ธ ์ํฉ์์ ํจ์๊ฐ ๋ ์ถ๊ฐ๋์ง ์์๋๋ฐ, ๋ ์ถ๊ฐ๋ ์์ ์ธ๋ฐ ์ด๋ ๊ฒ ํ์ ๊ฒ ๊ฐ์์
๋จ๊ธด ์ฝ๋ฉํธ์ด๊ธดํฉ๋๋ค! (๋ณธ๋ฌธ์ ์ฝ๋ฉํธ์ ๋์ผํ ๋ด์ฉ์
๋๋ค ใ
ใ
) |
@@ -0,0 +1,46 @@
+package lottodomain;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class LottoGame {
+ private static final int PRICE_PER_LOTTO = 1000;
+
+ private List<Lotto> allLotto;
+ private int numberOfAllLotto;
+
+ public LottoGame(int inputMoney, List<List<Integer>> manualLottoNos) {
+ numberOfAllLotto = inputMoney / PRICE_PER_LOTTO;
+ allLotto = issueLottos(manualLottoNos);
+ }
+
+ public LottoAnalyzer getLottoAnalyzer(WinningNos winningNos) {
+ return new LottoAnalyzer(allLotto, winningNos);
+ }
+
+ public List<Lotto> getAllLotto() {
+ return allLotto;
+ }
+
+ private List<Lotto> issueLottos(List<List<Integer>> manualLottoNos) {
+ List<Lotto> lottos = issueManualLottos(manualLottoNos);
+ lottos.addAll(issueAutoLottos(numberOfAllLotto - lottos.size()));
+ return lottos;
+ }
+
+ private List<Lotto> issueManualLottos(List<List<Integer>> manualLottoNos) {
+ List<Lotto> ManualLottos = new ArrayList<>();
+ for (int i = 0; i < manualLottoNos.size(); i++) {
+ ManualLottos.add(LottoGenerator.generateLottoWithNos(manualLottoNos.get(i)));
+ }
+ return ManualLottos;
+ }
+
+ private List<Lotto> issueAutoLottos(int numberOfAutoLottos) {
+ List<Lotto> autoLottos = new ArrayList<>();
+ for (int i = 0; i < numberOfAutoLottos; i++) {
+ autoLottos.add(LottoGenerator.generateAutoLotto());
+ }
+ return autoLottos;
+ }
+} | Java | ๋ณ์๋ช
์ด ๋๋ฌธ์๋ก ์์ํ๋ค์ ~ |
@@ -0,0 +1,25 @@
+package lottodomain;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+public class LottoGenerator {
+ private static final List<Integer> LOTTO_NO_POOLS = IntStream.rangeClosed(1, 45).boxed().collect(Collectors.toList());
+ ;
+
+ public static Lotto generateLottoWithNos(List<Integer> lottoNos) {
+ return new Lotto(lottoNos);
+ }
+
+ public static Lotto generateAutoLotto() {
+ return generateLottoWithNos(getRandomNos());
+ }
+
+
+ private static List<Integer> getRandomNos() {
+ Collections.shuffle(LOTTO_NO_POOLS);
+ return LOTTO_NO_POOLS.subList(0, 6);
+ }
+} | Java | Lotto ์ factory method ์ ์ถ๊ฐํ์ฌ ์์ฑํด๋ณด๋ฉด ์ด๋จ๊น์?
ex> Lotto.ofAuto(), Lotto.ofManual("1,2,3,4,5,6) |
@@ -0,0 +1,25 @@
+package lottodomain;
+
+public class LottoNo {
+ private Integer value;
+
+ public LottoNo(int number) {
+ value = number;
+ }
+
+ public Integer getValue() {
+ return value;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ LottoNo lottoNo = (LottoNo) o;
+ return value == lottoNo.value;
+ }
+} | Java | LottoNo ๋ฅผ ์์ฑํ ๋ range ์ ๋ํ ์กฐ๊ฑด์ ๊ฒ์ฆํ๋ฉด ์ข ๋ ์๋ฏธ ์๋ wrapping class ๊ฐ ๋์ง ์์๊น์? |
@@ -0,0 +1,25 @@
+package lottodomain;
+
+public class LottoNo {
+ private Integer value;
+
+ public LottoNo(int number) {
+ value = number;
+ }
+
+ public Integer getValue() {
+ return value;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ LottoNo lottoNo = (LottoNo) o;
+ return value == lottoNo.value;
+ }
+} | Java | ๋ฌธ์ :
"๋ชจ๋ ์์๊ฐ๊ณผ ๋ฌธ์์ด์ ํฌ์ฅํ๋ค." ์์น์ ๋ฐ๋ผ ์ธ์คํด์ค๋ฅผ ์์ฑํ๋ค๋ณด๋ ๋๋ฌด ๋ง์ ๊ฐ์ฒด๊ฐ ์์ฑ๋๊ณ , GC๊ฐ ๋์ด ์ฑ๋ฅ์ ๋ฌธ์ ๊ฐ ๋ฐ์ํ๋ค.
ํนํ ๋ก๋ ๋ฒํธ ํ๋๊น์ง ๊ฐ์ฒด๋ก ํฌ์ฅํ ๊ฒฝ์ฐ ์์ฑ๋๋ ์ธ์คํด์ค์ ์๋ ์๋นํ ๋์ด๋๋ ๋ฌธ์ ๊ฐ ๋ฐ์ํ๋ค.
์์ ๊ฐ์ ๋ฌธ์ ๋ ์ด๋ป๊ฒ ํด๊ฒฐํ ์ ์์๊น์? (ํค์๋ : static, map) |
@@ -0,0 +1,25 @@
+package lottodomain;
+
+public class LottoNo {
+ private Integer value;
+
+ public LottoNo(int number) {
+ value = number;
+ }
+
+ public Integer getValue() {
+ return value;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ LottoNo lottoNo = (LottoNo) o;
+ return value == lottoNo.value;
+ }
+} | Java | ๋ถ๋ณ์ ๊ฐ์ wrapping ํ ํด๋์ค์ด๋ฏ๋ก final int value; ๋ก ์ ์ธํด๋ณด๋ฉด ์ด๋จ๊น์? |
@@ -0,0 +1,49 @@
+package lottoview;
+
+import lottodomain.Lotto;
+import lottodomain.LottoAnalyzer;
+import lottodomain.LottoNo;
+import lottodomain.Rank;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+public class OutputView {
+ public static void showAllLottos(List<Lotto> allLotto, int numberOfManualLottos) {
+ int numberOfAutoLottos = allLotto.size() - numberOfManualLottos;
+ System.out.printf("์๋์ผ๋ก %d์ฅ, ์๋์ผ๋ก %d์ฅ์ ๊ตฌ๋งคํ์ต๋๋ค.\n", numberOfManualLottos, numberOfAutoLottos);
+ allLotto.stream().forEach(lotto -> showLotto(lotto));
+ }
+
+ public static void showLotto(Lotto lotto) {
+ List<LottoNo> lottoNos = lotto.getLottoNos();
+ System.out.println(lottoNos.stream().map(LottoNo::getValue).map(number -> number.toString())
+ .collect(Collectors.joining(", ", "[", "]")));
+ }
+
+ public static void showAnalysis(LottoAnalyzer lottoAnalyzer) {
+ showWRanks(lottoAnalyzer);
+ showEarningRate(lottoAnalyzer.calculateEarningRate());
+ }
+
+ public static void showRankCount(Rank rank, int count) {
+ System.out.printf("%d๊ฐ ์ผ์น (%d์)- %d๊ฐ\n", rank.getCountOfMatch(), rank.getWinningMoney(), count);
+ }
+
+ public static void showEarningRate(double earningRate) {
+ System.out.printf("์ด ์์ต๋ฅ ์ %.1f%%์
๋๋ค.\n", earningRate);
+ }
+
+ private static void showWRanks(LottoAnalyzer lottoAnalyzer) {
+ System.out.println("๋น์ฒจ ํต๊ณ");
+ System.out.println("---------");
+ List<Rank> prize = Stream.of(Rank.values()).collect(Collectors.toList());
+ prize.remove(Rank.MISS);
+ for (int i = prize.size() - 1; i >= 0; i--) {
+ int count = lottoAnalyzer.countRank(prize.get(i));
+ showRankCount(prize.get(i), count);
+ }
+ }
+} | Java | analyzer ๊ฐ outputview ์ ์์ ๋น์ฆ๋์ค ๋ก์ง์ ์ํํ๊ณ ์๋๋ฐ์
๊ฒ์์ ๊ฒฐ๊ณผ๋ฅผ ๋ด๋ LottoResults(DTO) ํด๋์ค์ Lotto list ๋ฅผ ๊ฐ์ธ๋ Lottos ํด๋์ค๋ฅผ ๋ง๋ค์ด์
outputview ์์ ๋น์ฆ๋์ค ๋ก์ง์ด ์คํ๋์ง ์๋๋ก ๋ณ๊ฒฝํด๋ณด๋ฉด ์ด๋จ๊น์? |
@@ -0,0 +1,63 @@
+package lottodomain;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import static org.junit.Assert.*;
+
+public class LottoAnalyzerTest {
+ private static final double DELTA = 1e-15;
+
+ private List<Lotto> lottos;
+ private LottoAnalyzer lottoAnalyzer;
+ private WinningNos winningNos;
+
+ @Before
+ public void setUp() throws Exception {
+ lottos = new ArrayList<>();
+ lottos.add(new Lotto(Arrays.asList(1, 2, 3, 4, 5, 6))); // FIRST
+ lottos.add(new Lotto(Arrays.asList(1, 2, 3, 4, 5, 7))); // SECOND
+ lottos.add(new Lotto(Arrays.asList(1, 2, 3, 4, 5, 8))); // THIRD
+ lottos.add(new Lotto(Arrays.asList(1, 2, 3, 4, 7, 8))); // FOURTH
+ lottos.add(new Lotto(Arrays.asList(1, 2, 3, 7, 8, 9))); // FIFTH
+ lottos.add(new Lotto(Arrays.asList(1, 2, 7, 8, 9, 10))); // MISS
+ winningNos = new WinningNos(Arrays.asList(1, 2, 3, 4, 5, 6), 7);
+ lottoAnalyzer = new LottoAnalyzer(lottos, winningNos);
+ }
+
+ @Test
+ public void calculateRankOfLotto() {
+ List<Rank> ranks = Arrays.asList(Rank.values());
+ for (int i = 0; i < lottos.size(); i++) {
+ assertEquals(ranks.get(i), lottoAnalyzer.calculateRankOfLotto(lottos.get(i), winningNos));
+ }
+ }
+
+ @Test
+ public void calculateEarnedMoney() {
+ assertEquals(2031555000, lottoAnalyzer.calculateEarnedMoney());
+ }
+
+ @Test
+ public void calculateEarningRate() {
+ assertEquals(33859250.0, lottoAnalyzer.calculateEarningRate(), DELTA);
+ }
+
+ @Test
+ public void countRank() {
+ List<Rank> ranks = Arrays.asList(Rank.values());
+ for (int i = 0; i < ranks.size(); i++) {
+ assertEquals(1, lottoAnalyzer.countRank(ranks.get(i)));
+ }
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ lottos = null;
+ }
+}
\ No newline at end of file | Java | ์ข์ ์ ๋ํ
์คํธ ์์ฑ๋ฒ์๋ F.I.R.S.T ๋ผ๋ ์์น์ด ์๋๋ฐ์
https://coding-start.tistory.com/261
์ฒจ๋ถํ๊ณ ๊ฐ๋๋ค ~ |
@@ -0,0 +1,47 @@
+package lottodomain;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import static org.junit.Assert.*;
+
+public class LottoGameTest {
+ private LottoGame lottoGame;
+ List<List<Integer>> manualLottoNumbers;
+
+ private void assertArrayEquals(List<Lotto> expectedLottos, List<Lotto> subList) {
+ for (int i = 0; i < expectedLottos.size(); i++) {
+ assertEquals(expectedLottos.get(i), subList.get(i));
+ }
+ }
+
+ @Before
+ public void setUp() throws Exception {
+ manualLottoNumbers = new ArrayList<>();
+ manualLottoNumbers.add(Arrays.asList(1, 2, 3, 4, 5, 6));
+ manualLottoNumbers.add(Arrays.asList(1, 4, 11, 15, 19, 23));
+ manualLottoNumbers.add(Arrays.asList(4, 10, 17, 25, 34, 42));
+ }
+
+ @Test
+ public void setManualLottos() {
+ lottoGame = new LottoGame(10000, manualLottoNumbers);
+ assertEquals(10, lottoGame.getAllLotto().size());
+
+ List<Lotto> expectedLottos = manualLottoNumbers.stream().map(numbers -> LottoGenerator.generateLottoWithNos(numbers))
+ .collect(Collectors.toList());
+ assertArrayEquals(expectedLottos, lottoGame.getAllLotto().subList(0, 3));
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ lottoGame = null;
+ manualLottoNumbers = null;
+ }
+}
\ No newline at end of file | Java | private method ๋ public ๋ณด๋ค ์๋์ ์์น์์ผ์ฃผ๋๊ฒ ๊ฐ๋
์ฑ์ ์ข์ต๋๋ค ~ |
@@ -0,0 +1,50 @@
+package lottodomain;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import static org.junit.Assert.*;
+
+public class WinningNosTest {
+ private WinningNos winningNos;
+
+ @Before
+ public void setUp() throws Exception {
+ winningNos = new WinningNos(Arrays.asList(1, 2, 3, 4, 5, 6), 7);
+ }
+
+ @Test
+ public void countMatchOf() {
+ List<Lotto> lottos = new ArrayList<>();
+ lottos.add(new Lotto(Arrays.asList(8, 9, 10, 11, 12, 13)));
+ lottos.add(new Lotto(Arrays.asList(1, 8, 9, 10, 11, 12)));
+ lottos.add(new Lotto(Arrays.asList(1, 2, 9, 10, 11, 12)));
+ lottos.add(new Lotto(Arrays.asList(1, 2, 3, 10, 11, 12)));
+ lottos.add(new Lotto(Arrays.asList(1, 2, 3, 4, 11, 12)));
+ lottos.add(new Lotto(Arrays.asList(1, 2, 3, 4, 5, 12)));
+ lottos.add(new Lotto(Arrays.asList(1, 2, 3, 4, 5, 6)));
+
+ for (int i = 0; i < lottos.size(); i++) {
+ assertEquals(i, winningNos.countMatchOf(lottos.get(i)));
+ }
+ }
+
+ @Test
+ public void isBonus() {
+ Lotto trueLotto = new Lotto(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
+ Lotto falseLotto = new Lotto(Arrays.asList(1, 2, 3, 4, 5, 6, 8));
+
+ assertTrue(winningNos.isBonus(trueLotto));
+ assertFalse(winningNos.isBonus(falseLotto));
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ winningNos = null;
+ }
+}
\ No newline at end of file | Java | ์ ์ฒด์ ์ผ๋ก ์ฝ๋์ ๋นํด ํ
์คํธ ์ชฝ์ด ์กฐ๊ธ ์์ฌ์์
์๊ฐ์ด ๋์ ๋ค๋ฉด TDD ๋ฐฉ๋ฒ๋ก ์ ํตํด ๋ก๋๋ ๋ ์ด์ฑ ๊ฒ์์ ๋ค์ ๊ตฌํํด๋ณด๋ ๊ฒ๋ ๋ง์ด ๋์์ด ๋์ค ๊ฒ ๊ฐ์ต๋๋ค |
@@ -1,5 +1,98 @@
import React from 'react';
+import { useState, useEffect } from 'react';
+import { useNavigate } from 'react-router-dom';
+import './Login.scss';
-export default function Login() {
- return <div>Hello, Hyeonze!</div>;
-}
+const Login = () => {
+ const [idInput, setIdInput] = useState('');
+ const [pwInput, setPwInput] = useState('');
+ const [isValidatedUser, setIsValidatedUser] = useState(false);
+
+ const navigate = useNavigate();
+ const changeIdInput = e => {
+ const { value } = e.target;
+ setIdInput(value);
+ };
+
+ const changePwInput = e => {
+ const { value } = e.target;
+ setPwInput(value);
+ };
+
+ useEffect(() => {
+ setIsValidatedUser(idInput.indexOf('@') !== -1 && pwInput.length > 4);
+ }, [idInput, pwInput]);
+
+ // ๋ฉ์ธ์ผ๋ก ์ด๋ํ ๋ ๋ก์ง
+ const goToMain = () => {
+ navigate('/main-hyeonze');
+ };
+
+ // ํ์๊ฐ์
์ ์ฌ์ฉํ ๋ก์ง
+ // const signup = () => {
+ // fetch('http://10.58.4.22:8000/users/signup', {
+ // method: 'POST',
+ // body: JSON.stringify({
+ // email: idInput,
+ // password: pwInput,
+ // }),
+ // })
+ // .then(response => response.json())
+ // .then(result => {
+ // //console.log('๊ฒฐ๊ณผ: ', result.message)
+ // if (result.message === 'EMAIL_ALREADY_EXISTS') {
+ // console.log('Error : Duplicated');
+ // }
+ // });
+ // };
+
+ // ๋ก๊ทธ์ธ์ ์ฌ์ฉํ ๋ก์ง
+ // const login = () => {
+ // fetch('http://10.58.4.22:8000/users/login', {
+ // method: 'POST',
+ // body: JSON.stringify({
+ // email: idInput,
+ // password: pwInput,
+ // }),
+ // })
+ // .then(response => response.json())
+ // .then(result => {
+ // //console.log('๊ฒฐ๊ณผ: ', result.message)
+ // if (result.message === 'SUCCESS') {
+ // console.log('login SUCCESS');
+ // }
+ // });
+ // };
+
+ return (
+ <div className="login">
+ <div id="wrapper">
+ <h1>westagram</h1>
+ <form className="login_form">
+ <input
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ className="username"
+ onChange={changeIdInput}
+ />
+ <input
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ className="userpassword"
+ onChange={changePwInput}
+ />
+ <input
+ className={isValidatedUser ? 'activated' : ''}
+ disabled={!isValidatedUser}
+ type="button"
+ value="๋ก๊ทธ์ธ"
+ onClick={goToMain}
+ />
+ </form>
+ <p>๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</p>
+ </div>
+ </div>
+ );
+};
+
+export default Login; | Unknown | ์ด ๋ ์กฐ๊ฑด์ &&๋ก ๊ฑธ๋ฉด state๋ฅผ ํ๋๋ง ์ฌ์ฉํ๊ณ validation์ ํ์ธํ ์ ์์ง ์์๊น์?
์ ์ ์ฆ์ดํํธ๋ฅผ ์ฐ์
จ๋์ง ๊ถ๊ธํฉ๋๋ค. |
@@ -1,5 +1,98 @@
import React from 'react';
+import { useState, useEffect } from 'react';
+import { useNavigate } from 'react-router-dom';
+import './Login.scss';
-export default function Login() {
- return <div>Hello, Hyeonze!</div>;
-}
+const Login = () => {
+ const [idInput, setIdInput] = useState('');
+ const [pwInput, setPwInput] = useState('');
+ const [isValidatedUser, setIsValidatedUser] = useState(false);
+
+ const navigate = useNavigate();
+ const changeIdInput = e => {
+ const { value } = e.target;
+ setIdInput(value);
+ };
+
+ const changePwInput = e => {
+ const { value } = e.target;
+ setPwInput(value);
+ };
+
+ useEffect(() => {
+ setIsValidatedUser(idInput.indexOf('@') !== -1 && pwInput.length > 4);
+ }, [idInput, pwInput]);
+
+ // ๋ฉ์ธ์ผ๋ก ์ด๋ํ ๋ ๋ก์ง
+ const goToMain = () => {
+ navigate('/main-hyeonze');
+ };
+
+ // ํ์๊ฐ์
์ ์ฌ์ฉํ ๋ก์ง
+ // const signup = () => {
+ // fetch('http://10.58.4.22:8000/users/signup', {
+ // method: 'POST',
+ // body: JSON.stringify({
+ // email: idInput,
+ // password: pwInput,
+ // }),
+ // })
+ // .then(response => response.json())
+ // .then(result => {
+ // //console.log('๊ฒฐ๊ณผ: ', result.message)
+ // if (result.message === 'EMAIL_ALREADY_EXISTS') {
+ // console.log('Error : Duplicated');
+ // }
+ // });
+ // };
+
+ // ๋ก๊ทธ์ธ์ ์ฌ์ฉํ ๋ก์ง
+ // const login = () => {
+ // fetch('http://10.58.4.22:8000/users/login', {
+ // method: 'POST',
+ // body: JSON.stringify({
+ // email: idInput,
+ // password: pwInput,
+ // }),
+ // })
+ // .then(response => response.json())
+ // .then(result => {
+ // //console.log('๊ฒฐ๊ณผ: ', result.message)
+ // if (result.message === 'SUCCESS') {
+ // console.log('login SUCCESS');
+ // }
+ // });
+ // };
+
+ return (
+ <div className="login">
+ <div id="wrapper">
+ <h1>westagram</h1>
+ <form className="login_form">
+ <input
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ className="username"
+ onChange={changeIdInput}
+ />
+ <input
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ className="userpassword"
+ onChange={changePwInput}
+ />
+ <input
+ className={isValidatedUser ? 'activated' : ''}
+ disabled={!isValidatedUser}
+ type="button"
+ value="๋ก๊ทธ์ธ"
+ onClick={goToMain}
+ />
+ </form>
+ <p>๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</p>
+ </div>
+ </div>
+ );
+};
+
+export default Login; | Unknown | id์ pw๋ก ํ๋ฒ์ validationํ๊ณ activateBtn์ True/false๋ฅผ ์ง์ ํ๋ฉด ๋ ๊ฒ ๊ฐ์ต๋๋ค. isValidatedId๋ isValidatedPw๋ ํฌ๊ฒ ํ์ํ์ง ์์ ๊ฒ ๊ฐ์์. ๋ถํ์ํ ๋ฆฌ๋๋๋ง๋ ์ค์ผ ์ ์๋ค๊ณ ์๊ฐํ๋๋ฐ ์ด๋ป๊ฒ ์๊ฐํ์๋์? |
@@ -0,0 +1,66 @@
+@use '../../../styles/mixin.scss' as mixin;
+@use '../../../styles/color.scss' as clr;
+
+body {
+ background: clr.$bg-login;
+
+ .login {
+ position: relative;
+ top: -80px;
+
+ #wrapper {
+ @include mixin.flex($align: center);
+ position: relative;
+ flex-direction: column;
+ width: 700px;
+ height: 761px;
+ border: 1px solid clr.$clr-border;
+
+ h1 {
+ margin-top: 90px;
+ margin-bottom: 130px;
+ font-size: 81px;
+ font-family: 'Lobster', cursive;
+ }
+
+ .login_form {
+ input {
+ display: block;
+ width: 536px;
+ height: 76px;
+ margin-bottom: 12px;
+ padding-left: 10px;
+ background: #fafafa;
+ border: 1px solid clr.$clr-border;
+ border-radius: 3px;
+ font-size: 16px;
+ }
+
+ input[type='button'] {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 536px;
+ height: 60px;
+ margin-top: 16px;
+ background-color: clr.$clr-primary;
+ opacity: 0.5;
+ border: none;
+ border-radius: 4px;
+ font-size: 16px;
+ color: #fff;
+
+ &.activated {
+ opacity: 1;
+ }
+ }
+ }
+
+ p {
+ position: absolute;
+ bottom: 20px;
+ color: #043667;
+ }
+ }
+ }
+} | Unknown | input์ด inline-block์ด๊ณ ์์ง์ผ๋ก ์ ๋ ฌํ๋ ค๊ณ display: flex๋ฅผ ์ฐ์ ๊ฒ ๊ฐ์ต๋๋ค. ๊ต์ฅํ ์ข์๋ฐ์ ์ ๋ Input์ display: blockํด์ฃผ๋ ๊ฒ๋ ๊ด์ฐฎ์ ๋ฐฉ๋ฒ์ด์ง ์์๊น ์๊ฐํฉ๋๋ค. |
@@ -0,0 +1,66 @@
+@use '../../../styles/mixin.scss' as mixin;
+@use '../../../styles/color.scss' as clr;
+
+body {
+ background: clr.$bg-login;
+
+ .login {
+ position: relative;
+ top: -80px;
+
+ #wrapper {
+ @include mixin.flex($align: center);
+ position: relative;
+ flex-direction: column;
+ width: 700px;
+ height: 761px;
+ border: 1px solid clr.$clr-border;
+
+ h1 {
+ margin-top: 90px;
+ margin-bottom: 130px;
+ font-size: 81px;
+ font-family: 'Lobster', cursive;
+ }
+
+ .login_form {
+ input {
+ display: block;
+ width: 536px;
+ height: 76px;
+ margin-bottom: 12px;
+ padding-left: 10px;
+ background: #fafafa;
+ border: 1px solid clr.$clr-border;
+ border-radius: 3px;
+ font-size: 16px;
+ }
+
+ input[type='button'] {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 536px;
+ height: 60px;
+ margin-top: 16px;
+ background-color: clr.$clr-primary;
+ opacity: 0.5;
+ border: none;
+ border-radius: 4px;
+ font-size: 16px;
+ color: #fff;
+
+ &.activated {
+ opacity: 1;
+ }
+ }
+ }
+
+ p {
+ position: absolute;
+ bottom: 20px;
+ color: #043667;
+ }
+ }
+ }
+} | Unknown | '๋ก๊ทธ์ธ' ์ด๋ผ๋ ๊ธ์ ์ผํฐ์ ๋ง์ถ๊ธฐ ์ํด display: flex์ฃผ์ ๊ฒ ๊ฐ์์. ์ข์๋ฐฉ๋ฒ์ด์ง๋ง flex์ ๊ทธ ์์ฑ๋ค์ด ์ข ๋จ์ด์ ธ ์๋ ๊ฒ ๊ฐ์ต๋๋ค. ์ด๋ ๊ฒ ์ฐ๊ด๋๋ css์์ฑ์ ๋ถ์ฌ ์ฃผ์๋ ๊ฒ ๋์ค์ ์ ์ง๋ณด์ ์ธก๋ฉด์์๋ ์ข์ ๊ฒ ๊ฐ์ ์ถ์ฒ ๋๋ฆฝ๋๋ค! |
@@ -0,0 +1,26 @@
+import React, { useState } from 'react';
+import { AiFillDelete, AiOutlineHeart, AiFillHeart } from 'react-icons/ai';
+
+const Comment = ({ id, userId, value, time, handleDelete }) => {
+ const [isLiked, setIsLiked] = useState(false);
+
+ const toggleLike = () => {
+ setIsLiked(!isLiked);
+ };
+
+ return (
+ <span id={id} className="comment">
+ <strong>{userId} </strong>
+ {value}
+ <small> {time}</small>
+ <AiFillDelete onClick={handleDelete} className="delete" />
+ {isLiked ? (
+ <AiFillHeart onClick={toggleLike} className="hearts liked" />
+ ) : (
+ <AiOutlineHeart onClick={toggleLike} className="hearts" />
+ )}
+ </span>
+ );
+};
+
+export default Comment; | Unknown | ์ ๋ฒ ์ธ์
์์ ๋ฉํ ๋์ด ํ์ ๊ฒ์ฒ๋ผ ๋ณ์๋ช
์ ์กฐ๊ธ ๋ ๊ตฌ์ฒด์ ์ผ๋ก ์ด๋ค ๋ด์ฉ์ ๋ด๊ณ ์๋์ง๋ฅผ ์์ฑํด ์ฃผ์๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค. commentVal์ด ๋๊ธ ์ ์ฒด๋ฅผ ๊ด๋ฆฌํ๋ ๋ฐฐ์ด์ด๊ณ el์ด ๊ฐ ๋ฐฐ์ด์ ์์์ด๋๊น
commentVal๋์ allComments, el๋์ comment๋ฑ์ผ๋ก (์ด๊ฑด ์ ๋ ์กฐ๊ธ ์ ๋งคํ๋ค์ .. ์ฃ์กํฉ๋๋ค) (๋ฐฐ์ด์ s๋ฅผ ๋ถ์ธ ๋ณ์๋ช
์ผ๋ก ํ๋ ๊ฒ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค!) |
@@ -0,0 +1,43 @@
+span.comment {
+ padding-left: 10px;
+
+ small {
+ color: #a3a3a3;
+ }
+
+ &:first-child {
+ padding: 10px;
+ font-weight: bold;
+ }
+
+ svg {
+ &.delete {
+ display: none;
+ cursor: pointer;
+ }
+
+ &.hearts {
+ color: #a3a3a3;
+ position: absolute;
+ right: 20px;
+ transition: color 1s;
+ cursor: pointer;
+
+ path {
+ color: #a3a3a3;
+ }
+ }
+
+ &.liked {
+ path {
+ color: #f00;
+ }
+ }
+ }
+
+ &:hover svg {
+ &.delete {
+ display: inline-block;
+ }
+ }
+} | Unknown | span์ ๋ํด์๋ง ์คํ์ผ๋ง์ ํด์ฃผ์
จ๋๋ฐ ์ด๋ฌ๋ฉด ๋ค๋ฅธ ์ปดํฌ๋ํธ์ span์๋ ์ํฅ์ด ๊ฐ์ง ์์๊น ์กฐ์ฌ์ค๋ฝ๊ฒ ์๊ฐํด ๋ด
๋๋ค. ๊ฐ์ธ์ ์ผ๋ก className์ ์ฃผ๋ ๊ฒ ์กฐ๊ธ ๋ ์์ ํ ๊ฒ ๊ฐ์ต๋๋ค
์ถ๊ฐ์ ์ผ๋ก svgํ๊ทธ๋ span ๋ด๋ถ์ nestingํด์ฃผ์๋ฉด ์ข์ ๊ฒ ๊ฐ์์.
```
svg {
&.red {}
&.blue {}
}
``` |
@@ -0,0 +1,87 @@
+import React, { useState } from 'react';
+import { AiFillHeart, AiOutlineComment, AiOutlineUpload } from 'react-icons/ai';
+import { BiDotsHorizontalRounded } from 'react-icons/bi';
+import { GrBookmark } from 'react-icons/gr';
+import './Feeds.scss';
+import Comments from './Comment/Comments';
+
+export default function Feeds({ userId, profileImg, img, comments }) {
+ const [commentVal, setCommentVal] = useState(comments);
+ let addedCommentVal = [...commentVal];
+ const [currInputVal, setCurrInputVal] = useState('');
+
+ const handleInput = e => {
+ const { value } = e.target;
+ if (e.keyCode === 13) uploadComment();
+ setCurrInputVal(value);
+ };
+
+ const uploadComment = e => {
+ e.preventDefault();
+ if (!currInputVal) return;
+ addedCommentVal.push({
+ id: addedCommentVal.length + 1,
+ userId: 'userid',
+ value: currInputVal,
+ time: '๋ฐฉ๊ธ์ ',
+ });
+ setCommentVal(addedCommentVal);
+ setCurrInputVal('');
+ };
+
+ const handleDelete = e => {
+ const { id } = e.target.parentNode.parentNode;
+ addedCommentVal = addedCommentVal.filter(el => el.id !== Number(id));
+ setCommentVal(addedCommentVal);
+ };
+
+ return (
+ <div className="feeds">
+ <article>
+ <div className="top_menu">
+ <span>
+ <img src={profileImg} alt="ํ๋กํ" />
+ {userId}
+ </span>
+ <span>
+ <BiDotsHorizontalRounded />
+ </span>
+ </div>
+ <img src={img} alt="๋ฌดํ๊ณผ" />
+ <div className="bottom_menu">
+ <span>
+ <AiFillHeart className="" />
+ </span>
+ <span>
+ <AiOutlineComment className="" />
+ </span>
+ <span>
+ <AiOutlineUpload className="" />
+ </span>
+ <span>
+ <GrBookmark className="" />
+ </span>
+ </div>
+ <div className="comments">
+ <span>4 Likes</span>
+ <Comments commentArr={commentVal} handleDelete={handleDelete} />
+ </div>
+ <form className="add_comments">
+ <input
+ type="text"
+ placeholder="๋๊ธ ๋ฌ๊ธฐ..."
+ className="input_upload"
+ onChange={handleInput}
+ value={currInputVal}
+ />
+ <button
+ className={currInputVal ? 'activated' : ''}
+ onClick={uploadComment}
+ >
+ ๊ฒ์
+ </button>
+ </form>
+ </article>
+ </div>
+ );
+} | Unknown | ๊ต์ฅํ ์ ์ง์ ๊ฒ ๊ฐ์ต๋๋ค!! ๐ ๊ทธ๋ฐ๋ฐ ์์๊ฐ ์กฐ๊ธ ์ ๋งคํ ๊ฒ ๊ฐ์์. 17)์์ uploadComment ํธ์ถ์ ํ๊ณ 31)์์ currInputVal( " " ) -> 18 ) ์์ currInputVal( e.target.value ) ์์ผ๋ก ์งํ์ด ๋๋ค๋ฉด ๋๊ธ์ ์ถ๊ฐํ๋๋ผ๋ input์ ๋น์์ง์ง ์์ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,101 @@
+@use '../../../../styles/mixin.scss' as mixin;
+@use '../../../../styles/color.scss' as clr;
+
+.feeds {
+ position: relative;
+ top: 77px;
+ width: 60%;
+ margin-bottom: 80px;
+ background: #fff;
+
+ .top_menu {
+ @include mixin.flex($justify: space-between, $align: center);
+ height: 82px;
+
+ span {
+ @include mixin.flex($align: center);
+ margin-left: 20px;
+ font-weight: bold;
+
+ &:last-child {
+ margin-right: 22px;
+ color: #2a2a2a;
+ font-size: 35px;
+ }
+
+ img {
+ width: 42px;
+ height: 42px;
+ border-radius: 50%;
+ margin-right: 20px;
+ }
+ }
+ }
+
+ article {
+ img {
+ width: 100%;
+ height: 818px;
+ }
+
+ .bottom_menu {
+ @include mixin.flex($align: center);
+ position: relative;
+ height: 62px;
+
+ span > svg {
+ margin: 0 10px;
+ font-size: 32px;
+ color: #414141;
+ }
+
+ span:last-child > svg {
+ position: absolute;
+ top: 15px;
+ right: 0;
+ }
+
+ span:first-child > svg > path {
+ color: #eb4b59;
+ }
+ }
+ }
+
+ .comments {
+ display: flex;
+ flex-direction: column;
+
+ span {
+ padding-left: 10px;
+ }
+ }
+
+ .add_comments {
+ position: absolute;
+ @include mixin.flex($justify: space-between, $align: center);
+ bottom: -62px;
+ width: 100%;
+ height: 62px;
+ border-top: 1px solid clr.$clr-border;
+ font-size: 14px;
+
+ input {
+ width: 90%;
+ height: 50%;
+ margin-left: 15px;
+ border: none;
+ }
+
+ button {
+ margin-right: 15px;
+ border: none;
+ color: clr.$clr-primary;
+ opacity: 0.5;
+ background: #fff;
+
+ &.activated {
+ opacity: 1;
+ }
+ }
+ }
+} | Unknown | Feeds.jsx์์ .feeds์ ๋ฐ๋ก ์์์์๊ฐ article์ด๋ผ article์ .feeds ๋ฐ๋ก ๋ค์์ ์จ์ฃผ๋ ๊ฒ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค. ๊ทธ๋ฆฌ๊ณ height์์๋ ์์์์๋ค์ ๋์ด์ ๋ฐ๋ผ ๊ฒฐ์ ๋๋๊น height: 100%๋ฅผ ์ฃผ์ด๋ feeds์ ๋์ด๊ฐ ๋ณํ์ง๋ ์์ ๊ฒ ๊ฐ๋ค๋ ์๊ฐ์ด ๋๋๋ฐ ํน์ ์ค์ ํ์ ์ด์ ๊ฐ ์์ผ์ ๊ฐ์? |
@@ -1,5 +1,98 @@
import React from 'react';
+import { useState, useEffect } from 'react';
+import { useNavigate } from 'react-router-dom';
+import './Login.scss';
-export default function Login() {
- return <div>Hello, Hyeonze!</div>;
-}
+const Login = () => {
+ const [idInput, setIdInput] = useState('');
+ const [pwInput, setPwInput] = useState('');
+ const [isValidatedUser, setIsValidatedUser] = useState(false);
+
+ const navigate = useNavigate();
+ const changeIdInput = e => {
+ const { value } = e.target;
+ setIdInput(value);
+ };
+
+ const changePwInput = e => {
+ const { value } = e.target;
+ setPwInput(value);
+ };
+
+ useEffect(() => {
+ setIsValidatedUser(idInput.indexOf('@') !== -1 && pwInput.length > 4);
+ }, [idInput, pwInput]);
+
+ // ๋ฉ์ธ์ผ๋ก ์ด๋ํ ๋ ๋ก์ง
+ const goToMain = () => {
+ navigate('/main-hyeonze');
+ };
+
+ // ํ์๊ฐ์
์ ์ฌ์ฉํ ๋ก์ง
+ // const signup = () => {
+ // fetch('http://10.58.4.22:8000/users/signup', {
+ // method: 'POST',
+ // body: JSON.stringify({
+ // email: idInput,
+ // password: pwInput,
+ // }),
+ // })
+ // .then(response => response.json())
+ // .then(result => {
+ // //console.log('๊ฒฐ๊ณผ: ', result.message)
+ // if (result.message === 'EMAIL_ALREADY_EXISTS') {
+ // console.log('Error : Duplicated');
+ // }
+ // });
+ // };
+
+ // ๋ก๊ทธ์ธ์ ์ฌ์ฉํ ๋ก์ง
+ // const login = () => {
+ // fetch('http://10.58.4.22:8000/users/login', {
+ // method: 'POST',
+ // body: JSON.stringify({
+ // email: idInput,
+ // password: pwInput,
+ // }),
+ // })
+ // .then(response => response.json())
+ // .then(result => {
+ // //console.log('๊ฒฐ๊ณผ: ', result.message)
+ // if (result.message === 'SUCCESS') {
+ // console.log('login SUCCESS');
+ // }
+ // });
+ // };
+
+ return (
+ <div className="login">
+ <div id="wrapper">
+ <h1>westagram</h1>
+ <form className="login_form">
+ <input
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ className="username"
+ onChange={changeIdInput}
+ />
+ <input
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ className="userpassword"
+ onChange={changePwInput}
+ />
+ <input
+ className={isValidatedUser ? 'activated' : ''}
+ disabled={!isValidatedUser}
+ type="button"
+ value="๋ก๊ทธ์ธ"
+ onClick={goToMain}
+ />
+ </form>
+ <p>๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</p>
+ </div>
+ </div>
+ );
+};
+
+export default Login; | Unknown | ์ด ๋ ์กฐ๊ฑด์ &&๋ก ๊ฑธ๋ฉด state๋ฅผ ํ๋๋ง ์ฌ์ฉํ๊ณ validation์ ํ์ธํ ์ ์์ง ์์๊น์? => ๋ง๋ ๊ฒ ๊ฐ์ต๋๋ค.
์์ ์ ์ฝ๋์์ ์ ํจ์ฑ๊ฒ์ฌ๋ฅผ changeIdInput, changePwInput ๋ด์์ ๊ฐ๊ฐ ํด์คฌ์๋๋ฐ ํธํ์ฑ ๊ฒ์ฌ์ ๋๋ ์ด๊ฐ ์๊ฒจ์ useEffect๋ฅผ ์ฌ์ฉํ๋๊ฒ ํด๊ฒฐ์ฑ
์ด๋ผ ์๊ฐํ์ต๋๋ค. ์ด ๊ณผ์ ์์ changeIdInput, changePwInput ๋ด๋ถ์ ์ผํญ์ฐ์ฐ์๋ค์ useEffect ๋ด๋ถ๋ก ์๋ผ๋ด์ด ์ค๊ฒ ๋๋ฉด์ ๋ก์ง์ด ๊ธธ์ด์ง ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -1,5 +1,98 @@
import React from 'react';
+import { useState, useEffect } from 'react';
+import { useNavigate } from 'react-router-dom';
+import './Login.scss';
-export default function Login() {
- return <div>Hello, Hyeonze!</div>;
-}
+const Login = () => {
+ const [idInput, setIdInput] = useState('');
+ const [pwInput, setPwInput] = useState('');
+ const [isValidatedUser, setIsValidatedUser] = useState(false);
+
+ const navigate = useNavigate();
+ const changeIdInput = e => {
+ const { value } = e.target;
+ setIdInput(value);
+ };
+
+ const changePwInput = e => {
+ const { value } = e.target;
+ setPwInput(value);
+ };
+
+ useEffect(() => {
+ setIsValidatedUser(idInput.indexOf('@') !== -1 && pwInput.length > 4);
+ }, [idInput, pwInput]);
+
+ // ๋ฉ์ธ์ผ๋ก ์ด๋ํ ๋ ๋ก์ง
+ const goToMain = () => {
+ navigate('/main-hyeonze');
+ };
+
+ // ํ์๊ฐ์
์ ์ฌ์ฉํ ๋ก์ง
+ // const signup = () => {
+ // fetch('http://10.58.4.22:8000/users/signup', {
+ // method: 'POST',
+ // body: JSON.stringify({
+ // email: idInput,
+ // password: pwInput,
+ // }),
+ // })
+ // .then(response => response.json())
+ // .then(result => {
+ // //console.log('๊ฒฐ๊ณผ: ', result.message)
+ // if (result.message === 'EMAIL_ALREADY_EXISTS') {
+ // console.log('Error : Duplicated');
+ // }
+ // });
+ // };
+
+ // ๋ก๊ทธ์ธ์ ์ฌ์ฉํ ๋ก์ง
+ // const login = () => {
+ // fetch('http://10.58.4.22:8000/users/login', {
+ // method: 'POST',
+ // body: JSON.stringify({
+ // email: idInput,
+ // password: pwInput,
+ // }),
+ // })
+ // .then(response => response.json())
+ // .then(result => {
+ // //console.log('๊ฒฐ๊ณผ: ', result.message)
+ // if (result.message === 'SUCCESS') {
+ // console.log('login SUCCESS');
+ // }
+ // });
+ // };
+
+ return (
+ <div className="login">
+ <div id="wrapper">
+ <h1>westagram</h1>
+ <form className="login_form">
+ <input
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ className="username"
+ onChange={changeIdInput}
+ />
+ <input
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ className="userpassword"
+ onChange={changePwInput}
+ />
+ <input
+ className={isValidatedUser ? 'activated' : ''}
+ disabled={!isValidatedUser}
+ type="button"
+ value="๋ก๊ทธ์ธ"
+ onClick={goToMain}
+ />
+ </form>
+ <p>๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</p>
+ </div>
+ </div>
+ );
+};
+
+export default Login; | Unknown | [๊ณต์๋ฌธ์ React๋ก ์ฌ๊ณ ํ๊ธฐ](https://ko.reactjs.org/docs/thinking-in-react.html#step-3-identify-the-minimal-but-complete-representation-of-ui-state) ๋ฅผ ๋ณด์๋ฉด ์ด๋ค ๊ฐ๋ค์ด state๊ฐ ๋์ด์ผํ๋์ง์ ๋ํด ์ ํ์์ต๋๋ค. ๊ฐ๊ฐ ์ดํด๋ณด๊ณ ํด๋น ๋ฐ์ดํฐ๋ state๋ก ์ ์ ํ์ง ๋๊ธ๋ก ๋จ๊ฒจ์ฃผ์ธ์. ๊ฐ ๋ฐ์ดํฐ์ ๋ํด ์๋์ ์ธ ๊ฐ์ง ์ง๋ฌธ์ ํตํด ๊ฒฐ์ ํ ์ ์์ต๋๋ค
> 1. ๋ถ๋ชจ๋ก๋ถํฐ props๋ฅผ ํตํด ์ ๋ฌ๋ฉ๋๊น? ๊ทธ๋ฌ๋ฉด ํ์คํ state๊ฐ ์๋๋๋ค.
>
> 2. ์๊ฐ์ด ์ง๋๋ ๋ณํ์ง ์๋์? ๊ทธ๋ฌ๋ฉด ํ์คํ state๊ฐ ์๋๋๋ค.
>
> 3. ์ปดํฌ๋ํธ ์์ ๋ค๋ฅธ state๋ props๋ฅผ ๊ฐ์ง๊ณ ๊ณ์ฐ ๊ฐ๋ฅํ๊ฐ์? ๊ทธ๋ ๋ค๋ฉด state๊ฐ ์๋๋๋ค.
> |
@@ -1,5 +1,98 @@
import React from 'react';
+import { useState, useEffect } from 'react';
+import { useNavigate } from 'react-router-dom';
+import './Login.scss';
-export default function Login() {
- return <div>Hello, Hyeonze!</div>;
-}
+const Login = () => {
+ const [idInput, setIdInput] = useState('');
+ const [pwInput, setPwInput] = useState('');
+ const [isValidatedUser, setIsValidatedUser] = useState(false);
+
+ const navigate = useNavigate();
+ const changeIdInput = e => {
+ const { value } = e.target;
+ setIdInput(value);
+ };
+
+ const changePwInput = e => {
+ const { value } = e.target;
+ setPwInput(value);
+ };
+
+ useEffect(() => {
+ setIsValidatedUser(idInput.indexOf('@') !== -1 && pwInput.length > 4);
+ }, [idInput, pwInput]);
+
+ // ๋ฉ์ธ์ผ๋ก ์ด๋ํ ๋ ๋ก์ง
+ const goToMain = () => {
+ navigate('/main-hyeonze');
+ };
+
+ // ํ์๊ฐ์
์ ์ฌ์ฉํ ๋ก์ง
+ // const signup = () => {
+ // fetch('http://10.58.4.22:8000/users/signup', {
+ // method: 'POST',
+ // body: JSON.stringify({
+ // email: idInput,
+ // password: pwInput,
+ // }),
+ // })
+ // .then(response => response.json())
+ // .then(result => {
+ // //console.log('๊ฒฐ๊ณผ: ', result.message)
+ // if (result.message === 'EMAIL_ALREADY_EXISTS') {
+ // console.log('Error : Duplicated');
+ // }
+ // });
+ // };
+
+ // ๋ก๊ทธ์ธ์ ์ฌ์ฉํ ๋ก์ง
+ // const login = () => {
+ // fetch('http://10.58.4.22:8000/users/login', {
+ // method: 'POST',
+ // body: JSON.stringify({
+ // email: idInput,
+ // password: pwInput,
+ // }),
+ // })
+ // .then(response => response.json())
+ // .then(result => {
+ // //console.log('๊ฒฐ๊ณผ: ', result.message)
+ // if (result.message === 'SUCCESS') {
+ // console.log('login SUCCESS');
+ // }
+ // });
+ // };
+
+ return (
+ <div className="login">
+ <div id="wrapper">
+ <h1>westagram</h1>
+ <form className="login_form">
+ <input
+ type="text"
+ placeholder="์ ํ๋ฒํธ, ์ฌ์ฉ์ ์ด๋ฆ ๋๋ ์ด๋ฉ์ผ"
+ className="username"
+ onChange={changeIdInput}
+ />
+ <input
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ"
+ className="userpassword"
+ onChange={changePwInput}
+ />
+ <input
+ className={isValidatedUser ? 'activated' : ''}
+ disabled={!isValidatedUser}
+ type="button"
+ value="๋ก๊ทธ์ธ"
+ onClick={goToMain}
+ />
+ </form>
+ <p>๋น๋ฐ๋ฒํธ๋ฅผ ์์ผ์
จ๋์?</p>
+ </div>
+ </div>
+ );
+};
+
+export default Login; | Unknown | ๋ผ์ด๋ธ๋ฆฌ๋ทฐ ๋ ๋ง์๋๋ฆฐ ๊ฒ์ฒ๋ผ ์กฐ๊ฑด์ falsy, truthyํ ๊ฐ์ ์ด์ฉํด ๋ฆฌํฉํ ๋ง ํด์ฃผ์ธ์! :)
๋๋ state๋ฅผ ์ค์ผ ๊ฒฝ์ฐ ๋ถํ์ํ ์๋ ์๊ฒ ๋ค์ |
@@ -0,0 +1,66 @@
+@use '../../../styles/mixin.scss' as mixin;
+@use '../../../styles/color.scss' as clr;
+
+body {
+ background: clr.$bg-login;
+
+ .login {
+ position: relative;
+ top: -80px;
+
+ #wrapper {
+ @include mixin.flex($align: center);
+ position: relative;
+ flex-direction: column;
+ width: 700px;
+ height: 761px;
+ border: 1px solid clr.$clr-border;
+
+ h1 {
+ margin-top: 90px;
+ margin-bottom: 130px;
+ font-size: 81px;
+ font-family: 'Lobster', cursive;
+ }
+
+ .login_form {
+ input {
+ display: block;
+ width: 536px;
+ height: 76px;
+ margin-bottom: 12px;
+ padding-left: 10px;
+ background: #fafafa;
+ border: 1px solid clr.$clr-border;
+ border-radius: 3px;
+ font-size: 16px;
+ }
+
+ input[type='button'] {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 536px;
+ height: 60px;
+ margin-top: 16px;
+ background-color: clr.$clr-primary;
+ opacity: 0.5;
+ border: none;
+ border-radius: 4px;
+ font-size: 16px;
+ color: #fff;
+
+ &.activated {
+ opacity: 1;
+ }
+ }
+ }
+
+ p {
+ position: absolute;
+ bottom: 20px;
+ color: #043667;
+ }
+ }
+ }
+} | Unknown | ์ ์ฝ๋๋ ์ด๋์ ์์ฑ๋๋ฉด ์ข์๊น์? |
@@ -0,0 +1,43 @@
+span.comment {
+ padding-left: 10px;
+
+ small {
+ color: #a3a3a3;
+ }
+
+ &:first-child {
+ padding: 10px;
+ font-weight: bold;
+ }
+
+ svg {
+ &.delete {
+ display: none;
+ cursor: pointer;
+ }
+
+ &.hearts {
+ color: #a3a3a3;
+ position: absolute;
+ right: 20px;
+ transition: color 1s;
+ cursor: pointer;
+
+ path {
+ color: #a3a3a3;
+ }
+ }
+
+ &.liked {
+ path {
+ color: #f00;
+ }
+ }
+ }
+
+ &:hover svg {
+ &.delete {
+ display: inline-block;
+ }
+ }
+} | Unknown | ์์ฃผ ์ฌ์ฉ์ด ๋๋ ์ปฌ๋ฌ๊ฐ์ด๋ค์! ์ด๋ฐ ๊ฒฝ์ฐ sass variables ๊ธฐ๋ฅ์ ์ด์ฉํ๋๊ฒ์ ์ด๋จ๊น์? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.