code stringlengths 41 34.3k | lang stringclasses 8
values | review stringlengths 1 4.74k |
|---|---|---|
@@ -0,0 +1,8 @@
+package nextstep.member.application;
+
+import nextstep.member.domain.User;
+
+public interface UserDetailsService {
+
+ User loadUserByUsername(String email);
+} | Java | ๋ง๋ค๋ฉด์ ๋ฐฐ์ฐ๋ ํด๋ฆฐ์ํคํ
์ณ๋ฅผ ๋ณด๋ฉด ์๋น์ค์ ์ธํฐํ์ด์ค์ ๊ทธ ๊ตฌํ์ฒด๋ฅผ ๊ฐ์ด ๋๊ธฐ์ ๊ทธ๊ฒ ์ต์ํด์ member์ ๋์๋ค์ ใ
ใ
UserDetailService๋ฅผ auth์์๋ง ์ฌ์ฉํ์ง ์์ ์๋ ์๊ธฐ์ ๊ตฌํ์ฒด์ ๊ฐ์ด ๋๋๊ฒ ํ๋์ ๋ ๋ค์ด์ฌ ๊ฒ ๊ฐ์ต๋๋ค!
๋ฌผ๋ก ์ธํฐํ์ด์ค์ ๊ตฌํ์ฒด์ ๊ตฌ๋ถ์ ํด๋๋ก๋ผ๋ ํ๋ฉด ์ข์๋ฐ ๊ธํ๊ฒ ํ๋๋ผ... ๐ |
@@ -0,0 +1,83 @@
+package nextstep.subway.unit;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import nextstep.auth.authentication.AuthenticationToken;
+import nextstep.auth.authentication.LoginMember;
+import nextstep.auth.token.JwtTokenProvider;
+import nextstep.auth.token.TokenAuthenticationInterceptor;
+import nextstep.auth.token.TokenRequest;
+import nextstep.auth.token.TokenResponse;
+import nextstep.member.application.UserDetailsService;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.springframework.http.HttpStatus;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.mock.web.MockHttpServletResponse;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.BDDMockito.given;
+import static org.mockito.Mockito.when;
+
+@ExtendWith({MockitoExtension.class})
+class TokenAuthenticationInterceptorMockTest {
+ private static final String EMAIL = "email@email.com";
+ private static final String PASSWORD = "password";
+ public static final String JWT_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIiLCJuYW1lIjoiSm9obiBEb2UiLCJpYXQiOjE1MTYyMzkwMjJ9.ih1aovtQShabQ7l0cINw4k1fagApg3qLWiB8Kt59Lno";
+
+ @Mock
+ JwtTokenProvider jwtTokenProvider;
+
+ @Mock
+ UserDetailsService userDetailsService;
+
+ ObjectMapper mapper = new ObjectMapper();
+
+ @InjectMocks
+ TokenAuthenticationInterceptor interceptor;
+
+ @Test
+ void convert() throws IOException {
+ AuthenticationToken token = interceptor.convert(createMockRequest());
+
+ assertThat(token).isEqualTo(new AuthenticationToken(EMAIL, PASSWORD));
+ }
+
+ @Test
+ void authenticate() throws IOException {
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ when(jwtTokenProvider.createToken(any(), any())).thenReturn(JWT_TOKEN);
+
+ interceptor.authenticate(new LoginMember(EMAIL, PASSWORD, List.of()), response);
+
+ assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
+ assertThat(mapper.readValue(response.getContentAsString(), TokenResponse.class)).isEqualTo(new TokenResponse(JWT_TOKEN));
+ }
+
+ @Test
+ void preHandle() throws IOException {
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ given(userDetailsService.loadUserByUsername(any())).willReturn(new LoginMember(EMAIL, PASSWORD, List.of()));
+ given(jwtTokenProvider.createToken(any(), any())).willReturn(JWT_TOKEN);
+ boolean result = interceptor.preHandle(createMockRequest(), response, new Object());
+
+ assertThat(result).isFalse();
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
+ assertThat(response.getContentAsString()).isEqualTo(mapper.writeValueAsString(new TokenResponse(JWT_TOKEN)));
+ }
+
+ private MockHttpServletRequest createMockRequest() throws IOException {
+ MockHttpServletRequest request = new MockHttpServletRequest();
+ TokenRequest tokenRequest = new TokenRequest(EMAIL, PASSWORD);
+ request.setContent(mapper.writeValueAsString(tokenRequest).getBytes());
+
+ return request;
+ }
+} | Java | bool๋ง ํ์ธํ๊ธฐ์๋ ๋ถ์กฑํ๋ค๊ณ ์๊ฐํ๋๋ฐ ์ข๋ค์! ๊ฐ์ฌํฉ๋๋ค. |
@@ -10,7 +10,7 @@
import static org.assertj.core.api.Assertions.assertThat;
class MemberAcceptanceTest extends AcceptanceTest {
- public static final String EMAIL = "email@email.com";
+ public static final String EMAIL = "email2@email.com";
public static final String PASSWORD = "password";
public static final int AGE = 20;
@@ -67,10 +67,32 @@ void deleteMember() {
@DisplayName("ํ์ ์ ๋ณด๋ฅผ ๊ด๋ฆฌํ๋ค.")
@Test
void manageMember() {
+ // given
+ ExtractableResponse<Response> createResponse = ํ์_์์ฑ_์์ฒญ(EMAIL, PASSWORD, AGE);
+ String newEmail = "new@email.com";
+
+ // when
+ ExtractableResponse<Response> response = ํ์_์ ๋ณด_์์ _์์ฒญ(createResponse, newEmail, PASSWORD, AGE);
+ ExtractableResponse<Response> member = ํ์_์ ๋ณด_์กฐํ_์์ฒญ(createResponse);
+
+ // then
+ assertThat(response.statusCode()).isEqualTo(HttpStatus.OK.value());
+ assertThat(member.jsonPath().getString("email")).isEqualTo(newEmail);
}
@DisplayName("๋์ ์ ๋ณด๋ฅผ ๊ด๋ฆฌํ๋ค.")
@Test
void manageMyInfo() {
+ // given
+ ExtractableResponse<Response> createResponse = ํ์_์์ฑ_์์ฒญ(EMAIL, PASSWORD, AGE);
+ String newEmail = "new@email.com";
+
+ // when
+ ExtractableResponse<Response> response = ๋ฒ ์ด์ง_์ธ์ฆ์ผ๋ก_๋ด_ํ์_์ ๋ณด_์์ _์์ฒญ(EMAIL, PASSWORD, newEmail, PASSWORD, AGE);
+ ExtractableResponse<Response> member = ํ์_์ ๋ณด_์กฐํ_์์ฒญ(createResponse);
+
+ // then
+ assertThat(response.statusCode()).isEqualTo(HttpStatus.OK.value());
+ assertThat(member.jsonPath().getString("email")).isEqualTo(newEmail);
}
}
\ No newline at end of file | Java | ๋ตใ
ใ
์ข๋ ํ๊ธํ๊ฐ ๋ค์ด๊ฐ๋ฉด ์ข์ ๊ฒ ๊ฐ๊ตฐ์ |
@@ -0,0 +1,39 @@
+package nextstep.auth.authentication;
+
+import nextstep.member.application.UserDetailsService;
+import nextstep.member.domain.User;
+import org.springframework.web.servlet.HandlerInterceptor;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+public abstract class Authenticator implements HandlerInterceptor {
+
+ private final UserDetailsService userDetailsService;
+
+ public Authenticator(UserDetailsService userDetailsService) {
+ this.userDetailsService = userDetailsService;
+ }
+
+ @Override
+ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
+ AuthenticationToken token = convert(request);
+ User user = userDetailsService.loadUserByUsername(token.getPrincipal());
+
+ checkAuthentication(user, token.getCredentials());
+ authenticate(user, response);
+
+ return false;
+ }
+
+ abstract public AuthenticationToken convert(HttpServletRequest request) throws IOException;
+
+ abstract public void authenticate(User user, HttpServletResponse response) throws IOException;
+
+ private void checkAuthentication(User user, String password) {
+ if (!user.checkPassword(password)) {
+ throw new AuthenticationException();
+ }
+ }
+} | Java | ๋ฏธ์
์ `auth` ํจํค์ง ๋ด์ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ ์ธํ ๋น์ฆ๋์ค ํจํค์ง๋ค์ด ๋ค์ด์ค์ง ์์์ผ ์๋ฃ๋ฉ๋๋ค ๐ข
ํ์ฌ `auth` ํจํค์ง๊ฐ `member` ์ ์์กดํ๊ณ ์์ด์ |
@@ -1,9 +1,12 @@
-package nextstep.member.domain;
+package nextstep.auth.authentication;
+import nextstep.member.domain.Member;
+import nextstep.member.domain.User;
+
import java.util.List;
-public class LoginMember {
+public class LoginMember implements User {
private String email;
private String password;
private List<String> authorities; | Java | `LoginMember` ๋ฅผ ์ฎ๊ธฐ์์ง ์์์ ๋ฉ๋๋ค ๐ข |
@@ -0,0 +1,8 @@
+package nextstep.member.application;
+
+import nextstep.member.domain.User;
+
+public interface UserDetailsService {
+
+ User loadUserByUsername(String email);
+} | Java | ํด๋น ์ฑ
์์์ ๊ตฌํ์๋๋ ๋จ์ํ ์ธํฐํ์ด์ค์ ๊ตฌํ์ฒด๋ฅผ ๊ฐ์ ํจํค์ง์ ๋๋ ๊ฒ์ ์๋๋๋ค ๐
ํด๋ฆฐ ์ํคํ
์ฒ์์ ๋ก๋ฒํธ C.๋งํด์ ์๋์ ๊ฐ์ ์์ ๊ทธ๋ ค์ ์ค๋ช
ํ๋๋ฐ์.
์กฐ๊ธ ๋จ์ํํด์ ๋ง์๋๋ฆฌ๋ฉด ์ ์ธ๋ถ์ ๊ฐ์ฒด๋ง์ด ์ ๋ด๋ถ์ ๊ฐ์ฒด์ ์์กดํด์ผ ํ๋ค๋ ๊ฒ์ ์ฃผ์ฅํฉ๋๋ค.
๋ง์ํ์ ๋ง๋ค๋ฉด์ ๋ฐฐ์ฐ๋ ํด๋ฆฐ์ํคํ
์ฒ๋ `DIP`๋ฅผ ํตํด ์์กด์ฑ ๊ฒฉ๋ฆฌํ๊ธฐ ์ํด ์ธํฐํ์ด์ค๋ฅผ ๋๊ณ , ํด๋น ์ธํฐํ์ด์ค๋ฅผ ๋ด๋ถ์ ๊ฐ์ฒด๊ฐ ๊ตฌํํ๊ณ , ์ธ๋ถ์ ๊ฐ์ฒด๋ ๊ทธ ์ธํฐํ์ด์ค๋ฅผ `์ฌ์ฉ`ํจ์ผ๋ก์จ ์ธ๋ถ์ ๊ฐ์ฒด๊ฐ ๋ด๋ถ์ ์ค์ ๊ตฌํ๊ฐ์ฒด๋ฅผ ์์ง ๋ชปํ๊ฒ ๋๋ ์ญํ ์ ํฉ๋๋ค.
์ง๊ธ ๋ฏธ์
์์ ์๊ตฌํ๋ ๊ฒ๋ ์ฌ์ค์ `DIP` ๋ฅผ ํตํ ์์กด์ฑ ๊ฒฉ๋ฆฌ์
๋๋ค ๐
[์ฐธ๊ณ ](https://www.youtube.com/watch?v=dJ5C4qRqAgA&t=2941s) ์์์ ํตํด ๊ณต๋ถํด๋ณด์๋ฉด ์กฐ๊ธ ๋ ์ดํด๊ฐ ์ฌ์ฐ์ค ๊ฒ ๊ฐ์์ ๐ฅ
 |
@@ -0,0 +1,8 @@
+package nextstep.member.application;
+
+import nextstep.member.domain.User;
+
+public interface UserDetailsService {
+
+ User loadUserByUsername(String email);
+} | Java | ๋ค ๋ง์ํ์ ๋๋ก ์ ์ธ๋ถ์ ๊ฐ์ฒด๋ง์ด ์ ๋ด๋ถ์ ๊ฐ์ฒด๋ฅผ ์ฐธ์กฐํด์ผ ํ๋ค๋ ๊ฒ์ ๋์ํฉ๋๋ค.
๊ทธ๋ฐ๋ฐ ํ์ฌ ๊ตฌ์กฐ๋ก๋ ์์กด์ฑ ๊ฒฉ๋ฆฌ๊ฐ ์ถฉ๋ถํ ๋์ง ์์๋ค๋ ๋ง์์ผ๊น์? ํ์ฌ๋ member ๊ณผ auth๊ฐ์ usecase๋ฅผ ํตํด ํต์ ์ด ์ด๋ฃจ์ด์ง๊ณ ์๊ธฐ์, dip๋ฅผ ํตํด ๊ตฌํ์ฒด๋ ์ง์ ์ ์ผ๋ก ์ฐธ์กฐ๊ฐ ์ด๋ค์ง์ง ์๊ณ ์์ด์ usecase๋ฅผ ์ด๋์ ๋ ๊ฒ์ธ๊ฐ๋ ๋ถ์ฐจ์ ์ธ ๋ฌธ์ ๋ผ๊ณ ์๊ฐํ์ต๋๋ค. (๊ทธ๋์ ๊ทธ์ค ํ๋๋ก ๋ง๋ค๋ฉด์ ๋ฐฐ์ฐ๋ ํด๋ฆฐ์ํคํ
์ณ ๋ด์ฉ์ ์์๋ก ๋ ๊ฒ์ด๊ณ ์. ์ฒจ๋ถํด์ฃผ์ ์์์์๋ import๋ฌธ์ด ์กด์ฌํ๊ธฐ๋ง ํด๋ ์์กด๊ด๊ณ๊ฐ ์๋ค๊ณ ํ๋ค์!)
๋ฏธ์
์ด ๊ทธ๋ฐ ์๋ฏธ๋ผ๋ฉด ์์ ํ๋๊ฑด ๋ฌธ์ ์์ต๋๋ค๋ง ๊ถ๊ธํด์ ์ง๋ฌธ๋๋ฆฝ๋๋ค ใ
ใ
|
@@ -0,0 +1,8 @@
+package nextstep.member.application;
+
+import nextstep.member.domain.User;
+
+public interface UserDetailsService {
+
+ User loadUserByUsername(String email);
+} | Java | ํด๋ฆฐ์ํคํ
์ฒ๋ฅผ ์ธ๊ธํ๊ฑด ์์๋์ด ์๊ธฐํ์ ๋ถ๋ถ์ ๋ํด ์ถ๊ฐ์ ์ธ ์ธ๊ธ์ ๋๋ฆฌ๋ค๋ณด๋ ๊ทธ๋ ๊ฒ ๋์๋ค์ ๐
ํด๋ฆฐ์ํคํ
์ฒ์ ๋ด์ฉ์ด ๋จ์ํ ์ธํฐํ์ด์ค์ ๊ตฌํ์ฒด๋ฅผ ๊ฐ์ ํจํค์ง์ ๋๋ผ๋ ์๋ฏธ๋ ์๋๋ผ๊ณ ์๊ฐํด์ ์ฒจ์ธ์ ๋๋ ค๋ดค์ต๋๋ค
ํ์ฌ ๋ฏธ์
์ ๋ํด ์ด์ผ๊ธฐํ๋ฉด auth ์ member ์ ์ฑ์ง์ ๋ํด ๊ณ ๋ฏผํด๋ด์ผํ๋ ๋ฐ์.
`auth` ๋ ์ธ์ฆ/์ธ๊ฐ์ ๋ํ ์ฑ
์์ ๊ฐ์ง๋ `๋น์ฆ๋์ค ๊ท์น`๊ณผ๋ ์กฐ๊ธ ๋๋จ์ด์ง `๊ณตํต`์ ์ฑ์ง์ ์ง๋ ํจํค์ง๋ผ๊ณ ์๊ฐ๋ฉ๋๋ค
๋ฐ๋ฉด์ `member`๋ ์ด ์ ํ๋ฆฌ์ผ์ด์
๋ง์ `๋น์ฆ๋์ค ๊ท์น`์ ๋ด์์๋ ์๋ ์ฌ์ฉ์์ ๋ํ ํจํค์ง๋ผ๊ณ ๋ณผ ์ ์์ ๊ฒ ๊ฐ์์
์ด์ ๋ฐ๋ผ `auth` -> `member` ๋ก์ ์์กด์ฑ์ด ์๊ธฐ์ง ์๋๋ก ๊ด๋ฆฌํ๋ ๊ฒ์ด ๋๋ถ๋ถ์ ์ํฉ์์ ์ ๋ฆฌํ ๊ฑฐ๋ผ๊ณ ์๊ฐํฉ๋๋ค.
๋ํ ํ์ฌ๋ `MemberController` ๊ฐ `@AuthenticationPrincipal`๋ฅผ ์ฌ์ฉํ๊ณ , `LoginMember`๊ฐ `User`๋ฅผ ๊ตฌํํ๊ธฐ ๋๋ฌธ์ ํจํค์ง ๊ฐ์ ์ํ์ฐธ์กฐ๊ฐ ์๊ฒผ์ต๋๋ค.
์ด๋ฅผ ๋์ด๋ด๊ธฐ ์ํด `DIP`๋ฅผ ์ฌ์ฉํ๋ผ๊ณ ๋ง์ ๋๋ฆฐ ๊ฒ์ด์์ต๋๋ค. ๐
์ ๋ฆฌํ์๋ฉด, ๋ฏธ์
์ ์๋๋ `DIP`๋ฅผ ํตํด (๋ค๋ฅธ ๋ฐฉ๋ฒ์ด ์์ผ๋ฉด ์ฐ์
๋ ๋ฉ๋๋ค) ํจํค์ง๊ฐ ์ํ์ฐธ์กฐ๋ฅผ ๋์ด๋ด์ ์
๋๋ค.
์์์์ ๋ณด์ ๊ฒ๊ณผ ๊ฐ์ด auth ๋ member ๋ ์ค์ ํ๊ณณ์์๋ ๋ค๋ฅธ ํจํค์ง์ import ๊ฐ ์๋๋ก ์์ ํด๋ณด์๊ธธ ๋ฐ๋๋๋ค. |
@@ -0,0 +1,8 @@
+package nextstep.member.application;
+
+import nextstep.member.domain.User;
+
+public interface UserDetailsService {
+
+ User loadUserByUsername(String email);
+} | Java | ์์๋ฅผ ๋ค์ด์ฃผ์ ๋ง๋ค๋ฉด์ ๋ฐฐ์ฐ๋ ํด๋ฆฐ ์ํคํ
์ฒ์์๋ application ํจํค์ง์ ์ธํฐํ์ด์ค๋ฅผ adapter ์์ ๊ตฌํ ํ๋ ํํ๋ก ๊ฐ๋ฐ์ ํ๊ณ ์์ต๋๋ค. ์์กด์ฑ ๊ฒฉ๋ฆฌ๋ฅผ ์ํด `DIP`๋ฅผ ์ฌ์ฉํ๋ฉด ๊ฐ๋
์์ผ๋ก๋ ์ด๊ฒ ์ ๊ฒ ์ด์ผ๊ธฐ ํ ์ ์๊ฒ ์ง๋ง, ๊ฒฐ๊ตญ์ ๋ด๋ถ์ ๊ฐ์ฒด๋ค์ด ์ธ๋ถ์ ์์กดํ์ง ์๋๋ก ๋ง๋๋ ์ฌ๋ฌ๊ฐ์ง ๋ฐฉ๋ฒ๋ค์ด๋ผ๊ณ ์๊ฐํฉ๋๋ค ๐ |
@@ -0,0 +1,8 @@
+package nextstep.member.application;
+
+import nextstep.member.domain.User;
+
+public interface UserDetailsService {
+
+ User loadUserByUsername(String email);
+} | Java | > MemberControllerย ๊ฐย @AuthenticationPrincipal๋ฅผ ์ฌ์ฉํ๊ณ ,ย LoginMember๊ฐย User๋ฅผ ๊ตฌํํ๊ธฐ ๋๋ฌธ์ ํจํค์ง ๊ฐ์ ์ํ์ฐธ์กฐ๊ฐ ์๊ฒผ์ต๋๋ค.
์ฌ๊ธฐ์ ์ฐธ์กฐ๊ฐ ์๋ค๋๊ฑด ์๊ฐ๋ชปํ๋ค์! ๋ต ์์ ํ๊ฒ ์ต๋๋ค
> ์์๋ฅผ ๋ค์ด์ฃผ์ ๋ง๋ค๋ฉด์ ๋ฐฐ์ฐ๋ ํด๋ฆฐ ์ํคํ
์ฒ์์๋ application ํจํค์ง์ ์ธํฐํ์ด์ค๋ฅผ adapter ์์ ๊ตฌํ ํ๋ ํํ๋ก ๊ฐ๋ฐ์ ํ๊ณ ์์ต๋๋ค
๋ต ์ฒ์ ๋๊ธ์์ ๋ง์๋๋ ธ๋ฏ์ด `๋ฌผ๋ก ์ธํฐํ์ด์ค์ ๊ตฌํ์ฒด์ ๊ตฌ๋ถ์ ํด๋๋ก๋ผ๋ ํ๋ฉด ์ข์๋ฐ ๊ธํ๊ฒ ํ๋๋ผ...ย ๐` ๐ ์์ผ๋ก ์ฐธ๊ณ ํ๊ฒ ์ต๋๋ค. ์ง๊ธ๊น์ง ๊ธด ์ค๋ช
๊ฐ์ฌ๋๋ฆฝ๋๋ค! |
@@ -0,0 +1,8 @@
+package nextstep.member.application;
+
+import nextstep.member.domain.User;
+
+public interface UserDetailsService {
+
+ User loadUserByUsername(String email);
+} | Java | ์ ๋ ํ ๋ก ํ๋ฉฐ ์ฌ๋ฏธ์์์ต๋๋ค
[์ฐธ๊ณ ](https://github.com/wikibook/clean-architecture) ์ ์์ ์ ์์กด๊ด๊ณ๋ฅผ ์ง์ ๊ทธ๋ฆผ์ผ๋ก ๊ทธ๋ ค๋ณด์๋ฉด ๋ ์ข์ ์ธ์ฌ์ดํธ๋ฅผ ์ป์ผ ์ค ์ ์์๊ฒ ๊ฐ์์ ๐ |
@@ -0,0 +1,39 @@
+package nextstep.subway.unit;
+
+import nextstep.subway.applicaion.LineService;
+import nextstep.subway.applicaion.PathService;
+import nextstep.subway.applicaion.StationService;
+import nextstep.subway.domain.Station;
+import nextstep.subway.utils.TestObjectFactory;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+@ExtendWith(MockitoExtension.class)
+public class PathServiceMockTest {
+
+ @Mock
+ LineService lineService;
+
+ @Mock
+ StationService stationService;
+
+ @InjectMocks
+ PathService pathService;
+
+ TestObjectFactory testObjectFactory = new TestObjectFactory();
+
+ @Test
+ @DisplayName("์คํจ_์ถ๋ฐ์ญ๊ณผ ๋์ฐฉ์ญ์ด ๊ฐ์ ๊ฒฝ์ฐ")
+ void fail_same_start_end() {
+ Station ๊ฐ๋จ์ญ = testObjectFactory.์ญ์์ฑ("๊ฐ๋จ์ญ");
+ Station ์์ฌ์ญ = testObjectFactory.์ญ์์ฑ("์์ฌ์ญ");
+
+ assertThrows(IllegalArgumentException.class, () -> pathService.getPath(๊ฐ๋จ์ญ.getId(), ์์ฌ์ญ.getId()));
+ }
+} | Java | StationService์ createStationResponse ๋ฉ์๋๋ฅผ ๊ทธ๋๋ก ์ฌ์ฉํ๊ณ ์ถ์ด์, stationService๋ฅผ ๋ชจํนํ์ง ์๊ณ ๋ฐ๋ก ์์ฑํ๋๋ก ํ์๋๋ฐ์
@InjectMocks๋ ์ฌ์ฉํ ์ ์์ด ๋ถํธํ๊ณ , ํ
์คํธํ ๋์ ํ๋๋ง ์๋ณธ ํด๋์ค๋ฅผ ๊ฐ์ ธ๋ค ์ฐ๊ณ ๋๋จธ์ง๋ ๋ค ๋ชฉ์ผ๋ก ์งํํด์ผ ํ๋ค๋ ๋ชฉ ํ
์คํธ์ ์ด๋
(?) ์๋ ๋ง์ง ์๋ ๊ฒ ๊ฐ์ ๊ณ ๋ฏผ์ด ๋ฉ๋๋ค.
ํน์ ๋ค๋ฅธ ๊น๋ํ ํ
์คํธ ๋ฐฉ๋ฒ์ด๋ ๋ฆฌํฉํ ๋ง ๋ฐฉ๋ฒ์ด ์์๊น์? |
@@ -0,0 +1,39 @@
+package nextstep.subway.unit;
+
+import nextstep.subway.applicaion.LineService;
+import nextstep.subway.applicaion.PathService;
+import nextstep.subway.applicaion.StationService;
+import nextstep.subway.domain.Station;
+import nextstep.subway.utils.TestObjectFactory;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+@ExtendWith(MockitoExtension.class)
+public class PathServiceMockTest {
+
+ @Mock
+ LineService lineService;
+
+ @Mock
+ StationService stationService;
+
+ @InjectMocks
+ PathService pathService;
+
+ TestObjectFactory testObjectFactory = new TestObjectFactory();
+
+ @Test
+ @DisplayName("์คํจ_์ถ๋ฐ์ญ๊ณผ ๋์ฐฉ์ญ์ด ๊ฐ์ ๊ฒฝ์ฐ")
+ void fail_same_start_end() {
+ Station ๊ฐ๋จ์ญ = testObjectFactory.์ญ์์ฑ("๊ฐ๋จ์ญ");
+ Station ์์ฌ์ญ = testObjectFactory.์ญ์์ฑ("์์ฌ์ญ");
+
+ assertThrows(IllegalArgumentException.class, () -> pathService.getPath(๊ฐ๋จ์ญ.getId(), ์์ฌ์ญ.getId()));
+ }
+} | Java | ์ฃผ๋ก ์ง๊ธ๊ณผ ๊ฐ์ด layered ์ํคํ
์ฒ์์๋ application(service) layer๋ domain ๊ฐ์ฒด๋ค์ ์กฐํฉํ๋ ์ญํ ์ ํ๋๋ฐ์,
์ง๊ธ ์ฝ๋์์๋ ์๋ต Response ๊ฐ์ฒด๋ฅผ ์์ฑํ๋ ์ญํ ๋ํ service๊ฐ ๊ฐ๊ณ ์์ด์ injectํด์ผํ๋ ๋ฌธ์ ๊ฐ ์๊ธฐ๋ ๊ฒ ๊ฐ์์.
mock testing ๋ฐฉ์์ ์ฌ์ฉํ์ ๋ ํฌ๊ฒ ๋๊ปด์ง๋ ๋จ์ ์ค ํ๋๋ ์์กดํ๋ ๊ฐ์ฒด๊ฐ ๋ง์ผ๋ฉด ๋ง์์ง์๋ก ํ
์คํธ ์์ฑ์ด ๊น๋ค๋ก์์ง๋ค๋ ๊ฑฐ์์.
(when, thenReturn์ ํด์ผํ๋ ๋ด๋ถ ๊ตฌํ ์์ฒด๋ฅผ ์ง์ ์ ์ผ๋ก ์์์ผ๊ฒ ์ฃ )
๊ทธ๋ฐ ์ ์์ service๋ผ๋ฆฌ ์์กด์ ํด์ผ๋๋ ๊ฒฝ์ฐ์ ์์กดํ๋ ค๋ service์์ ํ์๋ก ํ๋ ๊ธฐ๋ฅ์ด ์ ๋ง service์ ์์ด์ผํ ๊น๋ฅผ ์๊ฐํด๋ณด์๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค :)
์ง๊ธ์ ๊ฒฝ์ฐ๋ Response ๊ฐ์ฒด๋ฅผ ๋ง๋๋๊ฑธ Response ๊ฐ์ฒด๋ก ๋๊ฒจ์ฃผ์ด๋ ๋ ๊ฒ ๊ฐ์ต๋๋ค :)
(static factory method ๋ฑ์ ํ์ฉํ ์ ์์ ๊ฒ ๊ฐ๋ค์!) |
@@ -0,0 +1,134 @@
+package nextstep.subway.acceptance;
+
+import io.restassured.response.ExtractableResponse;
+import io.restassured.response.Response;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.springframework.http.HttpStatus;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import static nextstep.subway.acceptance.LineSteps.์งํ์ฒ _๋
ธ์ _์์ฑ_์์ฒญ;
+import static nextstep.subway.acceptance.LineSteps.์งํ์ฒ _๋
ธ์ ์_์งํ์ฒ _๊ตฌ๊ฐ_์์ฑ_์์ฒญ;
+import static nextstep.subway.acceptance.PathSteps.๊ฒฝ๋ก_์กฐํ;
+import static nextstep.subway.acceptance.StationSteps.์งํ์ฒ ์ญ_์์ฑ_์์ฒญ;
+import static org.assertj.core.api.Assertions.assertThat;
+
+@DisplayName("๊ฒฝ๋ก ๊ธฐ๋ฅ")
+class PathAcceptanceTest extends AcceptanceTest {
+ private Long ์ ๋ถ๋น์ ;
+ private Long ๊ตฌํธ์ ;
+ private Long ๊ฐ๋จ์ญ;
+ private Long ์์ฌ์ญ;
+
+ private Long ์ ๋
ผํ์ญ;
+
+ private Long ๊ณ ์ํฐ๋ฏธ๋์ญ;
+
+
+ /**
+ * /์ ๋ถ๋น์ /
+ * |
+ * /๊ตฌํธ์ / - ๊ฐ๋จ์ญ - ์ ๋
ผํ์ญ - ๊ณ ์ํฐ๋ฏธ๋์ญ
+ * |
+ * ์์ฌ์ญ
+ */
+
+ /**
+ * Given ์งํ์ฒ ์ญ๊ณผ ๋
ธ์ ์์ฑ์ ์์ฒญ ํ๊ณ
+ */
+ @BeforeEach
+ public void setUp() {
+ super.setUp();
+
+ ๊ฐ๋จ์ญ = ์งํ์ฒ ์ญ_์์ฑ_์์ฒญ("๊ฐ๋จ์ญ").jsonPath().getLong("id");
+ ์์ฌ์ญ = ์งํ์ฒ ์ญ_์์ฑ_์์ฒญ("์์ฌ์ญ").jsonPath().getLong("id");
+ ์ ๋
ผํ์ญ = ์งํ์ฒ ์ญ_์์ฑ_์์ฒญ("์ ๋
ผํ์ญ").jsonPath().getLong("id");
+ ๊ณ ์ํฐ๋ฏธ๋์ญ = ์งํ์ฒ ์ญ_์์ฑ_์์ฒญ("๊ณ ์ํฐ๋ฏธ๋์ญ").jsonPath().getLong("id");
+
+ Map<String, String> lineCreateParams = createLineCreateParams(๊ฐ๋จ์ญ, ์์ฌ์ญ);
+ ์ ๋ถ๋น์ = ์งํ์ฒ _๋
ธ์ _์์ฑ_์์ฒญ(lineCreateParams).jsonPath().getLong("id");
+ ์งํ์ฒ _๋
ธ์ ์_์งํ์ฒ _๊ตฌ๊ฐ_์์ฑ_์์ฒญ(์ ๋ถ๋น์ , createSectionCreateParams(๊ฐ๋จ์ญ, ์์ฌ์ญ));
+ ์งํ์ฒ _๋
ธ์ ์_์งํ์ฒ _๊ตฌ๊ฐ_์์ฑ_์์ฒญ(์ ๋ถ๋น์ , createSectionCreateParams(์ ๋
ผํ์ญ, ๊ฐ๋จ์ญ));
+
+ Map<String, String> line9CreateParams = createLineCreateParams(๊ณ ์ํฐ๋ฏธ๋์ญ, ์ ๋
ผํ์ญ);
+ ๊ตฌํธ์ = ์งํ์ฒ _๋
ธ์ _์์ฑ_์์ฒญ(line9CreateParams).jsonPath().getLong("id");
+ }
+
+ /**
+ * When ์งํ์ฒ ๊ฒฝ๋ก๋ฅผ ์์ฒญํ๋ฉด
+ * Then ๊ฒฝ๋ก๊ฐ ๋ฆฌํด๋๋ค
+ */
+ @DisplayName("์งํ์ฒ ๊ฒฝ๋ก ์์ฒญ")
+ @Test
+ void getPath() {
+ // when
+ ExtractableResponse<Response> response = ๊ฒฝ๋ก_์กฐํ(์์ฌ์ญ, ๊ณ ์ํฐ๋ฏธ๋์ญ);
+
+ // then
+ assertThat(response.statusCode()).isEqualTo(HttpStatus.OK.value());
+ assertThat(response.jsonPath().getList("stations.id", Long.class)).containsExactly(์์ฌ์ญ, ๊ฐ๋จ์ญ, ์ ๋
ผํ์ญ, ๊ณ ์ํฐ๋ฏธ๋์ญ);
+ }
+
+ /**
+ * Given ๋
๋ฆฝ์ ์ธ ์๋ก์ด ์งํ์ฒ ๋
ธ์ ์ ์์ฑํ๊ณ
+ * When ๋
๋ฆฝ๋ ๋
ธ์ ๊ณผ ๊ธฐ์กด ๋
ธ์ ๊ฐ ๊ฒฝ๋ก๋ฅผ ์์ฒญํ๋ช
+ * Then 400์๋ฌ๊ฐ ๋ฐ์ํ๋ค.
+ */
+ @DisplayName("๋
๋ฆฝ๋ ๋
ธ์ ์์ฒญ์ ์คํจ")
+ @Test
+ void fail_noPathExists() {
+ // given
+ Long ๋๋ฆผ์ญ = ์งํ์ฒ ์ญ_์์ฑ_์์ฒญ("๋๋ฆผ์ญ").jsonPath().getLong("id");
+ Long ๊ตฌ๋์ญ = ์งํ์ฒ ์ญ_์์ฑ_์์ฒญ("๊ตฌ๋์ญ").jsonPath().getLong("id");
+
+ Map<String, String> lineCreateParams = createLineCreateParams(๊ตฌ๋์ญ, ๋๋ฆผ์ญ);
+ Long ์ดํธ์ = ์งํ์ฒ _๋
ธ์ _์์ฑ_์์ฒญ(lineCreateParams).jsonPath().getLong("id");
+
+ // when
+ ExtractableResponse<Response> response = ๊ฒฝ๋ก_์กฐํ(๊ฐ๋จ์ญ, ๊ตฌ๋์ญ);
+
+ // then
+ assertThat(response.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST.value());
+ }
+
+ /**
+ * When ์กด์ฌํ์ง ์๋ ์ญ์ ์์ฒญํ๋ฉด
+ * Then 400์๋ฌ๊ฐ ๋ฐ์ํ๋ค.
+ */
+ @DisplayName("์กด์ฌํ์ง ์๋ ์ญ ๊ฒฝ๋ก ์์ฒญ์ ์คํจ")
+ @Test
+ void fail_noStationExists() {
+ // given
+ Long ๋๋ฆผ์ญ = ์งํ์ฒ ์ญ_์์ฑ_์์ฒญ("๋๋ฆผ์ญ").jsonPath().getLong("id");
+ Long ์กด์ฌํ์ง_์๋_์ญ = 9999L;
+
+
+ // when
+ ExtractableResponse<Response> response = ๊ฒฝ๋ก_์กฐํ(๋๋ฆผ์ญ, ์กด์ฌํ์ง_์๋_์ญ);
+
+ // then
+ assertThat(response.statusCode()).isEqualTo(HttpStatus.NOT_FOUND.value());
+ }
+
+ private Map<String, String> createLineCreateParams(Long upStationId, Long downStationId) {
+ Map<String, String> lineCreateParams;
+ lineCreateParams = new HashMap<>();
+ lineCreateParams.put("name", "์ ๋ถ๋น์ ");
+ lineCreateParams.put("color", "bg-red-600");
+ lineCreateParams.put("upStationId", upStationId + "");
+ lineCreateParams.put("downStationId", downStationId + "");
+ lineCreateParams.put("distance", 10 + "");
+ return lineCreateParams;
+ }
+
+ private Map<String, String> createSectionCreateParams(Long upStationId, Long downStationId) {
+ Map<String, String> params = new HashMap<>();
+ params.put("upStationId", upStationId + "");
+ params.put("downStationId", downStationId + "");
+ params.put("distance", 6 + "");
+ return params;
+ }
+} | Java | ๊ณต๊ฐ๊ณผ ๊ด๋ จ๋ ์๊ณ ๋ฆฌ์ฆ์ ํ
์คํธ๋ฅผ ํ๊ธฐ ๋๋ฌธ์
๋์ค์ ์์ ์ด ๋ณด๊ฑฐ๋ ๋ค๋ฅธ ๊ฐ๋ฐ์๊ฐ ์ด ํ
์คํธ ์ฝ๊ณ ํ์
ํ๊ธฐ๊ฐ ํ๋ค ์ ์์ ๊ฒ ๊ฐ์ต๋๋ค.

์ด๋ฒ ๋จ๊ณ ์์์ ์๋ ๊ฒ ์ฒ๋ผ ์ฃผ์์ผ๋ก ํฝ์ค์ณ๋ฅผ ์ค๋ช
ํด์ฃผ๋ฉด ๋์ค์ ๋ค์ ๋ณด์์ ๋๋ ์ฝ๊ฒ ํ
์คํธ๋ฅผ ํ์
ํ ์ ์์ ๊ฒ ๊ฐ์ต๋๋ค :) |
@@ -0,0 +1,39 @@
+package nextstep.subway.unit;
+
+import nextstep.subway.applicaion.LineService;
+import nextstep.subway.applicaion.PathService;
+import nextstep.subway.applicaion.StationService;
+import nextstep.subway.domain.Station;
+import nextstep.subway.utils.TestObjectFactory;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+@ExtendWith(MockitoExtension.class)
+public class PathServiceMockTest {
+
+ @Mock
+ LineService lineService;
+
+ @Mock
+ StationService stationService;
+
+ @InjectMocks
+ PathService pathService;
+
+ TestObjectFactory testObjectFactory = new TestObjectFactory();
+
+ @Test
+ @DisplayName("์คํจ_์ถ๋ฐ์ญ๊ณผ ๋์ฐฉ์ญ์ด ๊ฐ์ ๊ฒฝ์ฐ")
+ void fail_same_start_end() {
+ Station ๊ฐ๋จ์ญ = testObjectFactory.์ญ์์ฑ("๊ฐ๋จ์ญ");
+ Station ์์ฌ์ญ = testObjectFactory.์ญ์์ฑ("์์ฌ์ญ");
+
+ assertThrows(IllegalArgumentException.class, () -> pathService.getPath(๊ฐ๋จ์ญ.getId(), ์์ฌ์ญ.getId()));
+ }
+} | Java | ์ถ๊ฐ์ ์ผ๋ก ์์ธ ์ํฉ์ ๋ํด์ ํ
์คํธ๋ฅผ ํด์ฃผ์๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค!

๋์ ์ ์ง๊ธ๊ณผ ๊ฐ์ด service layer์ ๋น์ฆ๋์ค ๋ก์ง์ด ๋ค์ด๊ฐ๊ฒ ๋๋ฉด ํ
์คํธ ํด๋ด์ ์์๊ฒ ์ง๋ง
service์์ ํ์ํ (test double์ด๋ ์ค์ ๊ฐ์ฒด๋ )์์กด์ฑ์ด ๊ฐ์ถฐ์ง ์ํ์์ ํ
์คํธ๋ฅผ ํด์ผํ๋ ํ
์คํธ ์์ฑ์ด ๋ฒ๊ฑฐ๋กญ๊ฑฐ๋ ๊น๋ค๋ก์์ง๋๋ฐ์.
์ฒซ๋ฒ์งธ ๋จ๊ณ์ ์๊ตฌ์ฌํญ์ ํตํด ๊ฒฝํํ์
จ๋ฏ, `๊ธธ ์ฐพ๊ธฐ`์ ๋ํ `๋๋ฉ์ธ ๊ฐ์ฒด`๋ฅผ ๋ง๋ค์ด์ ๋จ์ ํ
์คํธ๋ฅผ ํด๋ณด์๋๊ฑด ์ด๋จ๊น์? :) |
@@ -0,0 +1,39 @@
+package nextstep.subway.unit;
+
+import nextstep.subway.applicaion.LineService;
+import nextstep.subway.applicaion.PathService;
+import nextstep.subway.applicaion.StationService;
+import nextstep.subway.domain.Station;
+import nextstep.subway.utils.TestObjectFactory;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+@ExtendWith(MockitoExtension.class)
+public class PathServiceMockTest {
+
+ @Mock
+ LineService lineService;
+
+ @Mock
+ StationService stationService;
+
+ @InjectMocks
+ PathService pathService;
+
+ TestObjectFactory testObjectFactory = new TestObjectFactory();
+
+ @Test
+ @DisplayName("์คํจ_์ถ๋ฐ์ญ๊ณผ ๋์ฐฉ์ญ์ด ๊ฐ์ ๊ฒฝ์ฐ")
+ void fail_same_start_end() {
+ Station ๊ฐ๋จ์ญ = testObjectFactory.์ญ์์ฑ("๊ฐ๋จ์ญ");
+ Station ์์ฌ์ญ = testObjectFactory.์ญ์์ฑ("์์ฌ์ญ");
+
+ assertThrows(IllegalArgumentException.class, () -> pathService.getPath(๊ฐ๋จ์ญ.getId(), ์์ฌ์ญ.getId()));
+ }
+} | Java | ํด๋น ๋ฆฌ๋ทฐ๋ฅผ ๋ฐ์ํ๋ฉด์
`์ถ๋ฐ์ญ๊ณผ ๋์ฐฉ์ญ์ด ์ฐ๊ฒฐ์ด ๋์ด ์์ง ์์ ๊ฒฝ์ฐ` ์ ๋ํด pathService ์๋น์ค ๋ ์ด์ด mock ํ
์คํธ๋ฅผ ์ง๋๋ฐ,
์ด๋ฅผ pathService์์ ํ
์คํธํ๋ ค๋ stationService๋ฅผ ๋ชฉ์ฒ๋ฆฌํด๋ฌ์, ํ
์คํธ๋ฅผ ์ง๋ ค๋ฉด stationService.findById์์ ์๋ฌ๋ฅผ ๋์ง๋๋ก ๋ชฉ ํ
์คํธ๋ฅผ ์งํํด์ผ ํ์ต๋๋ค. ํ์ง๋ง, ์ด๋ ์ฝ๋์ ๋ํ ํ
์คํธ๋ฅผ ์ง๊ธฐ๋ณด๋ค๋ ํ
์คํธ๋ฅผ ์ํ ํ
์คํธ๋ผ๋ ์๊ฐ์ด ๋ค์ด์ ๊ฒฐ๊ตญ ์ด ๊ฒฝ์ฐ๋ ์ค์ ๊ฐ์ฒด ํ
์คํธ์์ ์งํํด์ผ ํ๋๋ฐ์.
์ด์ ๊ฐ์ ๊ฒฝ์ฐ๋ ์ ๊ฐ ํ ๊ฒ์ฒ๋ผ mockํ
์คํธ๋ฅผ ํผํ๋๊ฒ ๋ง๋ ๊ฒ์ธ์ง? ์๋๋ฉด ๋ค๋ฅธ ๋ฐฉ๋ฒ์ด ์๋์ง ๊ถ๊ธํฉ๋๋ค! |
@@ -0,0 +1,39 @@
+package nextstep.subway.unit;
+
+import nextstep.subway.applicaion.LineService;
+import nextstep.subway.applicaion.PathService;
+import nextstep.subway.applicaion.StationService;
+import nextstep.subway.domain.Station;
+import nextstep.subway.utils.TestObjectFactory;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+@ExtendWith(MockitoExtension.class)
+public class PathServiceMockTest {
+
+ @Mock
+ LineService lineService;
+
+ @Mock
+ StationService stationService;
+
+ @InjectMocks
+ PathService pathService;
+
+ TestObjectFactory testObjectFactory = new TestObjectFactory();
+
+ @Test
+ @DisplayName("์คํจ_์ถ๋ฐ์ญ๊ณผ ๋์ฐฉ์ญ์ด ๊ฐ์ ๊ฒฝ์ฐ")
+ void fail_same_start_end() {
+ Station ๊ฐ๋จ์ญ = testObjectFactory.์ญ์์ฑ("๊ฐ๋จ์ญ");
+ Station ์์ฌ์ญ = testObjectFactory.์ญ์์ฑ("์์ฌ์ญ");
+
+ assertThrows(IllegalArgumentException.class, () -> pathService.getPath(๊ฐ๋จ์ญ.getId(), ์์ฌ์ญ.getId()));
+ }
+} | Java | @sang-eun
๋ค๋ค mock์ ์ฌ์ฉํ ํ
์คํ
์ ๊ฒฝ์ฐ ์์กดํ๋ ๊ฐ์ฒด๋ฅผ ๋งค๋ฒ ์ค์ ์ ํ๋ ๊ฒ์ด ๋งค์ฐ ๋ฒ๊ฑฐ๋กญ์ฃ ...!
๊ทธ๋์ ์ฒซ๋ฒ์งธ ๋จ๊ณ์์ ์๊ธฐ๋๋ ธ๋ฏ์ด ์ ๋ fake ๊ฐ์ฒด๋ฅผ ์ฌ์ฉํ๋ ๊ฑธ ์ ํธํ๋ ํธ์
๋๋ค!
์ง๊ธ๊ณผ ๊ฐ์ ๊ฒฝ์ฐ ๊ธธ์ ์ฐพ๋ ์ญํ ์ ๊ฐ๋ ๊ฐ์ฒด๋ฅผ ๋ฐ๋ก ๋ง๋ ๋ค๋ฉด ์ข ๋ ๊ฐ๋ฒผ์ด ํ
์คํ
์ด ๊ฐ๋ฅํ ๊ฒ ๊ฐ์ต๋๋ค!
(์ด๋ฏธ `Path` ๊ฐ์ฒด์์ ์ฒ๋ฆฌํ๋๋ก ํ์
จ๋ค์ ๐ ) |
@@ -0,0 +1,32 @@
+package nextstep.subway.exception;
+
+import nextstep.subway.auth.application.AuthorizationException;
+import org.springframework.dao.DataIntegrityViolationException;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.RestControllerAdvice;
+
+@RestControllerAdvice
+public class GlobalExceptionAdvisor {
+
+ @ExceptionHandler({IllegalArgumentException.class})
+ public ResponseEntity handleIllegalArgsException(Exception e) {
+ return ResponseEntity.badRequest().build();
+ }
+
+ @ExceptionHandler({RuntimeException.class})
+ public ResponseEntity handleRuntimeException(Exception e) {
+ return ResponseEntity.badRequest().build();
+ }
+
+ @ExceptionHandler(AuthorizationException.class)
+ public ResponseEntity handleAuthorizationException(Exception e) {
+ return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
+ }
+
+ @ExceptionHandler(DataIntegrityViolationException.class)
+ public ResponseEntity handleIllegalArgsException(DataIntegrityViolationException e) {
+ return ResponseEntity.badRequest().build();
+ }
+} | Java | ๊ณตํต ์์ธ ์ฒ๋ฆฌ ์ข์ต๋๋ค. ๐ |
@@ -0,0 +1,50 @@
+package nextstep.subway.fare.domain;
+
+import java.util.Arrays;
+
+public enum DiscountPolicy {
+ ADULT(19, 500, 0, 0),
+ TEENAGER(13, 19, 350, 0.2),
+ CHILD(6, 13, 350, 0.5),
+ INFANT(0, 6, 0, 1);
+
+ private int ageStart;
+ private final int ageEnd;
+ private final int minusFare;
+ private final double discountRatio;
+
+ DiscountPolicy(int ageStart, int ageEnd, int minusFare, double discountRatio) {
+
+ this.ageStart = ageStart;
+ this.ageEnd = ageEnd;
+ this.minusFare = minusFare;
+ this.discountRatio = discountRatio;
+ }
+
+ public int getDiscount(int fare) {
+ if (fare < 0) {
+ throw new IllegalArgumentException();
+ }
+ double discounted = (fare - this.minusFare) * (1 - this.discountRatio);
+ return (int) discounted;
+ }
+
+ public static DiscountPolicy getPolicy(int age) {
+ return Arrays.stream(values()).filter(
+ policy -> policy.isMatch(age)
+ ).findFirst()
+ .orElseThrow(IllegalArgumentException::new);
+ }
+
+ public int getAgeStart() {
+ return ageStart;
+ }
+
+ public int getAgeEnd() {
+ return ageEnd;
+ }
+
+ public boolean isMatch(int age) {
+ return getAgeStart() <= age && age < getAgeEnd();
+ }
+} | Java | ๋์ด์ ๋ฐ๋ฅธ ํ ์ธ ์๊ธ ๊ณ์ฐ ๋ก์ง ์ ๊ตฌํํด์ฃผ์
จ์ต๋๋ค. ๐
`ageStart`, `ageEnd`๋ ์ถฉ๋ถํ ๋ฌด์จ ์ญํ ์ ํ๋์ง ์ ์ ์๋ ์ด๋ฆ์ธ๋ฐ, ๋น๊ต์ ์ฌ์ฉ๋๋๊น ์ด์/์ด๊ณผ, ์ดํ/๋ฏธ๋ง ๊ตฌ๋ถ์ ์ํด `ageMinInclusive`, ageMaxExclusive`์ ๊ฐ์ด ์์ ํด๋ณด์
๋ ์ข๊ฒ ์ต๋๋ค. |
@@ -0,0 +1,50 @@
+package nextstep.subway.fare.domain;
+
+import java.util.Arrays;
+
+public enum DiscountPolicy {
+ ADULT(19, 500, 0, 0),
+ TEENAGER(13, 19, 350, 0.2),
+ CHILD(6, 13, 350, 0.5),
+ INFANT(0, 6, 0, 1);
+
+ private int ageStart;
+ private final int ageEnd;
+ private final int minusFare;
+ private final double discountRatio;
+
+ DiscountPolicy(int ageStart, int ageEnd, int minusFare, double discountRatio) {
+
+ this.ageStart = ageStart;
+ this.ageEnd = ageEnd;
+ this.minusFare = minusFare;
+ this.discountRatio = discountRatio;
+ }
+
+ public int getDiscount(int fare) {
+ if (fare < 0) {
+ throw new IllegalArgumentException();
+ }
+ double discounted = (fare - this.minusFare) * (1 - this.discountRatio);
+ return (int) discounted;
+ }
+
+ public static DiscountPolicy getPolicy(int age) {
+ return Arrays.stream(values()).filter(
+ policy -> policy.isMatch(age)
+ ).findFirst()
+ .orElseThrow(IllegalArgumentException::new);
+ }
+
+ public int getAgeStart() {
+ return ageStart;
+ }
+
+ public int getAgeEnd() {
+ return ageEnd;
+ }
+
+ public boolean isMatch(int age) {
+ return getAgeStart() <= age && age < getAgeEnd();
+ }
+} | Java | ์์ธ๋ฅผ ๋ฐ์์ํฌ ๋ ์์ธ ๋ด์ฉ, ๋๋ฒ๊น
์ ํ์ํ ๊ฐ์ ๋ฉ์์ง๋ก ํจ๊ป ์ ๋ฌํ์๋ฉด, ๋ฌธ์ ์ํฉ์์ ์์ธ ์ถ์ ์ด ์์ํด์ ์ข์ต๋๋ค. :) |
@@ -0,0 +1,42 @@
+package nextstep.subway.fare.domain;
+
+import java.util.Arrays;
+
+public enum DistanceExtraFare {
+ NEAR(10, 50, 100, 5),
+ FAR(50, 500, 100, 8);
+
+ private final int distanceStart;
+ private final int distanceEnd;
+ private final int fare;
+ private final int unitDistanceInKiloMeter;
+
+ DistanceExtraFare(int distanceStart, int distanceEnd, int fare, int unitDistanceInKiloMeter) {
+
+ this.distanceStart = distanceStart;
+ this.distanceEnd = distanceEnd;
+ this.fare = fare;
+ this.unitDistanceInKiloMeter = unitDistanceInKiloMeter;
+ }
+
+ public static int calculate(int distance) {
+ return Arrays.stream(values())
+ .map(distanceExtraFare -> distanceExtraFare.calculateBy(distance))
+ .reduce(Integer::sum)
+ .orElse(0);
+ }
+
+ private int calculateBy(int distance) {
+ if (distance <= this.distanceStart) {
+ return 0;
+ }
+ if (distance > this.distanceEnd) {
+ distance = this.distanceEnd;
+ }
+ return ((distance - this.distanceStart) / this.unitDistanceInKiloMeter) * this.fare;
+ }
+
+ public int getFare() {
+ return this.fare;
+ }
+} | Java | 16km๋ฅผ ๊ฐ๋ ๊ฒฝ์ฐ ์ถ๊ฐ ์๊ธ์ ((16 - 10) / 5) * 100 = 100์์ด ๋ ๊ฒ ๊ฐ์์!
์ฐธ๊ณ ๋งํฌ์ ์๋ ๊ฐ๊ณผ ๊ฒฐ๊ณผ๊ฐ ๋ค๋ฅธ ๊ฒ ๊ฐ์ต๋๋ค.
> http://www.seoulmetro.co.kr/kr/page.do?menuIdx=354
๋ฏธ์
ํ์ด์ง์ ์๋ ์์ ์ฌ์ฉํด์ ์ถ๊ฐ ์๊ธ์ ๊ณ์ฐํด๋ณด์๋ฉด ์ข๊ฒ ์ต๋๋ค. :)
> https://edu.nextstep.camp/s/urD8knTu/ls/4r6iyUcO |
@@ -0,0 +1,44 @@
+package nextstep.subway.fare.domain;
+
+import java.util.Objects;
+
+public class Fare {
+ private static final int basicFare = 1250;
+
+ private int fare;
+ private final DiscountPolicy discountPolicy;
+
+ private Fare(int fare, DiscountPolicy discountPolicy) {
+ this.fare = fare;
+ this.discountPolicy = discountPolicy;
+ }
+
+ public static Fare of(DiscountPolicy discountPolicy) {
+ return new Fare(Fare.basicFare, discountPolicy);
+ }
+
+ public static Fare of(int fare, DiscountPolicy discountPolicy) {
+ return new Fare(fare, discountPolicy);
+ }
+
+ public Fare plus(int fare) {
+ return Fare.of(this.fare + fare, this.discountPolicy);
+ }
+
+ public int discount() {
+ return this.discountPolicy.getDiscount(this.fare);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Fare fare1 = (Fare) o;
+ return fare == fare1.fare && discountPolicy == fare1.discountPolicy;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(fare, discountPolicy);
+ }
+} | Java | ๊ฐ ๊ฐ์ฒด ์ฌ์ฉ ์ข์ต๋๋ค. ๐
๊ณ ๋ฏผํด๋ณด์๋ฉด ์ข์ ๊ฒ ๊ฐ์ ๋ถ๋ถ์, `Fare` ํด๋์ค๋ฅผ ์ฌ์ฉํ๋ ์ฌ๋์ด `plus`, `discount` ์์๋ฅผ ์ ์๊ณ ํธ์ถํด์ผ ์๊ธ ๊ณ์ฐ์ด ์ ์์ ์ผ๋ก ๋ ๊ฒ ๊ฐ์์. ๊ทธ๋ฆฌ๊ณ , ํ ์ธ ์ ์ฑ
์ ์์ฑํ๋ ์์ ์ ๋ฐ์ง๋ง, ์ค์ ๋ก๋ ์ถ๊ฐ ์๊ธ ๊ณ์ฐ์ด ๋๋ ํ ์ฌ์ฉ์ด ๋์ด์ผ ํ๋ค์.
์๊ธ ๊ณ์ฐ์ `FareCalculator`๊ฐ ๋ด๋นํ๋ ๊ฒ์ผ๋ก ๋ณด์ด๋, `DiscountPolicy`๋ฅผ ์๊ธ ๊ณ์ฐ ๋ฉ์๋์์ ๊ด๋ฆฌํด๋ณด์
๋ ์ข๊ฒ ์ต๋๋ค. :) |
@@ -17,12 +17,11 @@
import java.util.stream.Collectors;
@Service
-@Transactional(readOnly = true)
+@Transactional
public class FavoriteService {
private final String MESSAGE_FAVORITE_ENTITY_NOT_FOUND = "์ฆ๊ฒจ์ฐพ๊ธฐ๊ฐ๊ฐ ์กด์ฌํ์ง ์์ต๋๋ค";
-
private FavoriteRepository favoriteRepository;
private MemberService memberService;
private StationService stationService;
@@ -42,7 +41,7 @@ public FavoriteResponse saveFavorite(Long memberId, FavoriteRequest favoriteRequ
Long sourceStationId = favoriteRequest.getSourceId();
Long targetStationId = favoriteRequest.getTargetId();
- checkSourceTargetHasPath(sourceStationId, targetStationId);
+ checkSourceTargetHasPath(memberId, sourceStationId, targetStationId);
Favorite favorite = saveFavoriteEntity(memberId, sourceStationId, targetStationId);
return FavoriteResponse.of(favorite);
@@ -55,10 +54,11 @@ private Favorite saveFavoriteEntity(Long memberId, Long sourceStationId, Long ta
return favoriteRepository.save(new Favorite(member, sourceStation, targetStation));
}
- private void checkSourceTargetHasPath(Long sourceStationId, Long targetStationId) {
- pathService.findShortestPath(sourceStationId, targetStationId);
+ private void checkSourceTargetHasPath(Long memberId, Long sourceStationId, Long targetStationId) {
+ pathService.findShortestPath(memberId, sourceStationId, targetStationId);
}
+ @Transactional(readOnly = true)
public List<FavoriteResponse> findFavorites(Long memberId) {
Member member = findMember(memberId);
List<Favorite> favorites = favoriteRepository.findByMemberId(member.getId()); | Java | ์ต๋จ ๊ฒฝ๋ก๋ฅผ ์กฐํํ๋ ๋ฉ์๋๊ฐ ์๊ธ ๊ณ์ฐ๋ ํ๊ธฐ ๋๋ฌธ์ `memberId`๊ฐ ํ์ํ๊ฒ ๋ ๊ฑธ๊น์?
๊ฒฝ๋ก ์กฐํ์ ์๊ธ ๊ณ์ฐ์ ๋ถ๋ฆฌํด๋ด๋ ์ข์ ๊ฒ ๊ฐ๋ค์! :) |
@@ -1,14 +1,16 @@
package nextstep.subway.path.application;
import nextstep.subway.line.domain.Section;
+import nextstep.subway.path.domain.SectionEdge;
+import nextstep.subway.path.domain.ShortestPath;
import nextstep.subway.station.domain.Station;
-import org.jgrapht.graph.DefaultWeightedEdge;
+import org.jgrapht.GraphPath;
import org.jgrapht.graph.WeightedMultigraph;
import java.util.List;
public class PathFinder {
- private final WeightedMultigraph<Station, DefaultWeightedEdge> graph;
+ private final WeightedMultigraph<Station, SectionEdge> graph;
private PathFindAlgorithm algorithm;
private PathFinder(List<Section> allSections, PathFindAlgorithm algorithm) {
@@ -17,13 +19,13 @@ private PathFinder(List<Section> allSections, PathFindAlgorithm algorithm) {
}
- private WeightedMultigraph<Station, DefaultWeightedEdge> makeGraph(final List<Section> allSections) {
- WeightedMultigraph<Station, DefaultWeightedEdge> graph = new WeightedMultigraph<>(DefaultWeightedEdge.class);
+ private WeightedMultigraph<Station, SectionEdge> makeGraph(final List<Section> allSections) {
+ WeightedMultigraph<Station, SectionEdge> graph = new WeightedMultigraph<>(SectionEdge.class);
allSections.forEach(
section -> {
graph.addVertex(section.getUpStation());
graph.addVertex(section.getDownStation());
- graph.setEdgeWeight(graph.addEdge(section.getUpStation(), section.getDownStation()), section.getDistance());
+ graph.addEdge(section.getUpStation(), section.getDownStation(), SectionEdge.of(section));
}
);
return graph;
@@ -34,6 +36,11 @@ public static PathFinder of(List<Section> allSections, PathFindAlgorithm algorit
}
public List<Station> find(Station departStation, Station destStation) {
- return algorithm.findShortestPath(graph, departStation, destStation);
+ return algorithm.findShortestPathStations(graph, departStation, destStation);
+ }
+
+ public ShortestPath getShortestGraph(Station departStation, Station destStation) {
+ GraphPath<Station, SectionEdge> shortestPathGraph = algorithm.getShortestPathGraph(graph, departStation, destStation);
+ return ShortestPath.of(shortestPathGraph);
}
} | Java | ์ฌ์ฉ์ฒ๊ฐ ์์ด์ง ๊ฒ ๊ฐ์ผ๋, ์ด ๋ฉ์๋๋ฅผ ํฌํจํด `PathFindAlgorithm`์ `findShortestPathStations`๋ฅผ ์ญ์ ํ์๋ฉด ์ข๊ฒ ์ต๋๋ค. :) |
@@ -1,8 +1,12 @@
package nextstep.subway.path.application;
+import nextstep.subway.fare.domain.FareCalculator;
import nextstep.subway.line.domain.Section;
import nextstep.subway.line.domain.SectionRepository;
import nextstep.subway.line.dto.PathResponse;
+import nextstep.subway.member.application.MemberService;
+import nextstep.subway.member.domain.Member;
+import nextstep.subway.path.domain.ShortestPath;
import nextstep.subway.station.application.StationService;
import nextstep.subway.station.domain.Station;
import org.springframework.stereotype.Service;
@@ -20,22 +24,30 @@ public class PathService {
private final StationService stationService;
private final SectionRepository sectionRepository;
-
private final PathFindAlgorithm pathFinder;
+ private final MemberService memberService;
- public PathService(StationService stationService, SectionRepository sectionRepository, PathFindAlgorithm pathFinder) {
+ public PathService(StationService stationService, SectionRepository sectionRepository, PathFindAlgorithm pathFinder,
+ MemberService memberService) {
this.stationService = stationService;
this.sectionRepository = sectionRepository;
this.pathFinder = pathFinder;
+ this.memberService = memberService;
}
- public PathResponse findShortestPath(Long source, Long target) {
+ public PathResponse findShortestPath(Long loginId, Long source, Long target) {
validateInput(source, target);
Station departStation = stationService.findStationById(source);
Station destStation = stationService.findStationById(target);
List<Section> allSections = sectionRepository.findAll();
- return PathResponse.from(PathFinder.of(allSections, pathFinder).find(departStation, destStation));
+ ShortestPath shortestGraph = PathFinder.of(allSections, this.pathFinder)
+ .getShortestGraph(departStation, destStation);
+
+ Member memberEntity = memberService.findMemberEntity(loginId);
+ int fare = FareCalculator.calculate(shortestGraph.getPathDistance(),
+ shortestGraph.getMaxLineFare(), memberEntity.getAge());
+ return PathResponse.from(shortestGraph, fare);
}
private static void validateInput(Long sourceStationId, Long targetStationId) {
@@ -46,5 +58,4 @@ private static void validateInput(Long sourceStationId, Long targetStationId) {
throw new IllegalArgumentException(MESSAGE_SOURCE_TARGET_SHOULD_BE_DIFFERENT);
}
}
-
} | Java | ๊ฒฝ๋ก ๊ณ์ฐํ๋ ๋ถ๋ถ๊ณผ ์๊ธ ๊ณ์ฐํ๋ ๋ก์ง์ ์ ๋ถ๋ฆฌํ ์ ์๊ฒ ๊ตฌํํ์ ๊ฒ์ผ๋ก ๋ณด์ฌ์.
์ค์ ๋ก ๋ด๋นํ๋ ํด๋์ค๋ฅผ ๋๋ ๋ณด๋ฉด ์ด๋จ๊น์? `FavoriteService` ์์๋ ๊ฒฝ๋ก๊ฐ ์กด์ฌํ๋์ง๋ง ํ์ธํ๋ฉด ๋๋ ์ฌ์ฌ์ฉ๋ ์ข ๋ ํจ์จ์ ์ผ๋ก ํ ์ ์์ ๊ฒ ๊ฐ๋ค์! |
@@ -1,14 +1,13 @@
package nextstep.subway.path.ui;
+import nextstep.subway.auth.domain.AuthenticationPrincipal;
+import nextstep.subway.auth.domain.LoginMember;
import nextstep.subway.line.dto.PathResponse;
-import nextstep.subway.member.dto.MemberRequest;
-import nextstep.subway.member.dto.MemberResponse;
import nextstep.subway.path.application.PathService;
import org.springframework.http.ResponseEntity;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.*;
-
-import java.net.URI;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
@RestController
public class PathController {
@@ -20,18 +19,10 @@ public PathController(PathService service) {
@GetMapping("/paths")
public ResponseEntity<PathResponse> findShortestPath(
- @RequestParam("source") Long source,
- @RequestParam("target") Long target) {
- PathResponse response = service.findShortestPath(source, target);
+ @AuthenticationPrincipal LoginMember loginMember,
+ @RequestParam("source") Long source,
+ @RequestParam("target") Long target) {
+ PathResponse response = service.findShortestPath(loginMember.getId(), source, target);
return ResponseEntity.ok(response);
}
-
- @ExceptionHandler({IllegalArgumentException.class})
- public ResponseEntity handleIllegalArgsException(Exception e) {
- return ResponseEntity.badRequest().build();
- }
- @ExceptionHandler({RuntimeException.class})
- public ResponseEntity handleRuntimeException(Exception e) {
- return ResponseEntity.badRequest().build();
- }
} | Java | ๋ก๊ทธ์ธํ์ง ์์ ๊ฒฝ์ฐ์๋ ๊ฒฝ๋ก๋ฅผ ์กฐํํ ์ ์์ด์ผ ํ ๊ฒ ๊ฐ์์.
์ด๋ฅผ ์ํด AuthenticationPrincipal์ ์ธ์ฆ์ด ํ์ํ์ง ์ฌ๋ถ ํ๋๋ฅผ ์ถ๊ฐํ๊ณ , ์ด๋ฅผ ํตํด ์ธ์ฆ์ ํ์ง ์์ ํ์๋ ์ฌ์ฉํ ์ ์๋ ๊ธฐ๋ฅ(๊ฒฝ๋ก ์กฐํ ๋ฑ)๊ณผ ์ธ์ฆ์ ํด์ผ๋ง ์ฌ์ฉํ ์ ์๋ ๊ธฐ๋ฅ(ํ์ ์ ๋ณด ๋ณ๊ฒฝ ๋ฑ)์์ ๋ชจ๋ LoginMember๋ฅผ ์ด์ฉํ ์ ์๋๋ก ๊ด๋ฆฌํด๋ณด์๋ฉด ์ข๊ฒ ์ต๋๋ค.
> https://edu.nextstep.camp/s/urD8knTu/ls/4r6iyUcO
"/paths ์์ฒญ ์ LoginMember ๊ฐ์ฒด ์ฒ๋ฆฌ" ๋ถ๋ถ์ ์ฐธ๊ณ ๋ถํ๋๋ฆฝ๋๋ค. |
@@ -0,0 +1,47 @@
+import { FollowUserType, followList } from '@/types/types';
+import axios from 'axios';
+import { SetterOrUpdater } from 'recoil';
+
+const PER_PAGE = 100;
+export const getFollowingList = async (setFollowings: SetterOrUpdater<followList[]>, tokenValue: string) => {
+ try {
+ const followingData = await axios.get(`${process.env.NEXT_PUBLIC_BASE_URL}/user/following?per_page=${PER_PAGE}`, {
+ headers: {
+ Accept: 'application/vnd.github+json',
+ Authorization: `Bearer ${tokenValue}`,
+ },
+ });
+
+ const data = followingData.data;
+
+ const followingList = data.map((user: FollowUserType) => {
+ const { id, login, avatar_url } = user;
+ return { id, login, avatar_url };
+ });
+
+ setFollowings(followingList);
+ } catch {
+ console.error('error');
+ }
+};
+
+export const getFollowerList = async (setFollowers: SetterOrUpdater<followList[]>, tokenValue: string) => {
+ try {
+ const followerData = await axios.get(`${process.env.NEXT_PUBLIC_BASE_URL}/user/followers?per_page=${PER_PAGE}`, {
+ headers: {
+ Accept: 'application/vnd.github+json',
+ Authorization: `Bearer ${tokenValue}`,
+ },
+ });
+ const data = followerData.data;
+
+ const followerList = data.map((user: FollowUserType) => {
+ const { id, login, avatar_url } = user;
+ return { id, login, avatar_url };
+ });
+
+ setFollowers(followerList);
+ } catch {
+ console.error('error');
+ }
+}; | TypeScript | ํ๋ก์์ด 100๋ช
์ด ๋์ผ๋ฉด ํน์ ์ด๋ป๊ฒ ๋๋์? |
@@ -0,0 +1,47 @@
+import { FollowUserType, followList } from '@/types/types';
+import axios from 'axios';
+import { SetterOrUpdater } from 'recoil';
+
+const PER_PAGE = 100;
+export const getFollowingList = async (setFollowings: SetterOrUpdater<followList[]>, tokenValue: string) => {
+ try {
+ const followingData = await axios.get(`${process.env.NEXT_PUBLIC_BASE_URL}/user/following?per_page=${PER_PAGE}`, {
+ headers: {
+ Accept: 'application/vnd.github+json',
+ Authorization: `Bearer ${tokenValue}`,
+ },
+ });
+
+ const data = followingData.data;
+
+ const followingList = data.map((user: FollowUserType) => {
+ const { id, login, avatar_url } = user;
+ return { id, login, avatar_url };
+ });
+
+ setFollowings(followingList);
+ } catch {
+ console.error('error');
+ }
+};
+
+export const getFollowerList = async (setFollowers: SetterOrUpdater<followList[]>, tokenValue: string) => {
+ try {
+ const followerData = await axios.get(`${process.env.NEXT_PUBLIC_BASE_URL}/user/followers?per_page=${PER_PAGE}`, {
+ headers: {
+ Accept: 'application/vnd.github+json',
+ Authorization: `Bearer ${tokenValue}`,
+ },
+ });
+ const data = followerData.data;
+
+ const followerList = data.map((user: FollowUserType) => {
+ const { id, login, avatar_url } = user;
+ return { id, login, avatar_url };
+ });
+
+ setFollowers(followerList);
+ } catch {
+ console.error('error');
+ }
+}; | TypeScript | Github API ์์๋ [API ๋ฒ์ ๋์ ์ํด ํค๋์ API ๋ฒ์ ์ ๋ณด๋ฅผ ํฌํจ์์ผ ์์ฒญ](https://docs.github.com/en/rest/about-the-rest-api/api-versions?apiVersion=2022-11-28)ํ๋ ๊ฒ์ ๊ถ์ฅํ๊ณ ์์ด์. ์ด๋ฅผ ์ถ๊ฐํด์ฃผ๋๊ฒ ์ข์ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,47 @@
+import { FollowUserType, followList } from '@/types/types';
+import axios from 'axios';
+import { SetterOrUpdater } from 'recoil';
+
+const PER_PAGE = 100;
+export const getFollowingList = async (setFollowings: SetterOrUpdater<followList[]>, tokenValue: string) => {
+ try {
+ const followingData = await axios.get(`${process.env.NEXT_PUBLIC_BASE_URL}/user/following?per_page=${PER_PAGE}`, {
+ headers: {
+ Accept: 'application/vnd.github+json',
+ Authorization: `Bearer ${tokenValue}`,
+ },
+ });
+
+ const data = followingData.data;
+
+ const followingList = data.map((user: FollowUserType) => {
+ const { id, login, avatar_url } = user;
+ return { id, login, avatar_url };
+ });
+
+ setFollowings(followingList);
+ } catch {
+ console.error('error');
+ }
+};
+
+export const getFollowerList = async (setFollowers: SetterOrUpdater<followList[]>, tokenValue: string) => {
+ try {
+ const followerData = await axios.get(`${process.env.NEXT_PUBLIC_BASE_URL}/user/followers?per_page=${PER_PAGE}`, {
+ headers: {
+ Accept: 'application/vnd.github+json',
+ Authorization: `Bearer ${tokenValue}`,
+ },
+ });
+ const data = followerData.data;
+
+ const followerList = data.map((user: FollowUserType) => {
+ const { id, login, avatar_url } = user;
+ return { id, login, avatar_url };
+ });
+
+ setFollowers(followerList);
+ } catch {
+ console.error('error');
+ }
+}; | TypeScript | ์ด๋ฐ ๋ฐฉ๋ฒ๋ ์์ด์!
```suggestion
const { data } = followingData;
``` |
@@ -0,0 +1,47 @@
+import { FollowUserType, followList } from '@/types/types';
+import axios from 'axios';
+import { SetterOrUpdater } from 'recoil';
+
+const PER_PAGE = 100;
+export const getFollowingList = async (setFollowings: SetterOrUpdater<followList[]>, tokenValue: string) => {
+ try {
+ const followingData = await axios.get(`${process.env.NEXT_PUBLIC_BASE_URL}/user/following?per_page=${PER_PAGE}`, {
+ headers: {
+ Accept: 'application/vnd.github+json',
+ Authorization: `Bearer ${tokenValue}`,
+ },
+ });
+
+ const data = followingData.data;
+
+ const followingList = data.map((user: FollowUserType) => {
+ const { id, login, avatar_url } = user;
+ return { id, login, avatar_url };
+ });
+
+ setFollowings(followingList);
+ } catch {
+ console.error('error');
+ }
+};
+
+export const getFollowerList = async (setFollowers: SetterOrUpdater<followList[]>, tokenValue: string) => {
+ try {
+ const followerData = await axios.get(`${process.env.NEXT_PUBLIC_BASE_URL}/user/followers?per_page=${PER_PAGE}`, {
+ headers: {
+ Accept: 'application/vnd.github+json',
+ Authorization: `Bearer ${tokenValue}`,
+ },
+ });
+ const data = followerData.data;
+
+ const followerList = data.map((user: FollowUserType) => {
+ const { id, login, avatar_url } = user;
+ return { id, login, avatar_url };
+ });
+
+ setFollowers(followerList);
+ } catch {
+ console.error('error');
+ }
+}; | TypeScript | try catch ๋ฌธ์ ์ผ๋ฐ์ ์ผ๋ก ์๋ฌ ์ํฉ์์ ์๋ฌ๋ฅผ ๋ณต๊ตฌํด ์ ์ ๋์์ ์ํค๊ฑฐ๋, ๋ก๊น
ํ๋ ์ฉ๋๋ก ์ฌ์ฉ๋ผ์. ๊ทธ๋ฐ๋ฐ ํ์ฌ์ ๊ฐ์ด ํน๋ณํ ๋ชฉ์ ์ด ์์ง ์๋ try catch ๋ฌธ์ ์คํ๋ ค ๋๋ฒ๊ทธํ ๋ ์์ฒญ ํท๊ฐ๋ฆฌ๊ฒ ๋ ์ ์์ด ๊ถ์ฅํ์ง ์์์. |
@@ -0,0 +1,47 @@
+import { FollowUserType, followList } from '@/types/types';
+import axios from 'axios';
+import { SetterOrUpdater } from 'recoil';
+
+const PER_PAGE = 100;
+export const getFollowingList = async (setFollowings: SetterOrUpdater<followList[]>, tokenValue: string) => {
+ try {
+ const followingData = await axios.get(`${process.env.NEXT_PUBLIC_BASE_URL}/user/following?per_page=${PER_PAGE}`, {
+ headers: {
+ Accept: 'application/vnd.github+json',
+ Authorization: `Bearer ${tokenValue}`,
+ },
+ });
+
+ const data = followingData.data;
+
+ const followingList = data.map((user: FollowUserType) => {
+ const { id, login, avatar_url } = user;
+ return { id, login, avatar_url };
+ });
+
+ setFollowings(followingList);
+ } catch {
+ console.error('error');
+ }
+};
+
+export const getFollowerList = async (setFollowers: SetterOrUpdater<followList[]>, tokenValue: string) => {
+ try {
+ const followerData = await axios.get(`${process.env.NEXT_PUBLIC_BASE_URL}/user/followers?per_page=${PER_PAGE}`, {
+ headers: {
+ Accept: 'application/vnd.github+json',
+ Authorization: `Bearer ${tokenValue}`,
+ },
+ });
+ const data = followerData.data;
+
+ const followerList = data.map((user: FollowUserType) => {
+ const { id, login, avatar_url } = user;
+ return { id, login, avatar_url };
+ });
+
+ setFollowers(followerList);
+ } catch {
+ console.error('error');
+ }
+}; | TypeScript | ํ์ฌ ์ด๋ ๊ฒ recoil ์ setter ๋ฅผ ๋ฐ์ ์ฌ์ฉํ๋๋ก ๋์ด์๋ ์ํฉ์์๋ ์์์์ ํญ์ recoil๊ณผ ํจ๊ป ์ฌ์ฉํด์ผ ํ๋ ์์กด์ฑ์ด ์๊ฒจ์ ํจ์์ ์ฌ์ฉ ๋ฐฉ์์ด ํน์ ๋ฐฉ๋ฒ์ผ๋ก ๊ฐ์ ๋ผ์. ๊ทธ๋ฐ๋ฐ ๊ทธ๋ด ํ์๊ฐ ์์๊น์? ๋ง์ฝ recoil์ด ์๋ useState๋ฅผ ์ฌ์ฉํ๋๋ก ๋ณ๊ฒฝ๋๋ค๋ฉด ์ด๋ป๊ฒ ๋ ๊น์?
๊ทธ๋ฆฌ๊ณ ์ด ํจ์๋ ํ๋ฒ์ ๋ ๊ฐ์ง ์ผ์ ํ๊ณ ์์ด์.
1. ์๋ฒ์์ ํ๋ก์ ๋ชฉ๋ก์ ๋ถ๋ฌ์จ๋ค.
2. Follower ์ํ์ ๊ฐ์ ์ค์ ํ๋ค.
getFollowerList ํจ์๋ฅผ ์๋ฒ์์ ํ๋ก์ ๋ชฉ๋ก์ ๋ถ๋ฌ์ค๋ ์ญํ ๋ง ํ๊ฒ ํ๊ณ , ๊ฐ ์ค์ ์ ์ด ํจ์๋ฅผ ์ฌ์ฉํ๋ ์ชฝ์์ ํ๋ฉด ์ด ํจ์๋ฅผ ๋ ์ ์ฐํ๊ฒ ์ฌ์ฉํ ์ ์์ด์.
```suggestion
export const getFollowerList = async (setFollowers: SetterOrUpdater<followList[]>, tokenValue: string) => {
const followerData = await axios.get(`${process.env.NEXT_PUBLIC_BASE_URL}/user/followers?per_page=${PER_PAGE}`, {
headers: {
Accept: 'application/vnd.github+json',
Authorization: `Bearer ${tokenValue}`,
},
});
const data = followerData.data;
const followerList = data.map((user: FollowUserType) => {
const { id, login, avatar_url } = user;
return { id, login, avatar_url };
});
return followerList;
};
``` |
@@ -0,0 +1,35 @@
+'use client';
+
+import FollowList from '@/components/checkfollow/FollowList';
+import { useRecoilValue, useSetRecoilState } from 'recoil';
+import FollowOrNotBtn from '../../components/checkfollow/FollowOrNotBtn';
+import Profile from '../../components/checkfollow/Profile';
+import { putFollowList } from '@/apis/putFollowList';
+import { followState, inputToken, loginClick } from '@/recoil/atoms';
+
+export default function CheckFollow() {
+ const loginClickState = useRecoilValue(loginClick);
+ const inputTokenValue = useRecoilValue(inputToken);
+ const setFollowState = useSetRecoilState(followState);
+
+ async function handleFllow(username: string) {
+ const success = await putFollowList(username, inputTokenValue);
+ if (success) {
+ setFollowState('follow');
+ window.location.reload();
+ }
+ }
+
+ return (
+ <article className="flex flex-col px-[25px] py-[37px]">
+ <Profile />
+ <FollowOrNotBtn />
+ <FollowList />
+ <button
+ onClick={() => handleFllow(loginClickState)}
+ className="mt-[34px] h-[45px] rounded-[5px] border-2 border-solid border-grey02 bg-sub01 text-title01 text-white hover:bg-grey02">
+ ๋งํํ๊ธฐ
+ </button>
+ </article>
+ );
+} | Unknown | ํ์ด์ง๋ฅผ ์ ์ฒด ์๋ก๊ณ ์นจํ๋ฉด ํฐ ์ฑ๋ฅ์์ ์ด์๊ฐ ์์ ๊ฒ ๊ฐ์๋ฐ, ํน์ ์ด๋ ๊ฒ ํ ์ด์ ๊ฐ ๋ฌด์์ผ๊น์? |
@@ -0,0 +1,89 @@
+'use client';
+
+import { getFollowerList, getFollowingList } from '@/apis/getFollowList';
+import { checkState, followState, followerList, followingList, inputToken, loginClick } from '@/recoil/atoms';
+import { followList } from '@/types/types';
+import { useEffect } from 'react';
+import { useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil';
+import ListElement from './ListElement';
+
+export default function FollowList() {
+ const [followers, setFollowers] = useRecoilState(followerList);
+ const [followings, setFollowings] = useRecoilState(followingList);
+ const followBtnState = useRecoilValue(followState);
+ const setCheckState = useSetRecoilState(checkState);
+ const inputTokenValue = useRecoilValue(inputToken);
+ const [loginClickState, setLoginClickState] = useRecoilState(loginClick);
+
+ useEffect(() => {
+ getFollowingList(setFollowings, inputTokenValue);
+ getFollowerList(setFollowers, inputTokenValue);
+ }, []);
+
+ const followerID = followers.map(user => user.id);
+ const followingID = followings.map(user => user.id);
+
+ const followEachOther = followings.filter(user => {
+ return followerID.includes(user.id) && user;
+ });
+
+ const notFollowEachOther = followers.filter(user => {
+ return !followingID.includes(user.id) && user;
+ });
+
+ const onClickCheck = () => {
+ setCheckState(true);
+ };
+
+ const onClickRemove = () => {
+ setCheckState(false);
+ };
+
+ useEffect(() => {
+ onClickRemove();
+ }, [followBtnState]);
+
+ function handleClickLogin(login: string) {
+ setLoginClickState(prevlogin => (prevlogin === login ? ' ' : login));
+ }
+
+ useEffect(() => {
+ console.log(loginClickState);
+ }, [loginClickState, setLoginClickState]);
+
+ return (
+ <section className="commonBackground flex h-[480px] w-full flex-col">
+ <div className="flex justify-end gap-[14px] px-[25px] py-[20px]">
+ <button
+ className="commonButton h-[25px] w-[65px] bg-white text-black hover:bg-red hover:text-white"
+ onClick={onClickCheck}>
+ โ๏ธ ๋ชจ๋ ์ ํ
+ </button>
+ <button
+ className="commonButton h-[25px] w-[65px] bg-white text-black hover:bg-red hover:text-white"
+ onClick={onClickRemove}>
+ ๋ชจ๋ ํด์ง
+ </button>
+ </div>
+ <div className="flex h-[350px] w-[340px] flex-col gap-[20px] overflow-scroll py-[5px]">
+ {followBtnState === 'follow'
+ ? followEachOther.map((user: followList) => {
+ const { id, login, avatar_url } = user;
+ return <ListElement key={id} id={id} login={login} avatar_url={avatar_url} />;
+ })
+ : notFollowEachOther.map((user: followList) => {
+ const { id, login, avatar_url } = user;
+ return (
+ <ListElement
+ onClick={() => handleClickLogin(login)}
+ key={id}
+ id={id}
+ login={login}
+ avatar_url={avatar_url}
+ />
+ );
+ })}
+ </div>
+ </section>
+ );
+} | Unknown | ์ํ์ useEffect๋ฅผ ์ฌ์ฉํ๋ฉด ์ ํํ ์ธ์ useEffect ์์ชฝ์ด ํธ์ถ๋๋์ง ์ถ์ ํ๊ธฐ ํ๋ ๋ฌธ์ ๊ฐ ์์ด์.
์ด ๊ฒฝ์ฐ์๋ [๊ณต์ ๋ฌธ์์์ ์ ์ํ๋ ๊ฒ](https://react.dev/learn/you-might-not-need-an-effect#sharing-logic-between-event-handlers) ์ฒ๋ผ ๋ก์ง์ follow ๋ฒํผ์ด ์ ํ๋๋ ๊ณณ์ผ๋ก ์ฎ๊ธฐ๋ ๊ฒ์ด ์ข์ ๊ฒ ๊ฐ์์. |
@@ -0,0 +1,27 @@
+'use client';
+
+import { followState } from '@/recoil/atoms';
+import { useSetRecoilState } from 'recoil';
+
+export default function FollowOrNotBtn() {
+ const setBtnState = useSetRecoilState(followState);
+
+ const onClickFollow = () => {
+ setBtnState('follow');
+ };
+
+ const onClickNotFollow = () => {
+ setBtnState('not');
+ };
+
+ return (
+ <section className="flex justify-center gap-[50px] px-[65px] py-[15px]">
+ <button className=" filteringFollowButton" onClick={onClickFollow}>
+ ๋งํํ ์ฌ๋
+ </button>
+ <button className=" filteringFollowButton" onClick={onClickNotFollow}>
+ ๋งํ ์๋ ์ฌ๋
+ </button>
+ </section>
+ );
+} | Unknown | ์ฌ๊ธฐ์๋ FollowOrNotBtn ์ปดํฌ๋ํธ๊ฐ onChange ๋ฑ์ ํ๋กญ์ผ๋ก ์์ ์ปดํฌ๋ํธ์ ์ํ ๋ณ๊ฒฝ์ ์๋ฆฌ๊ณ , ํด๋น ์ปดํฌ๋ํธ์์ ์ฒ๋ฆฌํ๋๋ก ๋ณ๊ฒฝํ๋๊ฒ ์ข์ ๊ฒ ๊ฐ์์.
๊ด๋ จ๋ PR: https://github.com/SimSimS-ToyProject-TEAM3/SimSimS-ToyProject-TEAM3/pull/24#discussion_r1436797019 |
@@ -0,0 +1,34 @@
+export interface ProfileType {
+ login: string;
+ avatar_url: string;
+ bio: string;
+ followers: number;
+ following: number;
+}
+
+export interface followList {
+ id: number;
+ login: string;
+ avatar_url: string;
+ onClick?: () => void;
+}
+export interface FollowUserType {
+ avatar_url: string;
+ events_url: string;
+ followers_url: string;
+ following_url: string;
+ gists_url: string;
+ gravatar_id: string;
+ html_url: string;
+ id: number;
+ login: string;
+ node_id: string;
+ organizations_url: string;
+ received_events_url: string;
+ repos_url: string;
+ site_admin: boolean;
+ starred_url: string;
+ subscriptions_url: string;
+ type: string;
+ url: string;
+} | TypeScript | ์ผ๋ฐ์ ์ผ๋ก ์ฌ์ฉ๋๋ ํ์
์คํฌ๋ฆฝํธ์ ์ปจ๋ฒค์
์ฒ๋ผ, ํ์ค์นผ ์ผ์ด์ค๋ก ์์ฑํ๋ฉด ์ข์ ๊ฒ ๊ฐ์์.
https://basarat.gitbook.io/typescript/styleguide#interface |
@@ -0,0 +1,89 @@
+'use client';
+
+import { getFollowerList, getFollowingList } from '@/apis/getFollowList';
+import { checkState, followState, followerList, followingList, inputToken, loginClick } from '@/recoil/atoms';
+import { followList } from '@/types/types';
+import { useEffect } from 'react';
+import { useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil';
+import ListElement from './ListElement';
+
+export default function FollowList() {
+ const [followers, setFollowers] = useRecoilState(followerList);
+ const [followings, setFollowings] = useRecoilState(followingList);
+ const followBtnState = useRecoilValue(followState);
+ const setCheckState = useSetRecoilState(checkState);
+ const inputTokenValue = useRecoilValue(inputToken);
+ const [loginClickState, setLoginClickState] = useRecoilState(loginClick);
+
+ useEffect(() => {
+ getFollowingList(setFollowings, inputTokenValue);
+ getFollowerList(setFollowers, inputTokenValue);
+ }, []);
+
+ const followerID = followers.map(user => user.id);
+ const followingID = followings.map(user => user.id);
+
+ const followEachOther = followings.filter(user => {
+ return followerID.includes(user.id) && user;
+ });
+
+ const notFollowEachOther = followers.filter(user => {
+ return !followingID.includes(user.id) && user;
+ });
+
+ const onClickCheck = () => {
+ setCheckState(true);
+ };
+
+ const onClickRemove = () => {
+ setCheckState(false);
+ };
+
+ useEffect(() => {
+ onClickRemove();
+ }, [followBtnState]);
+
+ function handleClickLogin(login: string) {
+ setLoginClickState(prevlogin => (prevlogin === login ? ' ' : login));
+ }
+
+ useEffect(() => {
+ console.log(loginClickState);
+ }, [loginClickState, setLoginClickState]);
+
+ return (
+ <section className="commonBackground flex h-[480px] w-full flex-col">
+ <div className="flex justify-end gap-[14px] px-[25px] py-[20px]">
+ <button
+ className="commonButton h-[25px] w-[65px] bg-white text-black hover:bg-red hover:text-white"
+ onClick={onClickCheck}>
+ โ๏ธ ๋ชจ๋ ์ ํ
+ </button>
+ <button
+ className="commonButton h-[25px] w-[65px] bg-white text-black hover:bg-red hover:text-white"
+ onClick={onClickRemove}>
+ ๋ชจ๋ ํด์ง
+ </button>
+ </div>
+ <div className="flex h-[350px] w-[340px] flex-col gap-[20px] overflow-scroll py-[5px]">
+ {followBtnState === 'follow'
+ ? followEachOther.map((user: followList) => {
+ const { id, login, avatar_url } = user;
+ return <ListElement key={id} id={id} login={login} avatar_url={avatar_url} />;
+ })
+ : notFollowEachOther.map((user: followList) => {
+ const { id, login, avatar_url } = user;
+ return (
+ <ListElement
+ onClick={() => handleClickLogin(login)}
+ key={id}
+ id={id}
+ login={login}
+ avatar_url={avatar_url}
+ />
+ );
+ })}
+ </div>
+ </section>
+ );
+} | Unknown | ์ ๋ถ๋ถ์์ recoil selector ๋ฅผ ํ์ฉํด ๋ณผ ์๋ ์์ ๊ฒ ๊ฐ์์.
```tsx
const followerIdSelector = selector({
key: 'followerIdSelector',
({ get }) => {
const followers = get(followerList);
return followers.map(user => user.id);
}
});
``` |
@@ -0,0 +1,14 @@
+import { useRouter } from 'next/navigation';
+
+export default function ConfirmFollowButton() {
+ const router = useRouter();
+
+ const handleOnclick = () => {
+ router.push('/checkfollow');
+ };
+ return (
+ <div className="commonFlex followBackButton hover:bg-grey02" onClick={handleOnclick}>
+ ๋์ ๋งํ ํ์ธํ๋ฌ ๊ฐ๊ธฐ
+ </div>
+ );
+} | Unknown | onClick ์ผ๋ก ๋งํฌ๋ฅผ ์ฒ๋ฆฌํ๋ฉด HTML ํ๊ทธ์์ ๋งํฌ๋ฅผ ๋ณผ ์ ์๊ณ , ์ปจํธ๋กค + ํด๋ฆญ, ์ฐํด๋ฆญ ๋ฑ์ ๋์์ด ๋จนํ์ง ์๋ ์ ๊ทผ์ฑ ์ด์๊ฐ ์์ด์. ๋ฐ๋ผ์ ์ฌ์ดํธ ๋ด ํ์ด์ง ์ด๋ ๋งํฌ๋ next/link ๋ฅผ ์ฌ์ฉํด์ผ ํด์.
```tsx
<Link href="/checkfollow" className="commonFlex followBackButton hover:bg-grey02">
๋์ ๋งํ ํ์ธํ๋ฌ ๊ฐ๊ธฐ
</Link> |
@@ -0,0 +1,46 @@
+import { ProfileType, followList } from '@/types/types';
+import { atom } from 'recoil';
+import { recoilPersist } from 'recoil-persist';
+const { persistAtom } = recoilPersist();
+
+export const profileInfo = atom<ProfileType>({
+ key: 'profileInfo',
+ default: {
+ login: '',
+ avatar_url: '',
+ bio: '',
+ followers: 0,
+ following: 0,
+ },
+});
+
+export const followerList = atom<followList[]>({
+ key: 'followerList',
+ default: [{ id: 0, login: '', avatar_url: '' }],
+});
+
+export const followingList = atom<followList[]>({
+ key: 'followingList',
+ default: [{ id: 0, login: '', avatar_url: '' }],
+});
+
+export const followState = atom<string>({
+ key: 'followState',
+ default: 'follow',
+});
+
+export const checkState = atom<boolean>({
+ key: 'checkState',
+ default: false,
+});
+
+export const inputToken = atom<string>({
+ key: 'inputToken',
+ default: '',
+ effects_UNSTABLE: [persistAtom],
+});
+
+export const loginClick = atom<string>({
+ key: 'loginClick',
+ default: ' ',
+}); | TypeScript | ๋ฏธ์ธ ํ: ์ด๋ฆ์ suffix๋ก Atom ์ ๋ถ์ด๋ฉด ์ปดํฌ๋ํธ์์ ์ด๋ฅผ ํ์ฉํ ๋ ์ด๋ฆ ์ถฉ๋ ๋ฌธ์ ์์ ์์ ๋ก์์ง ์ ์์ด์.
```tsx
// ์ ์ธ
export const profileInfoAtom = atom<ProfileType>({
key: 'profileInfo',
default: {
login: '',
avatar_url: '',
bio: '',
followers: 0,
following: 0,
},
});
// ์ฌ์ฉํ ๋
const profileInfo = useRecoilValue(profileInfoAtom);
``` |
@@ -0,0 +1,47 @@
+import { FollowUserType, followList } from '@/types/types';
+import axios from 'axios';
+import { SetterOrUpdater } from 'recoil';
+
+const PER_PAGE = 100;
+export const getFollowingList = async (setFollowings: SetterOrUpdater<followList[]>, tokenValue: string) => {
+ try {
+ const followingData = await axios.get(`${process.env.NEXT_PUBLIC_BASE_URL}/user/following?per_page=${PER_PAGE}`, {
+ headers: {
+ Accept: 'application/vnd.github+json',
+ Authorization: `Bearer ${tokenValue}`,
+ },
+ });
+
+ const data = followingData.data;
+
+ const followingList = data.map((user: FollowUserType) => {
+ const { id, login, avatar_url } = user;
+ return { id, login, avatar_url };
+ });
+
+ setFollowings(followingList);
+ } catch {
+ console.error('error');
+ }
+};
+
+export const getFollowerList = async (setFollowers: SetterOrUpdater<followList[]>, tokenValue: string) => {
+ try {
+ const followerData = await axios.get(`${process.env.NEXT_PUBLIC_BASE_URL}/user/followers?per_page=${PER_PAGE}`, {
+ headers: {
+ Accept: 'application/vnd.github+json',
+ Authorization: `Bearer ${tokenValue}`,
+ },
+ });
+ const data = followerData.data;
+
+ const followerList = data.map((user: FollowUserType) => {
+ const { id, login, avatar_url } = user;
+ return { id, login, avatar_url };
+ });
+
+ setFollowers(followerList);
+ } catch {
+ console.error('error');
+ }
+}; | TypeScript | ๊ฑด์์ด๊ฐ [์ฌ๊ธฐ](https://github.com/sopt-web-advanced-study/TOY-PROJECT/pull/13/files#r1436888989)์ ๋จ๊ฒจ์ฃผ๊ธด ํ๋๋ฐ์! ์ฌ๊ธฐ์ ํ์
์ camelCase๋ก ์ง์ด์ฃผ๋ค ๋ณด๋,
`followList`์ `followingList`๋ ๊ฐ๊ฐ ํ์
, ๋ณ์๋ก ์์ ๋ค๋ฅธ ์๋ฏธ๋ก ์ฌ์ฉ๋๋๋ฐ์, ํ ๋์ ํ์
ํ๊ธฐ๊ฐ ์ด๋ ค์ ์ด์! ๊ฐ ์ฉ๋์ ๋ฐ๋ผ ์ปจ๋ฒค์
์ ๋ง๊ฒ ์ด๋ฆ์ ์ง์ด์ฃผ๋ฉด ์ข์ ๊ฒ ๊ฐ์์. |
@@ -0,0 +1,47 @@
+import { FollowUserType, followList } from '@/types/types';
+import axios from 'axios';
+import { SetterOrUpdater } from 'recoil';
+
+const PER_PAGE = 100;
+export const getFollowingList = async (setFollowings: SetterOrUpdater<followList[]>, tokenValue: string) => {
+ try {
+ const followingData = await axios.get(`${process.env.NEXT_PUBLIC_BASE_URL}/user/following?per_page=${PER_PAGE}`, {
+ headers: {
+ Accept: 'application/vnd.github+json',
+ Authorization: `Bearer ${tokenValue}`,
+ },
+ });
+
+ const data = followingData.data;
+
+ const followingList = data.map((user: FollowUserType) => {
+ const { id, login, avatar_url } = user;
+ return { id, login, avatar_url };
+ });
+
+ setFollowings(followingList);
+ } catch {
+ console.error('error');
+ }
+};
+
+export const getFollowerList = async (setFollowers: SetterOrUpdater<followList[]>, tokenValue: string) => {
+ try {
+ const followerData = await axios.get(`${process.env.NEXT_PUBLIC_BASE_URL}/user/followers?per_page=${PER_PAGE}`, {
+ headers: {
+ Accept: 'application/vnd.github+json',
+ Authorization: `Bearer ${tokenValue}`,
+ },
+ });
+ const data = followerData.data;
+
+ const followerList = data.map((user: FollowUserType) => {
+ const { id, login, avatar_url } = user;
+ return { id, login, avatar_url };
+ });
+
+ setFollowers(followerList);
+ } catch {
+ console.error('error');
+ }
+}; | TypeScript | (๊ฑด์์ด๊ฐ ์จ์ค to-be์ ์ธ์์ setFollowers๋ ๋น ์ง๋๊ฑธ ์๋ํ๊ฑธ๊ฑฐ์์!)
```tsx
export const getFollowerList = async (tokenValue: string) => { ... }
``` |
@@ -0,0 +1,47 @@
+import { FollowUserType, followList } from '@/types/types';
+import axios from 'axios';
+import { SetterOrUpdater } from 'recoil';
+
+const PER_PAGE = 100;
+export const getFollowingList = async (setFollowings: SetterOrUpdater<followList[]>, tokenValue: string) => {
+ try {
+ const followingData = await axios.get(`${process.env.NEXT_PUBLIC_BASE_URL}/user/following?per_page=${PER_PAGE}`, {
+ headers: {
+ Accept: 'application/vnd.github+json',
+ Authorization: `Bearer ${tokenValue}`,
+ },
+ });
+
+ const data = followingData.data;
+
+ const followingList = data.map((user: FollowUserType) => {
+ const { id, login, avatar_url } = user;
+ return { id, login, avatar_url };
+ });
+
+ setFollowings(followingList);
+ } catch {
+ console.error('error');
+ }
+};
+
+export const getFollowerList = async (setFollowers: SetterOrUpdater<followList[]>, tokenValue: string) => {
+ try {
+ const followerData = await axios.get(`${process.env.NEXT_PUBLIC_BASE_URL}/user/followers?per_page=${PER_PAGE}`, {
+ headers: {
+ Accept: 'application/vnd.github+json',
+ Authorization: `Bearer ${tokenValue}`,
+ },
+ });
+ const data = followerData.data;
+
+ const followerList = data.map((user: FollowUserType) => {
+ const { id, login, avatar_url } = user;
+ return { id, login, avatar_url };
+ });
+
+ setFollowers(followerList);
+ } catch {
+ console.error('error');
+ }
+}; | TypeScript | ๋ง์ฝ console.error๋ก ๋ง ๋จ๊ฒจ๋๊ณ ์ถ์๋๋ผ๋ ์ด๋ ๊ฒ ํ๋ฉด ํ๋์ฝ๋ฉ๋ 'error'๋ง ๋จ๊ฒ๋์ด ํท๊ฐ๋ฆด ๊ฒ ๊ฐ์์.
`error.message`๋ฅผ ์ฐ๊ฑฐ๋([mdn ์์](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Error#%EC%9D%BC%EB%B0%98%EC%A0%81%EC%9D%B8_%EC%98%A4%EB%A5%98_%EB%8D%98%EC%A7%80%EA%B8%B0)), ์๋๋ฉด ๋ณดํต [Sentry](https://docs.sentry.io/platforms/javascript/guides/react/usage/)๋ฅผ ํตํด ์๋ฌ๋ฅผ ์์ง(๋ก๊น
)ํด์ ์๋ฌ๋ฅผ ๋น ๋ฅด๊ฒ ํ์ธํ๊ณ ์ด๋ฅผ ์ฒ๋ฆฌํ ์ ์๋๋ก ํ๊ณ ์์ด์!
์๋ฌ ๊ฐ์ฒด๋ `Error` ๋ผ๋ [๋ด์ฅ ๊ฐ์ฒด ํ์
](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Error)์ผ๋ก ๋์ ธ์ง๋๋ฐ์, ์ด๋ name, message, stack๋ฅผ ๊ธฐ๋ณธ์ ์ผ๋ก ๊ฐ์ง๊ณ ์์ด์ ๋ณดํต message๋ฅผ ๋ณด์ฌ์ฃผ๋ ์์ผ๋ก ๋ง์ด ์ฌ์ฉํด์. (์๋ฒ์ชฝ์์ ์๋ฌ ๋ฉ์์ง๋ฅผ ์ค์ ํด์ ๋ณด๋ด์ค๋ค๋ฉด, ํด๋น ํ๋๋ก ํ์ธ์ด ๊ฐ๋ฅํ ๊ฒฝ์ฐ๊ฐ ๋๋ถ๋ถ์ด์์.) ๋ง์ฝ ํ์
์ง์ ์ด ์๋๋ ๊ฒฝ์ฐ์๋ ์๋์ฒ๋ผ ์ฒ๋ฆฌํ ์ ์์ด์.
```tsx
// ์๋ ๊ฒ ํ๋ผ๋ ๋ง์์ ์๋๊ณ instatnceof ๊ตฌ๋ฌธ์ผ๋ก ํ์
์ถ๋ก ์ ํ ์ ์๋ค๋ ์์์
๋๋ค!
try {
} catch(error){
console.error(error instanceof Error ? error.message : '~์์ ์๋ฌ๊ฐ ๋ฐ์ํ์ด์ ');
}
```
์ฐธ๊ณ ๋ก ์๋ฌ๋ ๋ฐ์ํ ๊ณณ์์ ๋ถํฐ ์ต์์ ์ปดํฌ๋ํธ๊น์ง ์ ํ๋๊ณ , ๊ฐ์ฅ ๊ฐ๊น์ด catch๋ฌธ์ด๋ ์๋ฌ๋ฐ์ด๋๋ฆฌ๋ฅผ ์ค์ ํด๋ ๊ณณ์์ catch๋ ์ ์๋๋ฐ์, ์ด ๊ฒฝ์ฐ์๋ 'catch' ๋ผ๊ณ ๋ง console.error ๋ก ์ฐํ๊ฒ ๋์ด ๊ฑด์์ด ๋ง ์ฒ๋ผ ์คํ๋ ค ํท๊ฐ๋ฆด ์ ์์ ๊ฒ ๊ฐ์ต๋๋ท |
@@ -0,0 +1,35 @@
+'use client';
+
+import FollowList from '@/components/checkfollow/FollowList';
+import { useRecoilValue, useSetRecoilState } from 'recoil';
+import FollowOrNotBtn from '../../components/checkfollow/FollowOrNotBtn';
+import Profile from '../../components/checkfollow/Profile';
+import { putFollowList } from '@/apis/putFollowList';
+import { followState, inputToken, loginClick } from '@/recoil/atoms';
+
+export default function CheckFollow() {
+ const loginClickState = useRecoilValue(loginClick);
+ const inputTokenValue = useRecoilValue(inputToken);
+ const setFollowState = useSetRecoilState(followState);
+
+ async function handleFllow(username: string) {
+ const success = await putFollowList(username, inputTokenValue);
+ if (success) {
+ setFollowState('follow');
+ window.location.reload();
+ }
+ }
+
+ return (
+ <article className="flex flex-col px-[25px] py-[37px]">
+ <Profile />
+ <FollowOrNotBtn />
+ <FollowList />
+ <button
+ onClick={() => handleFllow(loginClickState)}
+ className="mt-[34px] h-[45px] rounded-[5px] border-2 border-solid border-grey02 bg-sub01 text-title01 text-white hover:bg-grey02">
+ ๋งํํ๊ธฐ
+ </button>
+ </article>
+ );
+} | Unknown | ์ ์ฒด ์๋ก๊ณ ์นจ์ ํ๋ฉด ์ฌ์ฉ์ ๊ฒฝํ ์ธก๋ฉด์์๋ ์ข์ง ์์ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,89 @@
+'use client';
+
+import { getFollowerList, getFollowingList } from '@/apis/getFollowList';
+import { checkState, followState, followerList, followingList, inputToken, loginClick } from '@/recoil/atoms';
+import { followList } from '@/types/types';
+import { useEffect } from 'react';
+import { useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil';
+import ListElement from './ListElement';
+
+export default function FollowList() {
+ const [followers, setFollowers] = useRecoilState(followerList);
+ const [followings, setFollowings] = useRecoilState(followingList);
+ const followBtnState = useRecoilValue(followState);
+ const setCheckState = useSetRecoilState(checkState);
+ const inputTokenValue = useRecoilValue(inputToken);
+ const [loginClickState, setLoginClickState] = useRecoilState(loginClick);
+
+ useEffect(() => {
+ getFollowingList(setFollowings, inputTokenValue);
+ getFollowerList(setFollowers, inputTokenValue);
+ }, []);
+
+ const followerID = followers.map(user => user.id);
+ const followingID = followings.map(user => user.id);
+
+ const followEachOther = followings.filter(user => {
+ return followerID.includes(user.id) && user;
+ });
+
+ const notFollowEachOther = followers.filter(user => {
+ return !followingID.includes(user.id) && user;
+ });
+
+ const onClickCheck = () => {
+ setCheckState(true);
+ };
+
+ const onClickRemove = () => {
+ setCheckState(false);
+ };
+
+ useEffect(() => {
+ onClickRemove();
+ }, [followBtnState]);
+
+ function handleClickLogin(login: string) {
+ setLoginClickState(prevlogin => (prevlogin === login ? ' ' : login));
+ }
+
+ useEffect(() => {
+ console.log(loginClickState);
+ }, [loginClickState, setLoginClickState]);
+
+ return (
+ <section className="commonBackground flex h-[480px] w-full flex-col">
+ <div className="flex justify-end gap-[14px] px-[25px] py-[20px]">
+ <button
+ className="commonButton h-[25px] w-[65px] bg-white text-black hover:bg-red hover:text-white"
+ onClick={onClickCheck}>
+ โ๏ธ ๋ชจ๋ ์ ํ
+ </button>
+ <button
+ className="commonButton h-[25px] w-[65px] bg-white text-black hover:bg-red hover:text-white"
+ onClick={onClickRemove}>
+ ๋ชจ๋ ํด์ง
+ </button>
+ </div>
+ <div className="flex h-[350px] w-[340px] flex-col gap-[20px] overflow-scroll py-[5px]">
+ {followBtnState === 'follow'
+ ? followEachOther.map((user: followList) => {
+ const { id, login, avatar_url } = user;
+ return <ListElement key={id} id={id} login={login} avatar_url={avatar_url} />;
+ })
+ : notFollowEachOther.map((user: followList) => {
+ const { id, login, avatar_url } = user;
+ return (
+ <ListElement
+ onClick={() => handleClickLogin(login)}
+ key={id}
+ id={id}
+ login={login}
+ avatar_url={avatar_url}
+ />
+ );
+ })}
+ </div>
+ </section>
+ );
+} | Unknown | ๋ง์ฝ ์์ ์ด ์ผ์ด๋๊ฒ ๋์๋, onClickRemove๊ฐ ์ด๋ ์์ ์ ์คํ๋๋์ง์ ๋ํ ๊ณ ๋ ค๊ฐ ํญ์ ์ด๋ค์ ธ์ผ ํด์ ์ฌ์ด๋ ์ดํํธ๊ฐ ์๊ฒจ ๋ณ๊ฒฝํ๊ธฐ๋ ์์ฃผ ๊น๋ค๋ก์ ์ง๋ ๋ฌธ์ ๊ฐ ์์ด์.
>๋ก์ง์ follow ๋ฒํผ์ด ์ ํ๋๋ ๊ณณ์ผ๋ก ์ฎ๊ธฐ๋ ๊ฒ์ด ์ข์ ๊ฒ ๊ฐ์์.
์๋ ๊ฒ ํด์ผ ํด๋น ๋ก์ง์ด ์คํ๋๋ ์์ ์๋ง onClickRemove๊ฐ ์คํ๋จ์ด ๋ณด์ฅ๋๊ธฐ ๋๋ฌธ์ ์ฌ์ด๋ ์ดํํธ๋ฅผ ์ต์ํํ ์ ์์ต๋๋น |
@@ -0,0 +1,89 @@
+'use client';
+
+import { getFollowerList, getFollowingList } from '@/apis/getFollowList';
+import { checkState, followState, followerList, followingList, inputToken, loginClick } from '@/recoil/atoms';
+import { followList } from '@/types/types';
+import { useEffect } from 'react';
+import { useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil';
+import ListElement from './ListElement';
+
+export default function FollowList() {
+ const [followers, setFollowers] = useRecoilState(followerList);
+ const [followings, setFollowings] = useRecoilState(followingList);
+ const followBtnState = useRecoilValue(followState);
+ const setCheckState = useSetRecoilState(checkState);
+ const inputTokenValue = useRecoilValue(inputToken);
+ const [loginClickState, setLoginClickState] = useRecoilState(loginClick);
+
+ useEffect(() => {
+ getFollowingList(setFollowings, inputTokenValue);
+ getFollowerList(setFollowers, inputTokenValue);
+ }, []);
+
+ const followerID = followers.map(user => user.id);
+ const followingID = followings.map(user => user.id);
+
+ const followEachOther = followings.filter(user => {
+ return followerID.includes(user.id) && user;
+ });
+
+ const notFollowEachOther = followers.filter(user => {
+ return !followingID.includes(user.id) && user;
+ });
+
+ const onClickCheck = () => {
+ setCheckState(true);
+ };
+
+ const onClickRemove = () => {
+ setCheckState(false);
+ };
+
+ useEffect(() => {
+ onClickRemove();
+ }, [followBtnState]);
+
+ function handleClickLogin(login: string) {
+ setLoginClickState(prevlogin => (prevlogin === login ? ' ' : login));
+ }
+
+ useEffect(() => {
+ console.log(loginClickState);
+ }, [loginClickState, setLoginClickState]);
+
+ return (
+ <section className="commonBackground flex h-[480px] w-full flex-col">
+ <div className="flex justify-end gap-[14px] px-[25px] py-[20px]">
+ <button
+ className="commonButton h-[25px] w-[65px] bg-white text-black hover:bg-red hover:text-white"
+ onClick={onClickCheck}>
+ โ๏ธ ๋ชจ๋ ์ ํ
+ </button>
+ <button
+ className="commonButton h-[25px] w-[65px] bg-white text-black hover:bg-red hover:text-white"
+ onClick={onClickRemove}>
+ ๋ชจ๋ ํด์ง
+ </button>
+ </div>
+ <div className="flex h-[350px] w-[340px] flex-col gap-[20px] overflow-scroll py-[5px]">
+ {followBtnState === 'follow'
+ ? followEachOther.map((user: followList) => {
+ const { id, login, avatar_url } = user;
+ return <ListElement key={id} id={id} login={login} avatar_url={avatar_url} />;
+ })
+ : notFollowEachOther.map((user: followList) => {
+ const { id, login, avatar_url } = user;
+ return (
+ <ListElement
+ onClick={() => handleClickLogin(login)}
+ key={id}
+ id={id}
+ login={login}
+ avatar_url={avatar_url}
+ />
+ );
+ })}
+ </div>
+ </section>
+ );
+} | Unknown | ๋๋ฒ๊น
์ฉ์ผ๋ก ์ฌ์ฉํ ๋ค์์ ์ง์ฐ๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ท ใ
ใ
|
@@ -0,0 +1,14 @@
+import { useRouter } from 'next/navigation';
+
+export default function ConfirmFollowButton() {
+ const router = useRouter();
+
+ const handleOnclick = () => {
+ router.push('/checkfollow');
+ };
+ return (
+ <div className="commonFlex followBackButton hover:bg-grey02" onClick={handleOnclick}>
+ ๋์ ๋งํ ํ์ธํ๋ฌ ๊ฐ๊ธฐ
+ </div>
+ );
+} | Unknown | ์๋ ๊ฒ ์๋์ ์ด๋๋ก ์ด๋ํ ๊ฑด์ง ํ๋ฆฌ๋ทฐ๋ก๋ ์๋ ค์ค๋ต๋๋น! Link๋ next.js์์ `<a>` ํ๊ทธ๋ฅผ ๋ํํด์ค ์ปดํฌ๋ํธ์์. (์ค์ ๋ก ๋งํ ์ ๊ทผ์ฑ์ aํ๊ทธ๊ฐ ์ฑ๊ฒจ์ฃผ๋ ๊ฒ ์
๋๋น)
<img width="1624" alt="image" src="https://github.com/sopt-web-advanced-study/TOY-PROJECT/assets/26808056/af8d6f55-393a-49ba-be04-f00972a2a478"> |
@@ -0,0 +1,14 @@
+import { useRouter } from 'next/navigation';
+
+export default function ConfirmFollowButton() {
+ const router = useRouter();
+
+ const handleOnclick = () => {
+ router.push('/checkfollow');
+ };
+ return (
+ <div className="commonFlex followBackButton hover:bg-grey02" onClick={handleOnclick}>
+ ๋์ ๋งํ ํ์ธํ๋ฌ ๊ฐ๊ธฐ
+ </div>
+ );
+} | Unknown | ์์ํ ๋ด์ฉ์ธ๋ฐ, ์ด๋ฒคํธ ํธ๋ค๋ฌ ํจ์ ์ด๋ฆ์ ์ง์๋ ๋ณดํต
`onClick~`
`handleClick~`
๋ ์ค ํ๋๋ก ์ง๋ ๊ฒ ๊ฐ์์. ์ ๋์ฌ๊ฐ ๋ ๋ค ๋ถ์ด์์ด์ ๋จ๊ฒจ๋ดค์ต๋๋ค! |
@@ -0,0 +1,34 @@
+export interface ProfileType {
+ login: string;
+ avatar_url: string;
+ bio: string;
+ followers: number;
+ following: number;
+}
+
+export interface followList {
+ id: number;
+ login: string;
+ avatar_url: string;
+ onClick?: () => void;
+}
+export interface FollowUserType {
+ avatar_url: string;
+ events_url: string;
+ followers_url: string;
+ following_url: string;
+ gists_url: string;
+ gravatar_id: string;
+ html_url: string;
+ id: number;
+ login: string;
+ node_id: string;
+ organizations_url: string;
+ received_events_url: string;
+ repos_url: string;
+ site_admin: boolean;
+ starred_url: string;
+ subscriptions_url: string;
+ type: string;
+ url: string;
+} | TypeScript | ๊ทธ๋ฆฌ๊ณ ์๋ฒ์์ ์ฌ์ฉ๋๋ ํ์
๊ณผ (api ํธ์ถ ๊ฒฐ๊ณผ ์๋ ค์ฃผ๋ ํ์
) ์ค์ ์ปดํฌ๋ํธ์์ ์ฌ์ฉํ๋ ํ์
์ ๊ตฌ๋ถ๋์์ผ๋ฉด ์ข๊ฒ ์ด์! (model.ts ๋ผ๋ ํ์์ผ๋ก ์ง๊ธฐ๋ ํ๋๋ฐ, api ํธ์ถ ๊ฒฐ๊ณผ ์๋ต์ผ๋ก ๋ฐ๋ ํ์
์ ์ ๋ ํ์ผ์ด์์.)
์ด๋ ๊ฒ onClick ์ด๋ผ๋ ์ปดํฌ๋ํธ์์ ์ ์ฉ๋๋ ๋
ผ๋ฆฌ์ ํ์
์ ๊ฐ์ง๊ณ ์์ ๊ฒฝ์ฐ api์ ํ์
์ด ๋ณ๊ฒฝ๋์ด ํด๋น ํ์
์ ๋ฐ๊ฟ์ฃผ์๋๋ฐ, ์ปดํฌ๋ํธ์์๊น์ง ์ํฅ์ ๋ฐ์ ์ ์์ด์!
๋ง์ฝ ์๋ฒ ํ์
์ ํ์ฅํด์ ์ฌ์ฉํ๊ณ ์ถ๋ค๋ฉด, ์ฌ์ฉ์ฒ(์ปดํฌ๋ํธ์ชฝ)์์ import ํ ๋ค ํ์ฅํด์ ์ฌ์ฉํ๋๊ฒ ๋ ์ข์ ๊ฒ ๊ฐ์์.
```tsx
// ์ด๋ ๊ฒ์!
interface ํ๋ก์ฐ์ด์ฉ๊ตฌComponentProps {
onClick?: ()=>void;
} extends FollowList
// ๊ทธ๋ฐ๋ฐ ์ฌ์ค ๋ชจ๋ธ๋ง ๊ฐ์ ธ์ค๋๊ฒ ๋ ์ข์ ๊ฒ ๊ฐ์์.
interface ํ๋ก์ฐ์ด์ฉ๊ตฌComponentProps {
followList: FollowList[]; // ์๋ฒ ํ์
์ด ๋ณ๊ฒฝ๋๋ฉด, followList๋ง ๋ณ๊ฒฝ์ด ์ด๋ค์ง๋ฉด ๋ผ์. ๋ณ๊ฒฝ์ ์ํฅ ๋ฒ์๋ฅผ ์ต์ํ์ผ๋ก ๋ง๋ค์ด์ค ์ ์์ด์.
onClick?: ()=>void;
};
``` |
@@ -0,0 +1,46 @@
+import { ProfileType, followList } from '@/types/types';
+import { atom } from 'recoil';
+import { recoilPersist } from 'recoil-persist';
+const { persistAtom } = recoilPersist();
+
+export const profileInfo = atom<ProfileType>({
+ key: 'profileInfo',
+ default: {
+ login: '',
+ avatar_url: '',
+ bio: '',
+ followers: 0,
+ following: 0,
+ },
+});
+
+export const followerList = atom<followList[]>({
+ key: 'followerList',
+ default: [{ id: 0, login: '', avatar_url: '' }],
+});
+
+export const followingList = atom<followList[]>({
+ key: 'followingList',
+ default: [{ id: 0, login: '', avatar_url: '' }],
+});
+
+export const followState = atom<string>({
+ key: 'followState',
+ default: 'follow',
+});
+
+export const checkState = atom<boolean>({
+ key: 'checkState',
+ default: false,
+});
+
+export const inputToken = atom<string>({
+ key: 'inputToken',
+ default: '',
+ effects_UNSTABLE: [persistAtom],
+});
+
+export const loginClick = atom<string>({
+ key: 'loginClick',
+ default: ' ',
+}); | TypeScript | ์ปดํฌ๋ํธ์ ์ฌ์ฉ์ฒ์์ ํ์ธํด๋ณด๋ `'follow' | 'not'` ๋ ๊ฐ์ง ๊ฒฝ์ฐ๋ก ์ฌ์ฉ๋๋ ๊ฒ ๊ฐ์๋ฐ์, ๊ทธ๋ ๋ค๋ฉด atom์ ํ์
์ string์ผ๋ก ์ ์ด์ฃผ๊ธฐ ๋ณด๋ค๋ ์๋์ฒ๋ผ ๋ํ๋ด๋๊ฒ ๋ ์ข์ ๊ฒ ๊ฐ์์.(string literal type, enum ํ์
์ด๋ผ๊ณ ๋ ๋ถ๋ฌ์) ์ค์ IDE์์ ํ์
์ถ๋ก ์ ํด์ฃผ์ด ํด๋จผ์๋ฌ๋ฅผ ๋ฐฉ์งํด์ฃผ๊ธฐ ์ํจ์ด์์.
๊ทธ๋ฆฌ๊ณ follow, not ์ ๋ ๊ฐ์ง ๋
ผ๋ฆฌ๋ง ์กด์ฌํ๋ค๋ฉด `boolean` ํ์
์ผ๋ก ๋์ด๋ ๊ด์ฐฎ์ ๊ฒ ๊ฐ์ต๋๋ค!
```suggestion
export const followState = atom<'follow' | 'not'>({
key: 'followState',
default: 'follow',
});
``` |
@@ -0,0 +1,46 @@
+import { ProfileType, followList } from '@/types/types';
+import { atom } from 'recoil';
+import { recoilPersist } from 'recoil-persist';
+const { persistAtom } = recoilPersist();
+
+export const profileInfo = atom<ProfileType>({
+ key: 'profileInfo',
+ default: {
+ login: '',
+ avatar_url: '',
+ bio: '',
+ followers: 0,
+ following: 0,
+ },
+});
+
+export const followerList = atom<followList[]>({
+ key: 'followerList',
+ default: [{ id: 0, login: '', avatar_url: '' }],
+});
+
+export const followingList = atom<followList[]>({
+ key: 'followingList',
+ default: [{ id: 0, login: '', avatar_url: '' }],
+});
+
+export const followState = atom<string>({
+ key: 'followState',
+ default: 'follow',
+});
+
+export const checkState = atom<boolean>({
+ key: 'checkState',
+ default: false,
+});
+
+export const inputToken = atom<string>({
+ key: 'inputToken',
+ default: '',
+ effects_UNSTABLE: [persistAtom],
+});
+
+export const loginClick = atom<string>({
+ key: 'loginClick',
+ default: ' ',
+}); | TypeScript | ํด๋น ๋ณ์๋ค์ด ๊ฐ ์ปดํฌ๋ํธ์ import ๋์ด ์ฌ์ฌ์ฉ๋๋ค ๋ณด๋ ์ํฐ์ ๋ํ๋ด๋๊ฑด์ง ํ๋์ ์ด๋ฆ์ผ๋ก๋ ์ ์ ์๊ฒ `~State`๋ `~Atom`๋ฑ์ ์ ๋ฏธ์ฌ๋ฅผ ๋ถ์ฌ์ ์ด๋ฆ์ด ๊ตฌ๋ถ๋์ด๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ท
(์๋์ followState์ ๊ฐ์ด์!) |
@@ -0,0 +1,46 @@
+import { ProfileType, followList } from '@/types/types';
+import { atom } from 'recoil';
+import { recoilPersist } from 'recoil-persist';
+const { persistAtom } = recoilPersist();
+
+export const profileInfo = atom<ProfileType>({
+ key: 'profileInfo',
+ default: {
+ login: '',
+ avatar_url: '',
+ bio: '',
+ followers: 0,
+ following: 0,
+ },
+});
+
+export const followerList = atom<followList[]>({
+ key: 'followerList',
+ default: [{ id: 0, login: '', avatar_url: '' }],
+});
+
+export const followingList = atom<followList[]>({
+ key: 'followingList',
+ default: [{ id: 0, login: '', avatar_url: '' }],
+});
+
+export const followState = atom<string>({
+ key: 'followState',
+ default: 'follow',
+});
+
+export const checkState = atom<boolean>({
+ key: 'checkState',
+ default: false,
+});
+
+export const inputToken = atom<string>({
+ key: 'inputToken',
+ default: '',
+ effects_UNSTABLE: [persistAtom],
+});
+
+export const loginClick = atom<string>({
+ key: 'loginClick',
+ default: ' ',
+}); | TypeScript | ์๊ฒ ์ ํํ ์ด๋ค๊ฑธ ์ํด ์ฌ์ฉ๋๋ atom์ธ์ง๊ฐ ์ด๋ฆ์ด๋ default ๊ฐ๋ง ๋ณด๊ณ ๋ ์กฐ๊ธ ํ์
ํ๊ธฐ๊ฐ ์ด๋ ค์ด ๊ฒ ๊ฐ์์ ใ
ใ
๊ทธ๋ฆฌ๊ณ ๊ธฐ๋ณธ๊ฐ์ด ๊ทธ๋ฅ ๋ค๋ฅธ ๊ฐ์ฒ๋ผ ๋น ์คํธ๋ง์ด ์๋๋ผ `' '` ์ธ ์ด์ ๋ ํน์ ์์๊น์?!
์ํฐ์ ์ฌ์ฉํ ๋, ์ด๋์ ์ด๋ค ๋ชฉ์ ์ผ๋ก ์ฌ์ฉ๋๋์ง๋ฅผ ์ด๋ฆ์ ๋ ๋ํ๋ด๊ณ , ๊ธฐ๋ณธ๊ฐ์ ์ ์ค์ ํด์ ์ด๋ค ์ฉ๋๋ก ์ด๋ป๊ฒ ์ฌ์ฉํ๋์ง ์ข ๋ ์ ๋๋ฌ๋ด๊ณ , ๊ถ๊ทน์ ์ผ๋ก๋ ์ํฐ์ ๊ผญ ์ฌ์ฉํด์ผ ํ๋์ง ํ๋ฒ ๋ ๊ณ ๋ฏผ์ ํด๋ณด๋ ๊ฒ๋ ์ข์ ๊ณ ๋ฏผ์ด ๋ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,47 @@
+import { FollowUserType, followList } from '@/types/types';
+import axios from 'axios';
+import { SetterOrUpdater } from 'recoil';
+
+const PER_PAGE = 100;
+export const getFollowingList = async (setFollowings: SetterOrUpdater<followList[]>, tokenValue: string) => {
+ try {
+ const followingData = await axios.get(`${process.env.NEXT_PUBLIC_BASE_URL}/user/following?per_page=${PER_PAGE}`, {
+ headers: {
+ Accept: 'application/vnd.github+json',
+ Authorization: `Bearer ${tokenValue}`,
+ },
+ });
+
+ const data = followingData.data;
+
+ const followingList = data.map((user: FollowUserType) => {
+ const { id, login, avatar_url } = user;
+ return { id, login, avatar_url };
+ });
+
+ setFollowings(followingList);
+ } catch {
+ console.error('error');
+ }
+};
+
+export const getFollowerList = async (setFollowers: SetterOrUpdater<followList[]>, tokenValue: string) => {
+ try {
+ const followerData = await axios.get(`${process.env.NEXT_PUBLIC_BASE_URL}/user/followers?per_page=${PER_PAGE}`, {
+ headers: {
+ Accept: 'application/vnd.github+json',
+ Authorization: `Bearer ${tokenValue}`,
+ },
+ });
+ const data = followerData.data;
+
+ const followerList = data.map((user: FollowUserType) => {
+ const { id, login, avatar_url } = user;
+ return { id, login, avatar_url };
+ });
+
+ setFollowers(followerList);
+ } catch {
+ console.error('error');
+ }
+}; | TypeScript | ์ฌ๊ธฐ์ ์๋ฒ์์ ๋ด๋ ค์ฃผ๋ ๊ฐ๋ค ์ค ํด๋ผ์ด์ธํธ์์ ํ์ํ ํ์
๋ค๋ง ์์ ๋ฝ์๋ด์ฃผ๋ ๊ณผ์ ์ด ์ด๋ค์ง๋ค๊ณ ์๊ฐํ๋๋ฐ์!
ํด๋ผ์ด์ธํธ์์ camelCase๋ฅผ ์ฌ์ฉํ๊ณ ์์ผ๋, ๋๊ฒจ์ฃผ๋ ๊น์ camelCase๋ก ๋ณ๊ฒฝํด์ฃผ๋ ์์
์ ์ฌ๊ธฐ์ ์งํํด๋ ์ข์ ๊ฒ ๊ฐ๋ค์! ์ง์ ๋ฐ๊ฟ์ฃผ์ด๋ ๊ด์ฐฎ๊ณ , ์๋ฐ ์ญํ ์ ํด์ฃผ๋ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ ์์ผ๋ ([์์](https://www.npmjs.com/package/camelcase-keys)) ์ฐธ๊ณ ํด๋ณด๋ฉด ์ข์ ๊ฒ ๊ฐ์์. |
@@ -0,0 +1,35 @@
+'use client';
+
+import FollowList from '@/components/checkfollow/FollowList';
+import { useRecoilValue, useSetRecoilState } from 'recoil';
+import FollowOrNotBtn from '../../components/checkfollow/FollowOrNotBtn';
+import Profile from '../../components/checkfollow/Profile';
+import { putFollowList } from '@/apis/putFollowList';
+import { followState, inputToken, loginClick } from '@/recoil/atoms';
+
+export default function CheckFollow() {
+ const loginClickState = useRecoilValue(loginClick);
+ const inputTokenValue = useRecoilValue(inputToken);
+ const setFollowState = useSetRecoilState(followState);
+
+ async function handleFllow(username: string) {
+ const success = await putFollowList(username, inputTokenValue);
+ if (success) {
+ setFollowState('follow');
+ window.location.reload();
+ }
+ }
+
+ return (
+ <article className="flex flex-col px-[25px] py-[37px]">
+ <Profile />
+ <FollowOrNotBtn />
+ <FollowList />
+ <button
+ onClick={() => handleFllow(loginClickState)}
+ className="mt-[34px] h-[45px] rounded-[5px] border-2 border-solid border-grey02 bg-sub01 text-title01 text-white hover:bg-grey02">
+ ๋งํํ๊ธฐ
+ </button>
+ </article>
+ );
+} | Unknown | ์๊ฑฐ๋,,, ์ฌ์ค put ์ดํ์ ํ๋ฉด์ ๋ฐ๋ก ๋ณด์ฌ์ง๊ฒ ํ๋๋ก ํ๊ณ ์ถ์ด์,,,, ์๋ก๊ณ ์นจ์ ์๋ํ์์ต๋๋คใ
ใ
! |
@@ -0,0 +1,14 @@
+import { useRouter } from 'next/navigation';
+
+export default function ConfirmFollowButton() {
+ const router = useRouter();
+
+ const handleOnclick = () => {
+ router.push('/checkfollow');
+ };
+ return (
+ <div className="commonFlex followBackButton hover:bg-grey02" onClick={handleOnclick}>
+ ๋์ ๋งํ ํ์ธํ๋ฌ ๊ฐ๊ธฐ
+ </div>
+ );
+} | Unknown | ํ ๊ฐ์ฌํฉ๋๋ค!!!!! |
@@ -1,7 +1,111 @@
package lotto;
+import camp.nextstep.edu.missionutils.Console;
+import lotto.domain.*;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+
+
public class Application {
+ private static final String REQUEST_PURCHASE_AMOUNT = "๊ตฌ์
๊ธ์ก์ ์
๋ ฅํด ์ฃผ์ธ์.";
+ private static final String REQUEST_LOTTO_NUMBER = "๋น์ฒจ ๋ฒํธ๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์.";
+ private static final String SHOW_WINNING_STATISTICS = "๋น์ฒจ ํต๊ณ" + "\n" + "---";
+
+ public static int lottery;
+
public static void main(String[] args) {
- // TODO: ํ๋ก๊ทธ๋จ ๊ตฌํ
+
+ getLottery();
+
+ GuessLottoTickets guessLotto = new GuessLottoTickets(lottery);
+ guessLotto.printWinningLottoList();
+
+ WinningLotto winningLotto = getWinningLotto();
+
+ System.out.println(SHOW_WINNING_STATISTICS);
+ Statistics statistics = new Statistics();
+ statistics.printMatchResult(winningLotto.countContainsNumber(guessLotto),
+ winningLotto.containsBonus(guessLotto), lottery);
+
+
+ }
+
+ private static WinningLotto getWinningLotto() {
+ Lotto winningLotto = generateWinningLotto();
+ Bonus bonus = generateBonus();
+ return new WinningLotto(winningLotto, bonus);
+ }
+
+ private static void getLottery() {
+ while (true) {
+ try {
+ setLottery();
+ break;
+ } catch (IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+ }
+
+ private static void setLottery() {
+ System.out.println(REQUEST_PURCHASE_AMOUNT);
+ int price = getNumber();
+
+ if (price % 1000 != 0) {
+ throw new IllegalArgumentException("[ERROR] ์ฒ์ ๋จ์๋ก ์
๋ ฅํด์ฃผ์ธ์.");
+ }
+
+ lottery = price / 1000;
+ System.out.println(lottery + "๊ฐ๋ฅผ ๊ตฌ๋งคํ์ต๋๋ค.");
+
+
+ if (lottery < 1) {
+ throw new IllegalArgumentException("[ERROR] ํ ์ฅ ์ด์ ๊ตฌ๋งคํ์ธ์.");
+ }
+ }
+
+ private static Bonus generateBonus() {
+ while (true) {
+ try {
+ System.out.println("๋ณด๋์ค ๋ฒํธ๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์.");
+ int number = getNumber();
+ return new Bonus(number);
+ } catch (IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+ }
+
+ private static Lotto generateWinningLotto() {
+ while (true) {
+ try {
+ System.out.println(REQUEST_LOTTO_NUMBER);
+ String[] splittedNumbers = Console.readLine().split(",");
+ List<Integer> numbers = toNumbers(splittedNumbers);
+ return new Lotto(numbers);
+ } catch (IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+ }
+
+ private static int getNumber() {
+ try {
+ return Integer.parseInt(Console.readLine());
+ } catch (NumberFormatException e) {
+ throw new NumberFormatException("[ERROR] ์ซ์๋ฅผ ์
๋ ฅํ์ธ์.");
+ }
+ }
+
+ private static List<Integer> toNumbers(String[] splittedNumbers) {
+ try {
+ return Arrays.stream(splittedNumbers)
+ .map(Integer::parseInt)
+ .collect(Collectors.toList());
+ } catch (NumberFormatException e) {
+ throw new NumberFormatException("[ERROR] ์ซ์๋ง ์
๋ ฅํ์ธ์.");
+ }
}
} | Java | ์์ฃผ ํน๋ณํ ๊ฒฝ์ฐ๊ฐ ์๋๋ผ๋ฉด, static๋ณ์๋ฅผ ๋ง๋ค๊ณ , ๊ทธ ๊ฐ์ ๊ด๋ฆฌํ๋ application์ ๋ง๋๋ ๊ฒ์ ์ข์ ๋ฐฉ๋ฒ์ ์๋๋๋ค. ์๋ํ๋ฉด, ์ด๋ ๊ฒ ํ์๋ฉด, ํ๋์ ์ดํ๋ฆฌ์ผ์ด์
์ lottery๋ณ์๋ ํ๋๋ฐ์ ์๊ฒ ๋๊ณ , ๊ทธ๋ ๊ฒ ๋๋ฉด, ๋ ๋ช
์ด์์ด ์ด ๋ก์ง์ ์ฌ์ฉํ ๊ฒฝ์ฐ ๋ฌธ์ ๊ฐ ์๊ธธ ์ ์๊ธฐ ๋๋ฌธ์
๋๋ค. ์ฆ ํ์ฅ์ฑ์ ๋ฌธ์ ๊ฐ ์๊น๋๋ค. |
@@ -1,7 +1,111 @@
package lotto;
+import camp.nextstep.edu.missionutils.Console;
+import lotto.domain.*;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+
+
public class Application {
+ private static final String REQUEST_PURCHASE_AMOUNT = "๊ตฌ์
๊ธ์ก์ ์
๋ ฅํด ์ฃผ์ธ์.";
+ private static final String REQUEST_LOTTO_NUMBER = "๋น์ฒจ ๋ฒํธ๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์.";
+ private static final String SHOW_WINNING_STATISTICS = "๋น์ฒจ ํต๊ณ" + "\n" + "---";
+
+ public static int lottery;
+
public static void main(String[] args) {
- // TODO: ํ๋ก๊ทธ๋จ ๊ตฌํ
+
+ getLottery();
+
+ GuessLottoTickets guessLotto = new GuessLottoTickets(lottery);
+ guessLotto.printWinningLottoList();
+
+ WinningLotto winningLotto = getWinningLotto();
+
+ System.out.println(SHOW_WINNING_STATISTICS);
+ Statistics statistics = new Statistics();
+ statistics.printMatchResult(winningLotto.countContainsNumber(guessLotto),
+ winningLotto.containsBonus(guessLotto), lottery);
+
+
+ }
+
+ private static WinningLotto getWinningLotto() {
+ Lotto winningLotto = generateWinningLotto();
+ Bonus bonus = generateBonus();
+ return new WinningLotto(winningLotto, bonus);
+ }
+
+ private static void getLottery() {
+ while (true) {
+ try {
+ setLottery();
+ break;
+ } catch (IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+ }
+
+ private static void setLottery() {
+ System.out.println(REQUEST_PURCHASE_AMOUNT);
+ int price = getNumber();
+
+ if (price % 1000 != 0) {
+ throw new IllegalArgumentException("[ERROR] ์ฒ์ ๋จ์๋ก ์
๋ ฅํด์ฃผ์ธ์.");
+ }
+
+ lottery = price / 1000;
+ System.out.println(lottery + "๊ฐ๋ฅผ ๊ตฌ๋งคํ์ต๋๋ค.");
+
+
+ if (lottery < 1) {
+ throw new IllegalArgumentException("[ERROR] ํ ์ฅ ์ด์ ๊ตฌ๋งคํ์ธ์.");
+ }
+ }
+
+ private static Bonus generateBonus() {
+ while (true) {
+ try {
+ System.out.println("๋ณด๋์ค ๋ฒํธ๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์.");
+ int number = getNumber();
+ return new Bonus(number);
+ } catch (IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+ }
+
+ private static Lotto generateWinningLotto() {
+ while (true) {
+ try {
+ System.out.println(REQUEST_LOTTO_NUMBER);
+ String[] splittedNumbers = Console.readLine().split(",");
+ List<Integer> numbers = toNumbers(splittedNumbers);
+ return new Lotto(numbers);
+ } catch (IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+ }
+
+ private static int getNumber() {
+ try {
+ return Integer.parseInt(Console.readLine());
+ } catch (NumberFormatException e) {
+ throw new NumberFormatException("[ERROR] ์ซ์๋ฅผ ์
๋ ฅํ์ธ์.");
+ }
+ }
+
+ private static List<Integer> toNumbers(String[] splittedNumbers) {
+ try {
+ return Arrays.stream(splittedNumbers)
+ .map(Integer::parseInt)
+ .collect(Collectors.toList());
+ } catch (NumberFormatException e) {
+ throw new NumberFormatException("[ERROR] ์ซ์๋ง ์
๋ ฅํ์ธ์.");
+ }
}
} | Java | ```suggestion
private static boolean setLottery() {
System.out.println(REQUEST_PURCHASE_AMOUNT);
int price = getNumber();
if (price % 1000 != 0) {
System.out.println("[ERROR] ์ฒ์ ๋จ์๋ก ์
๋ ฅํด์ฃผ์ธ์.");
return false;
}
lottery = price / 1000;
System.out.println(lottery + "๊ฐ๋ฅผ ๊ตฌ๋งคํ์ต๋๋ค.");
if (lottery < 1) {
System.out.println("[ERROR] ํ ์ฅ ์ด์ ๊ตฌ๋งคํ์ธ์.");
return false;
}
return true;
}
``` |
@@ -0,0 +1,80 @@
+## ๋ก๋
+
+### ๊ท์น
+1. ๋ก๋ ๋ฒํธ์ ์ซ์ ๋ฒ์๋ 1~45๊น์ง ์ด๋ค.
+2. ๋ก๋ ๋ฒํธ๋ ์ด 6๊ฐ์ ์ซ์๋ก ์ด๋ฃจ์ด์ ธ์๋ค.
+3. ๋ณต๊ถ์ ํ์ฅ๋น 1,000์์ด๋ค.
+4. ์ฌ์ฉ์๋ ๊ตฌ์
ํ ๋ณต๊ถ ์ฅ ์ ๋งํผ ๋น์ฒจ์ ๊ณ์ฐํ๋ค.
+5. ์ฌ์ฉ์๋ ๋น์ฒจ ๋ฒํธ์ ๋ณด๋์ค ๋ฒํธ๋ฅผ ์
๋ ฅํ๋ค.
+6. ๊ตฌ๋งคํ ๋ก๋ ๋ฒํธ์ ๋น์ฒจ ๋ฒํธ๋ฅผ ๋น๊ตํ์ฌ ๋น์ฒจ ๊ธฐ์ค์ ๋ฐ๋ผ ๊ธ์ก์ ๋ฐ๋๋ค. ๋น์ฒจ ๊ธฐ์ค๊ณผ ๊ธ์ก์ ์๋์ ๊ฐ๋ค.
+ - 1๋ฑ: 6๊ฐ ๋ฒํธ ์ผ์น / 2,000,000,000์
+ - 2๋ฑ: 5๊ฐ ๋ฒํธ + ๋ณด๋์ค ๋ฒํธ ์ผ์น / 30,000,000์
+ - 3๋ฑ: 5๊ฐ ๋ฒํธ ์ผ์น / 1,500,000์
+ - 4๋ฑ: 4๊ฐ ๋ฒํธ ์ผ์น / 50,000์
+ - 5๋ฑ: 3๊ฐ ๋ฒํธ ์ผ์น / 5,000์
+7. ์ฌ์ฉ์๊ฐ ์๋ชป๋ ๊ฐ ์
๋ ฅํ ๊ฒฝ์ฐ ์๋ฌ๋ฉ์ธ์ง ์ถ๋ ฅ ํ,๋ถ๋ถ๋ถํฐ ์
๋ ฅ์ ๋ค์ ๋ฐ๋๋ค.
+
+### ํ๋ก๊ทธ๋๋ฐ ์๊ตฌ ์ฌํญ
+1. ํจ์(๋๋ ๋ฉ์๋)๊ฐ ํ ๊ฐ์ง ์ผ๋ง ํ๋๋ก ์ต๋ํ ์๊ฒ ๋ง๋ค์ด๋ผ.
+2. ํจ์(๋๋ ๋ฉ์๋)์ ๊ธธ์ด๊ฐ 15๋ผ์ธ์ ๋์ด๊ฐ์ง ์๋๋ก ๊ตฌํํ๋ค.
+3. indent(์ธ๋ดํธ, ๋ค์ฌ์ฐ๊ธฐ) depth๋ฅผ 3์ด ๋์ง ์๋๋ก ๊ตฌํํ๋ค. 2๊น์ง๋ง ํ์ฉํ๋ค.
+4. 3ํญ ์ฐ์ฐ์๋ฅผ ์ฐ์ง ์๋๋ค.
+5. else ์์ฝ์ด๋ฅผ ์ฐ์ง ์๋๋ค. switch/case๋ ํ์ฉํ์ง ์๋๋ค.
+6. Java Enum์ ์ ์ฉํ๋ค.
+7. ๋๋ฉ์ธ ๋ก์ง์ ๋จ์ ํ
์คํธ๋ฅผ ๊ตฌํํด์ผ ํ๋ค. ๋จ, UI(System.out, System.in, Scanner) ๋ก์ง์ ์ ์ธํ๋ค๋๋ฉ์ธ ๋ก์ง์ ๋จ์ ํ
์คํธ๋ฅผ ๊ตฌํํด์ผ ํ๋ค. ๋จ, UI(System.out, System.in, Scanner) ๋ก์ง์ ์ ์ธํ๋ค.
+8. ํต์ฌ ๋ก์ง์ ๊ตฌํํ๋ ์ฝ๋์ UI๋ฅผ ๋ด๋นํ๋ ๋ก์ง์ ๋ถ๋ฆฌํด ๊ตฌํํ๋ค.
+
+### ์ฃผ์ ๊ฐ์ฒด
+- ๋ก๋
+- ์ฌ์ฉ์
+- ํต๊ณ
+
+### ์ฃผ์ ๊ฐ์ฒด๋ค์ ์์ฑ๊ณผ ์ญํ
+- ๋ก๋
+ - 1๋ถํฐ 45๊น์ง ์๋ก ๋ค๋ฅธ 6๊ฐ์ ์ซ์๋ฅผ ๊ฐ์ง๊ณ ์๋ค.
+ - 6๊ฐ ์ซ์๋ฅผ ๋ฝ์์ ์ค๋ค.
+
+- ๋น์ฒจ ๋ก๋๋ฒํธ
+ - ๋น์ฒจ ๋ก๋๋ฒํธ๋ฅผ ๋ฐํํ๋ค.
+ - ๋ฐํ๋ ๋ก๋๋ฒํธ ๋ฆฌ์คํธ๋ฅผ ๊ฐ์ง๊ณ ์๋ค.
+ - ๋น์ฒจ ๋ฒํธ์ ์ผ์นํ๋ ๊ฐฏ์๋ฅผ ํ์ธํ๋ค.
+
+- ํต๊ณ
+ - ์์ต๋ฅ ์ ๋ธ๋ค.
+### ๊ธฐ๋ฅ ์ ์
+1. ์
๋ ฅ
+- [x] ๋ก๋ ๊ตฌ์
๊ธ์ก์ ์
๋ ฅ ๋ฐ๋๋ค.
+- [x] ๋น์ฒจ ๋ฒํธ๋ฅผ ์
๋ ฅ ๋ฐ๋๋ค. ๋ฒํธ๋ ์ผํ(,)๋ฅผ ๊ธฐ์ค์ผ๋ก ๊ตฌ๋ถํ๋ค.
+- [x] ๋ณด๋์ค ๋ฒํธ๋ฅผ ์
๋ ฅ ๋ฐ๋๋ค.
+
+2. ์ถ๋ ฅ
+- [x] ๋ฐํํ ๋ก๋ ์๋ ๋ฐ ๋ฒํธ๋ฅผ ์ถ๋ ฅํ๋ค. ๋ก๋ ๋ฒํธ๋ ์ค๋ฆ์ฐจ์์ผ๋ก ์ ๋ ฌํ์ฌ ๋ณด์ฌ์ค๋ค.
+- [x] ๋น์ฒจ ๋ด์ญ์ ์ถ๋ ฅํ๋ค.
+- [x] ๋ฒํธ ๋ฒ์๊ฐ ๋์ด๊ฐ ์์ ์๋ฌ๋ฌธ๊ตฌ ์ถ๋ ฅํ๋ค.
+
+3. ๋ก๋ ๋ฒํธ
+- [x] 6๊ฐ ์ซ์๋ฅผ ๊ฐ์ง๋ค.
+- [x] 6๊ฐ์ธ์ง ํ์ธํ๋ค.
+- [x] ์ซ์ ํฌํจ์ฌ๋ถ๋ฅผ ํ์ธํด ํฌํจ ๊ฐ์๋ฅผ ๋ฐํํ๋ค.
+
+4. ์ถ์ธก ๋ก๋
+- [x] ๋ก๋ ๋ฒํธ๋ฅผ ์์ฑํ๋ค.
+
+5. ์ถ์ธก ๋ก๋ ํฐ์ผ๋ค
+- [x] ๊ฐ์ง ๋ก๋ ๋ฒํธ๋ค์ด๋ ๋น์ฒจ ๋ฒํธ๋ ๋น๊ตํ๋ค.
+
+6. ๋น์ฒจ ๋ฒํธ
+- [x] ๋ก๋ ๋ฒํธ์ ๋ณด๋์ค ์ซ์๋ฅผ ๊ฐ์ง๋ค.
+
+7. ํต๊ณ
+- [x] ๋น์ฒจ ํ๋ฅ ์ ๊ฒ์ฐํ๋ค.
+- [x] ๋ก๋ ๋ฒํธ์ ๋น์ฒจ ๋ด์ญ์ ๊ณ์ฐํ๋ค.
+
+### ์ปค๋ฐ ์ปจ๋ฒค์
+[commit_type] : commit_message
+- [Feature]: ์๋ก์ด ๊ธฐ๋ฅ์ ์ถ๊ฐํ๋ ๊ฒฝ์ฐ
+- [Bugfix]: ๋ฒ๊ทธ๋ฅผ ์์ ํ๋ ๊ฒฝ์ฐ
+- [Refactor]: ์ฝ๋ ๋ฆฌํฉํ ๋ง์ ์ํํ๋ ๊ฒฝ์ฐ
+- [Docs]: ๋ฌธ์๋ฅผ ์
๋ฐ์ดํธํ๋ ๊ฒฝ์ฐ
+- [Style]: ์ฝ๋ ์คํ์ผ ๋ณ๊ฒฝ ๋๋ ํฌ๋งทํ
์ ์ํํ๋ ๊ฒฝ์ฐ
+- [Test]: ํ
์คํธ ๊ด๋ จ ๋ณ๊ฒฝ์ ์ํํ๋ ๊ฒฝ์ฐ | Unknown | ~~์ด ๋ถ๋ถ์ด ๊ถ๊ธํ๊ฒ ์๋๋ฐ, ์ผ๋ฐ์ ์ผ๋ก ์ฐ๋ฆฌ๊ฐ ๋ก๋๋ฅผ ์ด ๋๋ ๊ทธ๋ฅ ์ซ์ 6๊ฐ๋ฅผ ์ ํํ๊ณ , 2๋ฑ์ ๋ฝ์ ๋, ๋ณด๋์ค ๋ฒํธ๋ฅผ ์ถ์ฒจํด์ ๋น๊ตํ๋๋ฐ, ์ด๊ฒ๊ณผ๋ ๋ค๋ฅธ ์๊ตฌ์ฌํญ์ด์๋ ๊ฒ์ธ๊ฐ์?~~
์ // ์ฝ๋ ํ์ธํ์ต๋๋ค. WinningLotto๋ผ๋ ํด๋์ค๊ฐ ์๋ ๊ฒ์ด๊ตฐ์. |
@@ -1,8 +1,8 @@
'use client';
import { ReactNode } from 'react';
-import { useInView } from 'react-intersection-observer';
+import { keyframes } from '@emotion/react';
import { Box, Card, CardMedia, SxProps, Typography } from '@mui/material';
import { Theme } from '@mui/system';
@@ -14,40 +14,49 @@ interface CommentCardProps {
isFilled?: boolean;
isCharacter?: boolean;
isChat?: boolean;
+ isFixed?: boolean;
sx?: SxProps<Theme>;
+ positionY?: string;
}
+const gradientAnimation = keyframes`
+ 0% {
+ background-position: 0% 50%;
+ }
+ 50% {
+ background-position: 100% 50%;
+ }
+ 100% {
+ background-position: 0% 50%;
+ }
+`;
+
const CommentCard = ({
content,
isStroke = false,
isFilled = false,
isCharacter = false,
isChat = false,
+ isFixed = false,
sx,
+ positionY = '40px',
}: CommentCardProps) => {
- const { ref, inView } = useInView({
- threshold: 0.1,
- });
-
return (
<Card
- ref={ref}
sx={{
display: 'flex',
boxShadow: 'none',
alignItems: 'center',
bgcolor: 'transparent',
- ...(isChat && {
- opacity: inView ? 1 : 0,
- transform: inView ? 'translateY(0)' : 'translateY(20px)',
- transition: 'opacity 0.6s ease-out, transform 0.6s ease-out',
- }),
- ...(!isChat && {
- width: '100%',
- }),
- ...(!isCharacter && {
- mb: 1.3,
- }),
+ position: isFixed ? 'fixed' : 'relative',
+ bottom: isFixed ? positionY : 'unset',
+ right: isFixed ? '20px' : 'unset',
+ zIndex: isFixed ? 9999 : 'unset',
+ transition: 'transform 0.3s ease-in-out',
+ '&:hover': {
+ transform: 'scale(1.1)',
+ },
+ ...sx,
}}
>
{isCharacter && (
@@ -59,19 +68,21 @@ const CommentCard = ({
borderRadius: 5,
ml: 1,
padding: '2px',
- background: isStroke ? `linear-gradient(${color.gradient_blue_dark}, ${color.gradient_blue_light})` : 'none',
- ...(!isChat && {
- width: '100%',
- }),
+ background: isStroke
+ ? `linear-gradient(45deg, ${color.gradient_blue_dark}, ${color.gradient_blue_light})`
+ : 'none',
+ width: '100%',
}}
>
<Box
borderRadius="18px"
padding={2}
sx={{
background: isFilled
- ? `linear-gradient(${color.gradient_blue_dark}, ${color.gradient_blue_light})`
+ ? `linear-gradient(45deg, ${color.gradient_blue_dark}, ${color.gradient_blue_light})`
: 'white',
+ backgroundSize: '200% 200%',
+ animation: isFixed && isFilled ? `${gradientAnimation} 6s ease infinite` : 'none',
...sx,
}}
> | Unknown | ์ธ์ฌ์ดํธ์ ์ฑ๋ด์ ํฌํจํ ๋ชจ๋ ๋งํ์ ์นด๋์ ๋ง์ฐ์ค๋ฅผ ํธ๋ฒํ๋ฉด ์ปค์ง๋ ํจ๊ณผ๊ฐ ๋ํ๋์ ์กฐ๊ฑด์ ์ฃผ์
์ผ ํ ๊ฒ ๊ฐ์์~!
์ง๊ธ ๋น์ฅ ์ฐ์ด๋ ๊ณณ์ด ์ด๊ฒ๋ฐ์ ์์ผ๋ `isFixed`๋ก ํ๊ฑฐ๋ ๋ค๋ฅธ ์์ฑ ํ๋ ์ถ๊ฐํด์ฃผ์
๋ ๋๊ณ ๋ง์๋๋ก ํ์์ง์ฉ~! |
@@ -0,0 +1,65 @@
+package oncall.domain.date;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class Day {
+ private static final String WEEK_HOLIDAY_MESSAGE = "(ํด์ผ) ";
+
+ private final Month month;
+ private final Date date;
+ private final DayOfWeek dayOfWeek;
+
+ public Day(Month month, Date date, DayOfWeek dayOfWeek) {
+ this.month = month;
+ this.date = date;
+ this.dayOfWeek = dayOfWeek;
+ }
+
+ public Day makeNextDay() {
+ return new Day(month, date.makeNextDate(), dayOfWeek.getNextDayOfWeek());
+ }
+
+ public DateType checkDateType() {
+ if (isWeekend()) {
+ return DateType.WEEKEND;
+ }
+ if (isHoliday()) {
+ return DateType.WEEK_HOLIDAY;
+ }
+ return DateType.WEEK;
+ }
+
+ private boolean isWeekend() {
+ return DayOfWeek.checkWeekend(dayOfWeek);
+ }
+
+ private boolean isHoliday() {
+ return Holidays.checkHoliday(month, date);
+ }
+
+ private boolean isWeekHoliday() {
+ return !isWeekend() && isHoliday();
+ }
+
+ public Month getMonth() {
+ return month;
+ }
+
+ public int getTotalDate() {
+ return month.getTotalDate();
+ }
+
+ @Override
+ public String toString() {
+ List<String> stringBuffer = new ArrayList<>();
+ stringBuffer.add(month.toString());
+ stringBuffer.add(date.toString());
+ stringBuffer.add(dayOfWeek.toString());
+ if (this.isWeekHoliday()) {
+ stringBuffer.add(WEEK_HOLIDAY_MESSAGE);
+ }
+ return stringBuffer.stream().collect(Collectors.joining(" ",""," "));
+ }
+} | Java | ์ ๋ ๋์น ๋ถ๋ถ์ด๊ธด ํ๋ฐ, "(ํด์ผ)"์ ๋ถ์ด๋ ๊ฒฝ์ฐ๊ฐ ๋ฌด์กฐ๊ฑด ๊ณตํด์ผ์ธ ๊ฒฝ์ฐ์ ๋ถ์ด๋ ๊ฒ์ด ์๋๋ผ ์ฃผ๋ง์ด ์๋ ๊ณตํด์ผ์๋ง ๋ถ์ด๋ ์กฐ๊ฑด์ด๋๋ผ๊ตฌ์..! |
@@ -0,0 +1,54 @@
+package oncall.domain.employee;
+
+import java.util.List;
+import oncall.util.exception.ErrorMessage;
+import oncall.util.exception.MyIllegalArgumentException;
+
+public class EmployeeRepository {
+ private static final int MIN_EMPLOYEES_NUMBER = 5;
+ private static final int MAX_EMPLOYEES_NUMBER = 35;
+
+ private final List<WeekWorkEmployee> weekWorkEmployees;
+ private final List<WeekendWorkEmployee> weekendWorkEmployees;
+
+ public EmployeeRepository(List<WeekWorkEmployee> weekWorkEmployees,
+ List<WeekendWorkEmployee> weekendWorkEmployees) {
+ validateEmployees(weekWorkEmployees, weekendWorkEmployees);
+
+ this.weekWorkEmployees = weekWorkEmployees;
+ this.weekendWorkEmployees = weekendWorkEmployees;
+ }
+
+ private void validateEmployees(List<WeekWorkEmployee> weekWorkEmployees,
+ List<WeekendWorkEmployee> weekendWorkEmployees) {
+ if (weekWorkEmployees.size() < MIN_EMPLOYEES_NUMBER || weekWorkEmployees.size() > MAX_EMPLOYEES_NUMBER) {
+ throw new MyIllegalArgumentException(ErrorMessage.WRONG_EMPLOYEE_NUMBER);
+ }
+ validateSameWeekWorkEmployee(weekWorkEmployees);
+ validateSameWeekendWorkEmployee(weekendWorkEmployees);
+ }
+
+ private static void validateSameWeekendWorkEmployee(List<WeekendWorkEmployee> weekendWorkEmployees) {
+ if (weekendWorkEmployees.stream().distinct().count() != weekendWorkEmployees.size()) {
+ throw new MyIllegalArgumentException(ErrorMessage.NOT_SAME_EMPLOYEE_IN_ONE_WORK);
+ }
+ }
+
+ private static void validateSameWeekWorkEmployee(List<WeekWorkEmployee> weekWorkEmployees) {
+ if (weekWorkEmployees.stream().distinct().count() != weekWorkEmployees.size()) {
+ throw new MyIllegalArgumentException(ErrorMessage.NOT_SAME_EMPLOYEE_IN_ONE_WORK);
+ }
+ }
+
+ public WeekWorkEmployee getWeekWorkEmployee(int index) {
+ return weekWorkEmployees.get(index);
+ }
+
+ public WeekendWorkEmployee getWeekendWorkEmployees(int index) {
+ return weekendWorkEmployees.get(index);
+ }
+
+ public int getNumberOfEmployee() {
+ return weekWorkEmployees.size();
+ }
+} | Java | ์ค๋ณตํ์ธ ๋ก์ง์ ๋ฉ์๋๋ก ๋ถ๋ฆฌํ ๊ฒ ์ฒ๋ผ ๊ธธ์ด ๊ฒ์ฆ๋ ๋ฉ์๋๋ก ๋ถ๋ฆฌํ๋ฉด ์ข์ ๊ฑฐ ๊ฐ๋ค์! |
@@ -0,0 +1,33 @@
+package oncall.domain.schedule;
+
+import java.util.List;
+import oncall.domain.date.Day;
+import oncall.domain.employee.Employee;
+
+public class DaySchedule {
+ private final Day day;
+ private final Employee employee;
+
+ public DaySchedule(Day day, Employee employee) {
+ this.day = day;
+ this.employee = employee;
+ }
+
+ public static boolean isContinuousWork(DaySchedule daySchedule_pre, DaySchedule daySchedule_post) {
+ return daySchedule_pre.employee.equals(daySchedule_post.employee);
+ }
+
+ public boolean isWeek() {
+ return day.checkDateType().isWeek();
+ }
+
+ public List<DaySchedule> changeEmployee(DaySchedule otherDaySchedule) {
+ DaySchedule firstDaySchedule = new DaySchedule(this.day, otherDaySchedule.employee);
+ DaySchedule secondDaySchedule = new DaySchedule(otherDaySchedule.day, this.employee);
+ return List.of(firstDaySchedule, secondDaySchedule);
+ }
+
+ public String toString() {
+ return day.toString() + employee.getName();
+ }
+} | Java | ์ด๋ถ๋ถ ์๋ฐ ์ปจ๋ฒค์
์ ๋ฐ๋ผ ์นด๋ฉ์ผ์ด์ค๋ฅผ ์ฌ์ฉํ๋๊ฒ ์ข์ ๊ฑฐ ๊ฐ๊ตฐ์! ์๋๋ฉด ํน์ ์ด๋ถ๋ถ๋ง ์ค๋ค์ดํฌ์ผ์ด์ค๋ฅผ ์ฌ์ฉํ์ ์ด์ ๊ฐ ์์ผ์ ๊ฑธ๊น์? |
@@ -0,0 +1,33 @@
+package oncall.domain.schedule;
+
+import java.util.List;
+import oncall.domain.date.Day;
+import oncall.domain.employee.Employee;
+
+public class DaySchedule {
+ private final Day day;
+ private final Employee employee;
+
+ public DaySchedule(Day day, Employee employee) {
+ this.day = day;
+ this.employee = employee;
+ }
+
+ public static boolean isContinuousWork(DaySchedule daySchedule_pre, DaySchedule daySchedule_post) {
+ return daySchedule_pre.employee.equals(daySchedule_post.employee);
+ }
+
+ public boolean isWeek() {
+ return day.checkDateType().isWeek();
+ }
+
+ public List<DaySchedule> changeEmployee(DaySchedule otherDaySchedule) {
+ DaySchedule firstDaySchedule = new DaySchedule(this.day, otherDaySchedule.employee);
+ DaySchedule secondDaySchedule = new DaySchedule(otherDaySchedule.day, this.employee);
+ return List.of(firstDaySchedule, secondDaySchedule);
+ }
+
+ public String toString() {
+ return day.toString() + employee.getName();
+ }
+} | Java | @Override ์ ๋
ธํ
์ด์
์ ๋ถ์ฌ์ฃผ๋ ๊ฒ์ด ์ข์ ๊ฑฐ ๊ฐ์์ |
@@ -0,0 +1,24 @@
+package oncall.util.exception;
+
+public enum ErrorMessage {
+ WRONG_DELIMITER ("[ERROR]", "๊ตฌ๋ถ์๋ฅผ ์๋ชป ์
๋ ฅํ์
จ์ต๋๋ค. ์ฝค๋ง(,) ๋ฅผ ์ฌ์ฉํด์ฃผ์ธ์."),
+ NOT_NUMBER ("[ERROR]", "์์๋ ์ซ์๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์."),
+ NOT_DAY_OF_WEEK ("[ERROR]", "์๋ชป๋ ์์ผ์ ์
๋ ฅํ์ต๋๋ค."),
+ WRONG_MONTH_VALUE("[ERROR]", "์์๋ 0~12์ ์ซ์๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์."),
+ WRONG_EMPLOYEE_NUMBER("[ERROR]", "์ง์ ์ซ์๋ ์ต์ 5๋ช
, ์ต๋ 35๋ช
์
๋๋ค."),
+ NOT_SAME_EMPLOYEE_IN_ONE_WORK("[ERROR]", "ํ์ผ, ํน์ ํด์ผ ๋น์๊ทผ๋ฌด ์ค์ผ์ฅด์ ์ค๋ณต ์ธ์์ด ๋ค์ด๊ฐ ์ ์์ต๋๋ค."),
+ TOO_LONG_EMPLOYEE_NAME("[ERROR]", "์์ง์์ ์ด๋ฆ์ 5์๊น์ง ๊ฐ๋ฅํฉ๋๋ค");
+
+
+ private final String suffix;
+ private final String errorMessage;
+
+ ErrorMessage(String suffix, String errorMessage) {
+ this.suffix = suffix;
+ this.errorMessage = errorMessage;
+ }
+
+ public String makeErrorMessage() {
+ return String.join(" ", suffix, errorMessage);
+ }
+} | Java | ์์๋ 1~12์ ์ซ์๋ฅผ ์
๋ ฅํด๋ฌ๋ผ๋ ๋ฉ์ธ์ง๊ฐ ๋ง์ง ์๋์? |
@@ -0,0 +1,60 @@
+package oncall.view;
+
+
+import camp.nextstep.edu.missionutils.Console;
+import java.util.List;
+import oncall.util.converter.ViewConverter;
+import oncall.util.exception.ErrorMessage;
+import oncall.util.exception.MyIllegalArgumentException;
+import oncall.view.dto.InputMonthAndDayDto;
+
+public class InputView {
+ private static final String INPUT_START_MONTH_AND_DAY_MESSAGE = "๋น์ ๊ทผ๋ฌด๋ฅผ ๋ฐฐ์ ํ ์๊ณผ ์์ ์์ผ์ ์
๋ ฅํ์ธ์> ";
+ private static final String INPUT_WEEK_WORK_EMPLOYEE_MESSAGE = "ํ์ผ ๋น์ ๊ทผ๋ฌด ์๋ฒ๋๋ก ์ฌ์ ๋๋ค์์ ์
๋ ฅํ์ธ์> ";
+ private static final String INPUT_WEEKEND_WORK_EMPLOYEE_MESSAGE = "ํด์ผ ๋น์ ๊ทผ๋ฌด ์๋ฒ๋๋ก ์ฌ์ ๋๋ค์์ ์
๋ ฅํ์ธ์> ";
+ private static final String DELIMITER = ",";
+
+ private final ViewConverter viewConverter;
+
+ public InputView(ViewConverter viewConverter) {
+ this.viewConverter = viewConverter;
+ }
+
+ public InputMonthAndDayDto readMonthAndDay() {
+ System.out.println(INPUT_START_MONTH_AND_DAY_MESSAGE);
+ String inputMessage = Console.readLine();
+ if (!inputMessage.contains(DELIMITER)) {
+ throw new MyIllegalArgumentException(ErrorMessage.WRONG_DELIMITER);
+ }
+ String[] splitInput = inputMessage.split(DELIMITER);
+ validateMonthIsNumber(splitInput);
+
+ return viewConverter.convertToInputMonthAndDayDto(splitInput);
+ }
+
+ private static void validateMonthIsNumber(String[] splitInput) {
+ try {
+ Integer.parseInt(splitInput[0]);
+ } catch (NumberFormatException e) {
+ throw new MyIllegalArgumentException(ErrorMessage.NOT_NUMBER);
+ }
+ }
+
+ public List<String> readWeekWorkEmployee() {
+ System.out.println(INPUT_WEEK_WORK_EMPLOYEE_MESSAGE);
+ return readEmployeeName();
+ }
+
+ public List<String> readWeekendWorkEmployee() {
+ System.out.println(INPUT_WEEKEND_WORK_EMPLOYEE_MESSAGE);
+ return readEmployeeName();
+ }
+
+ private static List<String> readEmployeeName() {
+ String inputMessage = Console.readLine();
+ if (!inputMessage.contains(DELIMITER)) {
+ throw new MyIllegalArgumentException(ErrorMessage.WRONG_DELIMITER);
+ }
+ return List.of(inputMessage.split(DELIMITER));
+ }
+} | Java | ์ฌ์ํ๊ธด ํ์ง๋ง ์์ ์
๋ ฅ ํํ๋ณด๋ฉด "๋น์ ๊ทผ๋ฌด๋ฅผ ๋ฐฐ์ ํ ์๊ณผ ์์ ์์ผ์ ์
๋ ฅํ์ธ์> " ๋ฉ์์ง ๋ฐ๋ก ์์์๋ถํฐ ์
๋ ฅํ ์ ์๋ ํํ์
๋๋ค!
System.out.println(...) ๋์ System.out.print() ๋ฅผ ์ฌ์ฉํ๋ฉด ์์ฒ๋ผ ํ์ค ๋ฐ์ด์ ์
๋ ฅ๋ฐ๋๊ฒ ์๋๋ผ ์ถ๋ ฅํ๊ณ ๋ฐ๋ก ๋ค์ ์
๋ ฅ๋ฐ์ ์ ์์ต๋๋ค |
@@ -0,0 +1,78 @@
+package oncall.domain.schedule;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+import oncall.domain.date.Month;
+
+public class MonthSchedule {
+ private final Month month;
+ private final List<DaySchedule> daySchedules;
+
+ public MonthSchedule(Month month, List<DaySchedule> daySchedules) {
+ this.month = month;
+ this.daySchedules = daySchedules;
+ }
+
+ public MonthSchedule adjustSchedule() {
+ List<DaySchedule> continuousWork = findContinuousWork();
+ if (continuousWork.isEmpty()) {
+ return this;
+ }
+
+ List<DaySchedule> newDaySchedule = new ArrayList<>(daySchedules);
+ for (DaySchedule daySchedule : continuousWork) {
+ DaySchedule nextSameDateType = findNextSameDateType(daySchedule);
+ int indexOne = daySchedules.indexOf(daySchedule);
+ int indexTwo = daySchedules.indexOf(nextSameDateType);
+ List<DaySchedule> newDaySchedules = daySchedule.changeEmployee(nextSameDateType);
+ newDaySchedule.set(indexOne, newDaySchedules.get(0));
+ newDaySchedule.set(indexTwo, newDaySchedules.get(1));
+ }
+ MonthSchedule newMonthSchedule = new MonthSchedule(month, newDaySchedule);
+ if (!newMonthSchedule.findContinuousWork().isEmpty()) {
+ adjustSchedule();
+ }
+ return new MonthSchedule(month, newDaySchedule);
+ }
+
+ private DaySchedule findNextSameDateType(DaySchedule daySchedule) {
+ int index = daySchedules.indexOf(daySchedule);
+ DaySchedule nextDaySchedule;
+ if (daySchedule.isWeek()) {
+ do {
+ index += 1;
+ nextDaySchedule = daySchedules.get(index);
+ } while (nextDaySchedule.isWeek());
+ return daySchedules.get(index);
+ }
+ do {
+ index += 1;
+ nextDaySchedule = daySchedules.get(index);
+ } while (!nextDaySchedule.isWeek());
+ return daySchedules.get(index);
+ }
+
+ private List<DaySchedule> findContinuousWork() {
+ List<DaySchedule> continuousWorkDaySchedule = new ArrayList<>();
+ for (int index = 0; index < daySchedules.size() - 1; index++) {
+ int index_post = index + 1;
+ DaySchedule daySchedule_pre = daySchedules.get(index);
+ DaySchedule daySchedule_post = daySchedules.get(index_post);
+
+ if (DaySchedule.isContinuousWork(daySchedule_pre, daySchedule_post)) {
+ continuousWorkDaySchedule.add(daySchedule_post);
+ }
+ }
+ return continuousWorkDaySchedule;
+ }
+
+ @Override
+ public String toString() {
+ return daySchedules.stream()
+ .map(DaySchedule::toString)
+ .limit(month.getTotalDate())
+ .collect(Collectors.joining("\n"));
+ }
+
+} | Java | ์ด ๋ถ๋ถ์์ ์ฌ๊ท๋ฅผ ํ์ถํ์ง ๋ชปํด ์คํ์ค๋ฒํ๋ก์ฐ๊ฐ ๋ฐ์ํ๊ณ ์์ด์..! |
@@ -0,0 +1,31 @@
+package oncall.service;
+
+import java.util.ArrayList;
+import java.util.List;
+import oncall.domain.date.Day;
+import oncall.domain.employee.Employee;
+import oncall.domain.employee.EmployeeProvider;
+import oncall.domain.schedule.DaySchedule;
+import oncall.domain.schedule.MonthSchedule;
+
+public class ScheduleService {
+ private static final int BUFFER = 20;
+ private final EmployeeProvider employeeProvider;
+
+ public ScheduleService(EmployeeProvider employeeProvider) {
+ this.employeeProvider = employeeProvider;
+ }
+
+ public MonthSchedule makeMonthSchedule(Day firstDay) {
+ int totalDate = firstDay.getTotalDate();
+ List<DaySchedule> employeeSchedule = new ArrayList<>();
+ Day day = firstDay;
+ for (int i = 0; i < totalDate + BUFFER; i++) {
+ Employee employee = employeeProvider.provideEmployee(day);
+ DaySchedule daySchedule = new DaySchedule(day, employee);
+ employeeSchedule.add(daySchedule);
+ day = day.makeNextDay();
+ }
+ return new MonthSchedule(firstDay.getMonth(), employeeSchedule);
+ }
+} | Java | ์ ๋ฒํผ๋ ์ด๋ค ์ญํ ์ ํ๋์? |
@@ -0,0 +1,24 @@
+package oncall.util.exception;
+
+public enum ErrorMessage {
+ WRONG_DELIMITER ("[ERROR]", "๊ตฌ๋ถ์๋ฅผ ์๋ชป ์
๋ ฅํ์
จ์ต๋๋ค. ์ฝค๋ง(,) ๋ฅผ ์ฌ์ฉํด์ฃผ์ธ์."),
+ NOT_NUMBER ("[ERROR]", "์์๋ ์ซ์๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์."),
+ NOT_DAY_OF_WEEK ("[ERROR]", "์๋ชป๋ ์์ผ์ ์
๋ ฅํ์ต๋๋ค."),
+ WRONG_MONTH_VALUE("[ERROR]", "์์๋ 0~12์ ์ซ์๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์."),
+ WRONG_EMPLOYEE_NUMBER("[ERROR]", "์ง์ ์ซ์๋ ์ต์ 5๋ช
, ์ต๋ 35๋ช
์
๋๋ค."),
+ NOT_SAME_EMPLOYEE_IN_ONE_WORK("[ERROR]", "ํ์ผ, ํน์ ํด์ผ ๋น์๊ทผ๋ฌด ์ค์ผ์ฅด์ ์ค๋ณต ์ธ์์ด ๋ค์ด๊ฐ ์ ์์ต๋๋ค."),
+ TOO_LONG_EMPLOYEE_NAME("[ERROR]", "์์ง์์ ์ด๋ฆ์ 5์๊น์ง ๊ฐ๋ฅํฉ๋๋ค");
+
+
+ private final String suffix;
+ private final String errorMessage;
+
+ ErrorMessage(String suffix, String errorMessage) {
+ this.suffix = suffix;
+ this.errorMessage = errorMessage;
+ }
+
+ public String makeErrorMessage() {
+ return String.join(" ", suffix, errorMessage);
+ }
+} | Java | ```suggestion
private static final String prefix = "[ERROR] ";
```
ํญ์ `prefix` ๋ถ๋ถ์ ์ค๋ณต๋๊ธฐ์ ํด๋น ๋ถ๋ถ์ ์์๋ก ์ถ์ถํ๋ ๊ฒ๋ ๊ด์ฐฎ์ ๊ฒ ๊ฐ๋ค๊ณ ์๊ฐํด์. |
@@ -0,0 +1,43 @@
+package oncall.domain.date;
+
+import java.util.Arrays;
+import oncall.util.exception.ErrorMessage;
+import oncall.util.exception.MyIllegalArgumentException;
+
+public enum Month {
+ JAN(1, 31),
+ FEB(2, 28),
+ MAR(3, 31),
+ APR(4, 30),
+ MAY(5,31),
+ JUN(6, 30),
+ JUL(7, 31),
+ AUG(8, 31),
+ SEP(9, 30),
+ OCT(10, 31),
+ NOV(11, 30),
+ DEC(12, 31);
+ private final int month;
+ private final int totalDate;
+
+ Month(int month, int totalDate) {
+ this.month = month;
+ this.totalDate = totalDate;
+ }
+
+ public int getTotalDate() {
+ return totalDate;
+ }
+
+ public static Month getMonth(int month) {
+ return Arrays.stream(values())
+ .filter(m -> m.month == month)
+ .findAny()
+ .orElseThrow(() -> new MyIllegalArgumentException(ErrorMessage.WRONG_MONTH_VALUE));
+ }
+
+ @Override
+ public String toString() {
+ return month + "์";
+ }
+} | Java | ํด๋น ํด๋์ค๋ `java.time.Month` enum์ผ๋ก ์๋ฒฝํ ๋์ฒด ๊ฐ๋ฅํ ๊ฒ ๊ฐ์ต๋๋ค!
(๋ฌผ๋ก ์ ๋ ์ด ์ฌ์ค์ ์ํ์ด ๋๋ ํ ๊นจ๋ฌ์์ต๋๋ค...ใ
ใ
) |
@@ -0,0 +1,43 @@
+package oncall.domain.date;
+
+import java.util.Arrays;
+import java.util.Objects;
+import oncall.util.exception.ErrorMessage;
+import oncall.util.exception.MyIllegalArgumentException;
+
+public enum DayOfWeek {
+ SUN(0, "์ผ"), MON(1, "์"), TUE(2, "ํ"), WED(3, "์"),
+ THU(4, "๋ชฉ"), FRI(5, "๊ธ"), SAT(6, "ํ ");
+ private static final int NUMBER_OF_DAY_OF_WEEK = 7;
+
+ private final int code;
+ private final String dayOfWeek;
+
+ DayOfWeek(int code, String dayOfWeek ) {
+ this.code = code;
+ this.dayOfWeek = dayOfWeek;
+ }
+
+ public static boolean checkWeekend(DayOfWeek dayOfWeek) {
+ return dayOfWeek.equals(SUN) || dayOfWeek.equals(SAT);
+ }
+
+ public DayOfWeek getNextDayOfWeek() {
+ int nextDayOfWeekCode = (this.code + 1) % NUMBER_OF_DAY_OF_WEEK;
+ return Arrays.stream(values()).filter(dayOfWeek -> dayOfWeek.code == nextDayOfWeekCode)
+ .findAny()
+ .orElseThrow(IllegalArgumentException::new);
+ }
+
+ public static DayOfWeek getDayOfWeek(String dayOfWeek) {
+ return Arrays.stream(values())
+ .filter(day -> Objects.equals(day.dayOfWeek, dayOfWeek))
+ .findAny()
+ .orElseThrow(() -> new MyIllegalArgumentException(ErrorMessage.NOT_DAY_OF_WEEK));
+ }
+
+ @Override
+ public String toString() {
+ return dayOfWeek;
+ }
+} | Java | `code`๋ฅผ ๊ธฐ์ค์ผ๋ก ์ ๋ ฌ๋ ๋ฐฐ์ด, ๋๋ ๋ฆฌ์คํธ๋ฅผ ๋ฏธ๋ฆฌ ์บ์ฑํด ๋๋ค๋ฉด ๋ฐ๋ณต์ ์ธ `getNextDayOfWeek()` ํธ์ถ ์ํฉ์์ ๋งค๋ฒ `Stream` ๊ฐ์ฒด๋ฅผ ์์ฑํ์ง ์์๋ ๋๋ฉฐ `code`๋ฅผ ์ฌ์ฉํด ์ธ๋ฑ์ค๋ก ์ ๊ทผ๋ง ํ๋ฉด ๋๊ธฐ์ ์ฑ๋ฅ์ด ํจ์ฌ ์ข์์ง ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,32 @@
+package oncall.domain.employee;
+
+import java.util.Objects;
+import oncall.util.exception.ErrorMessage;
+import oncall.util.exception.MyIllegalArgumentException;
+
+public class Employee {
+ private final String name;
+
+ public Employee(String name) {
+ validateEmployeeName(name);
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ private void validateEmployeeName(String name) {
+ if (name.length() > 5) {
+ throw new MyIllegalArgumentException(ErrorMessage.TOO_LONG_EMPLOYEE_NAME);
+ }
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj instanceof Employee compare) {
+ return Objects.equals(this.name, compare.name);
+ }
+ return false;
+ }
+} | Java | ์์ ์ถ์ถ์ด ๊ฐ๋ฅํ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,17 @@
+package oncall.domain.employee;
+
+import java.util.List;
+
+public class EmployeeGenerator {
+ public static List<WeekWorkEmployee> generateWeekWorkEmployees(List<String> input) {
+ return input.stream()
+ .map(WeekWorkEmployee::new)
+ .toList();
+ }
+
+ public static List<WeekendWorkEmployee> generateWeekendWorkEmployees(List<String> input) {
+ return input.stream()
+ .map(WeekendWorkEmployee::new)
+ .toList();
+ }
+} | Java | ์ดํ๋ฆฌ์ผ์ด์
์์ ๋ ๊ฐ์ ์๋ก ๋ค๋ฅธ ํด๋์ค๋ก ๊ตฌ๋ถ๋๋ `WeekWorkEmployee`์ `WeekendWorkEmployee`๊ฐ ๊ธฐ๋ฅ์ ์ธ ์ฐจ์ด๊ฐ ์์ด ๋ณด์ด๋๋ฐ์.
๋์ผํ `Employee`๋ฅผ ๋ณ์ ๋ช
์ผ๋ก ๊ตฌ๋ถํด ์ฃผ๋ ๋์ ๋ณ๋์ ํด๋์ค๋ก ๊ตฌํํ์ ์ด์ ๊ฐ ์์๊น์? |
@@ -0,0 +1,54 @@
+package oncall.domain.employee;
+
+import java.util.List;
+import oncall.util.exception.ErrorMessage;
+import oncall.util.exception.MyIllegalArgumentException;
+
+public class EmployeeRepository {
+ private static final int MIN_EMPLOYEES_NUMBER = 5;
+ private static final int MAX_EMPLOYEES_NUMBER = 35;
+
+ private final List<WeekWorkEmployee> weekWorkEmployees;
+ private final List<WeekendWorkEmployee> weekendWorkEmployees;
+
+ public EmployeeRepository(List<WeekWorkEmployee> weekWorkEmployees,
+ List<WeekendWorkEmployee> weekendWorkEmployees) {
+ validateEmployees(weekWorkEmployees, weekendWorkEmployees);
+
+ this.weekWorkEmployees = weekWorkEmployees;
+ this.weekendWorkEmployees = weekendWorkEmployees;
+ }
+
+ private void validateEmployees(List<WeekWorkEmployee> weekWorkEmployees,
+ List<WeekendWorkEmployee> weekendWorkEmployees) {
+ if (weekWorkEmployees.size() < MIN_EMPLOYEES_NUMBER || weekWorkEmployees.size() > MAX_EMPLOYEES_NUMBER) {
+ throw new MyIllegalArgumentException(ErrorMessage.WRONG_EMPLOYEE_NUMBER);
+ }
+ validateSameWeekWorkEmployee(weekWorkEmployees);
+ validateSameWeekendWorkEmployee(weekendWorkEmployees);
+ }
+
+ private static void validateSameWeekendWorkEmployee(List<WeekendWorkEmployee> weekendWorkEmployees) {
+ if (weekendWorkEmployees.stream().distinct().count() != weekendWorkEmployees.size()) {
+ throw new MyIllegalArgumentException(ErrorMessage.NOT_SAME_EMPLOYEE_IN_ONE_WORK);
+ }
+ }
+
+ private static void validateSameWeekWorkEmployee(List<WeekWorkEmployee> weekWorkEmployees) {
+ if (weekWorkEmployees.stream().distinct().count() != weekWorkEmployees.size()) {
+ throw new MyIllegalArgumentException(ErrorMessage.NOT_SAME_EMPLOYEE_IN_ONE_WORK);
+ }
+ }
+
+ public WeekWorkEmployee getWeekWorkEmployee(int index) {
+ return weekWorkEmployees.get(index);
+ }
+
+ public WeekendWorkEmployee getWeekendWorkEmployees(int index) {
+ return weekendWorkEmployees.get(index);
+ }
+
+ public int getNumberOfEmployee() {
+ return weekWorkEmployees.size();
+ }
+} | Java | getter๋ฅผ ํตํด ์ธ๋ถ์ ์ปฌ๋ ์
์ ํฌ๊ธฐ๋ฅผ ๋
ธ์ถ์ํค๋ ๋์ , `getXXXEmployees(int index)` ๋ฉ์๋์์ % ๋๋จธ์ง ์ฐ์ฐ์ ํจ๊ป ์ํํด ์ฃผ๋ ๊ฒ์ ์ด๋จ๊น์?
์ธ๋ถ์์๋ ์ด ํด๋์ค๋ฅผ ์ด์ฉํ ๋ ๋ด๋ถ์์ ์ด๋ค ์์ผ๋ก ์์๋ฅผ ์ ์ง์ํจ ์ฑ ๋ฐ๋ณต์ ์ผ๋ก ๋ฉค๋ฒ๋ฅผ ํ์ํ๋์ง์ ๊ตฌํ์ ์ ๊ฒฝ์ฐ์ง ์๊ณ "`index` ๋ฒ์งธ์ ๊ทผ๋ฌด์"๋ฅผ ๊ตฌํ ์ ์์ ๊ฒ ๊ฐ์์!
์ด๋ ๊ฒ ๋๋ฉด ์ธ์ ๊ฐ ๋ด๋ถ ์๋ฃ๊ตฌ์กฐ๊ฐ `List<>`์์ ๋ฐฐ์ด๋ก ๋ณ๊ฒฝ๋๋ ๋ฑ์ ๋ณํ๊ฐ ์๋๋ผ๋ ์ธ๋ถ ์ฝ๋๊ฐ ๋ณ๊ฒฝ๋์ง ์์ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,11 @@
+package oncall.domain.date;
+
+public class DayGenerator {
+ public static Day generateFirstDay(Month month, DayOfWeek firstDayOfWeek) {
+ return new Day(month, new Date(1), firstDayOfWeek);
+ }
+
+ public static Day generateDay(Day day) {
+ return day.makeNextDay();
+ }
+} | Java | ๋ ์ง๋ฅผ ์์ฑํด ์ฃผ๋ ์ญํ ์ ์ํํ๋ ์ ์ ์ ํธ ํด๋์ค์ฒ๋ผ ๋ณด์ด๋๋ฐ์.
์ ๋ "๋ ์ง ๊ฐ์ฒด ์์ฑ" ์ญ์ ๋ ์ง ๊ฐ์ฒด ์ค์ค๋ก์ ์ฑ
์์ด๋ผ๊ณ ์๊ฐํด์.
๋๋ฌธ์ `generateFirstDay()` ๋ฉ์๋๋ ๋จ์ํ `Day.of(Month, DayOfWeek)`์ ํํ๋ฅผ ๊ฐ์ง๋ ์ ์ ํฉํ ๋ฆฌ ๋ฉ์๋๋ก๋ง ๊ตฌํํด๋ ๊ด์ฐฎ์ง ์์์๊น ์๊ฐํฉ๋๋ค.
์ด๋ ๊ฒ ๊ตฌํํด ์ค๋ค๋ฉด `DayGenerator` ํด๋์ค๋ฅผ `Day` ํด๋์ค์ ๋ณํฉํด ์ค ์ ์์ ๊ฒ ๊ฐ์์. |
@@ -0,0 +1,106 @@
+package chess.database.dao;
+
+import chess.dto.game.ChessGameLoadDto;
+import chess.dto.game.ChessGameSaveDto;
+
+import java.sql.*;
+import java.util.ArrayList;
+import java.util.List;
+
+public final class DbChessGameDao implements ChessDao {
+
+ private final String url;
+ private final String user;
+ private final String password;
+
+ public DbChessGameDao(final String url, final String user, final String password) {
+ this.url = url;
+ this.user = user;
+ this.password = password;
+ }
+
+ private Connection getConnection() {
+ try {
+ return DriverManager.getConnection(url, user, password);
+ } catch (SQLException e) {
+// throw new RuntimeException(e);
+ return null;
+ }
+ }
+
+ @Override
+ public void save(final ChessGameSaveDto dto) {
+ final String sql = "INSERT INTO chess_game(piece_type, piece_file, piece_rank, piece_team, last_turn) VALUES (?, ?, ?, ?, ?)";
+ try (final Connection connection = getConnection();
+ final PreparedStatement preparedStatement = connection.prepareStatement(sql);
+ ) {
+ for (int i = 0; i < dto.getSize(); i++) {
+ preparedStatement.setString(1, dto.getPieceTypes().get(i));
+ preparedStatement.setString(2, dto.getPieceFiles().get(i));
+ preparedStatement.setString(3, dto.getPieceRanks().get(i));
+ preparedStatement.setString(4, dto.getPieceTeams().get(i));
+ preparedStatement.setString(5, dto.getLastTurns().get(i));
+ preparedStatement.executeUpdate();
+ }
+ } catch (SQLException e) {
+ throw new RuntimeException(e);
+ } catch (NullPointerException ignored) {
+ }
+ }
+
+ @Override
+ public ChessGameLoadDto loadGame() {
+ final String sql = "SELECT piece_type, piece_file, piece_rank, piece_team, last_turn FROM chess_game";
+ try (final Connection connection = getConnection();
+ final PreparedStatement preparedStatement = connection.prepareStatement(sql);
+ final ResultSet resultSet = preparedStatement.executeQuery();
+ ) {
+ final List<String> pieceType = new ArrayList<>();
+ final List<String> pieceFile = new ArrayList<>();
+ final List<String> pieceRanks = new ArrayList<>();
+ final List<String> pieceTeams = new ArrayList<>();
+ String lastTurn = "";
+
+ while (resultSet.next()) {
+ pieceType.add(resultSet.getString("piece_type"));
+ pieceFile.add(resultSet.getString("piece_file"));
+ pieceRanks.add(resultSet.getString("piece_rank"));
+ pieceTeams.add(resultSet.getString("piece_team"));
+ lastTurn = resultSet.getString("last_turn");
+ }
+ return new ChessGameLoadDto(pieceType, pieceFile, pieceRanks, pieceTeams, lastTurn);
+ } catch (SQLException e) {
+ throw new RuntimeException(e);
+ } catch (NullPointerException e) {
+ return null;
+ }
+ }
+
+ @Override
+ public boolean hasHistory() {
+ final String sql = "SELECT piece_type, piece_file, piece_rank, piece_team, last_turn FROM chess_game";
+ try (final Connection connection = getConnection();
+ final PreparedStatement preparedStatement = connection.prepareStatement(sql);
+ final ResultSet resultSet = preparedStatement.executeQuery();
+ ) {
+ return resultSet.next();
+ } catch (SQLException e) {
+ throw new RuntimeException(e);
+ } catch (NullPointerException e) {
+ return false;
+ }
+ }
+
+ @Override
+ public void delete() {
+ final String sql = "DELETE FROM chess_game";
+ try (final Connection connection = getConnection();
+ final PreparedStatement preparedStatement = connection.prepareStatement(sql)
+ ) {
+ preparedStatement.executeUpdate();
+ } catch (SQLException e) {
+ throw new RuntimeException(e);
+ } catch (NullPointerException ignored) {
+ }
+ }
+} | Java | Jdbc Connection ๊ด๋ฆฌ๋ฅผ Dao์์ ํด์ฃผ๊ณ ๊ณ์๋ค์! ๊ทธ๋ฐ๋ฐ ๊ด๋ฆฌํด์ผ ํ ํ
์ด๋ธ์ด ๋์ด๋์ ์ฌ๋ฌ Dao ๊ฐ์ฒด๊ฐ ์๊ฒจ๋๊ฒ ๋๋ฉด ์ค๋ณต๋๋ ์ฝ๋์ธ ์ธ์คํด์ค ๋ณ์๋ค์ด ๋ฐ์ํ๊ฒ ๋ ๊ฒ ๊ฐ์์.
์ ๋ ์ฒด์ค๋ฏธ์
์ ์งํํ๋ฉฐ ๋ฆฌ๋ทฐ์ด๋ถ๊ป ๋ฆฌ๋ทฐ๋ฐ์ ์ฌํญ์ธ๋ฐ DB Connection๊ณผ ๊ฐ์ resource ๊ด๋ฆฌ ์ฝ๋๋ฅผ Util ํด๋์ค ๋ฑ์ผ๋ก ๊ตฌ๋ถํด์ ๊ด๋ฆฌํด๋ณด์๋ ๊ฑด ์ด๋จ์ง ์ ์๋๋ ค๋ด
๋๋ค! |
@@ -0,0 +1,106 @@
+package chess.database.dao;
+
+import chess.dto.game.ChessGameLoadDto;
+import chess.dto.game.ChessGameSaveDto;
+
+import java.sql.*;
+import java.util.ArrayList;
+import java.util.List;
+
+public final class DbChessGameDao implements ChessDao {
+
+ private final String url;
+ private final String user;
+ private final String password;
+
+ public DbChessGameDao(final String url, final String user, final String password) {
+ this.url = url;
+ this.user = user;
+ this.password = password;
+ }
+
+ private Connection getConnection() {
+ try {
+ return DriverManager.getConnection(url, user, password);
+ } catch (SQLException e) {
+// throw new RuntimeException(e);
+ return null;
+ }
+ }
+
+ @Override
+ public void save(final ChessGameSaveDto dto) {
+ final String sql = "INSERT INTO chess_game(piece_type, piece_file, piece_rank, piece_team, last_turn) VALUES (?, ?, ?, ?, ?)";
+ try (final Connection connection = getConnection();
+ final PreparedStatement preparedStatement = connection.prepareStatement(sql);
+ ) {
+ for (int i = 0; i < dto.getSize(); i++) {
+ preparedStatement.setString(1, dto.getPieceTypes().get(i));
+ preparedStatement.setString(2, dto.getPieceFiles().get(i));
+ preparedStatement.setString(3, dto.getPieceRanks().get(i));
+ preparedStatement.setString(4, dto.getPieceTeams().get(i));
+ preparedStatement.setString(5, dto.getLastTurns().get(i));
+ preparedStatement.executeUpdate();
+ }
+ } catch (SQLException e) {
+ throw new RuntimeException(e);
+ } catch (NullPointerException ignored) {
+ }
+ }
+
+ @Override
+ public ChessGameLoadDto loadGame() {
+ final String sql = "SELECT piece_type, piece_file, piece_rank, piece_team, last_turn FROM chess_game";
+ try (final Connection connection = getConnection();
+ final PreparedStatement preparedStatement = connection.prepareStatement(sql);
+ final ResultSet resultSet = preparedStatement.executeQuery();
+ ) {
+ final List<String> pieceType = new ArrayList<>();
+ final List<String> pieceFile = new ArrayList<>();
+ final List<String> pieceRanks = new ArrayList<>();
+ final List<String> pieceTeams = new ArrayList<>();
+ String lastTurn = "";
+
+ while (resultSet.next()) {
+ pieceType.add(resultSet.getString("piece_type"));
+ pieceFile.add(resultSet.getString("piece_file"));
+ pieceRanks.add(resultSet.getString("piece_rank"));
+ pieceTeams.add(resultSet.getString("piece_team"));
+ lastTurn = resultSet.getString("last_turn");
+ }
+ return new ChessGameLoadDto(pieceType, pieceFile, pieceRanks, pieceTeams, lastTurn);
+ } catch (SQLException e) {
+ throw new RuntimeException(e);
+ } catch (NullPointerException e) {
+ return null;
+ }
+ }
+
+ @Override
+ public boolean hasHistory() {
+ final String sql = "SELECT piece_type, piece_file, piece_rank, piece_team, last_turn FROM chess_game";
+ try (final Connection connection = getConnection();
+ final PreparedStatement preparedStatement = connection.prepareStatement(sql);
+ final ResultSet resultSet = preparedStatement.executeQuery();
+ ) {
+ return resultSet.next();
+ } catch (SQLException e) {
+ throw new RuntimeException(e);
+ } catch (NullPointerException e) {
+ return false;
+ }
+ }
+
+ @Override
+ public void delete() {
+ final String sql = "DELETE FROM chess_game";
+ try (final Connection connection = getConnection();
+ final PreparedStatement preparedStatement = connection.prepareStatement(sql)
+ ) {
+ preparedStatement.executeUpdate();
+ } catch (SQLException e) {
+ throw new RuntimeException(e);
+ } catch (NullPointerException ignored) {
+ }
+ }
+} | Java | Dao์์ NullPointerException์ ๋ฌด์ํ๋ ๊ฒ์ ๋ฆฌ๋ทฐ์ด๋ฅผ ์ํ ๋ฐฐ๋ ค์ผ๊น์? ใ
ใ
๊ทธ๊ฒ ์๋๋ผ๋ฉด ์ด๋ค ์๋๋ก ์์ธ๋ฅผ ๋ฌด์์ฒ๋ฆฌํด์ฃผ์ ๊ฑด์ง ๊ถ๊ธํฉ๋๋ค~ |
@@ -1,7 +1,97 @@
-# java-chess
+## ์ ์ฒด ์๋๋ฆฌ์ค
-์ฒด์ค ๋ฏธ์
์ ์ฅ์
+1. start๋ฅผ ์
๋ ฅ ๋ฐ์ผ๋ฉด ๊ฒ์์ ์์ํ๋ค.
+ - [์์ธ] ๊ฒ์์ด ์์ํ์ง ์์๋๋ฐ move๋ฅผ ์
๋ ฅํ๋ฉด ์์ธ๊ฐ ๋ฐ์ํ๋ค.
+2. move sourcePosition targetPosition์ ์
๋ ฅ ๋ฐ์ ๊ธฐ๋ฌผ์ ์์ง์ธ๋ค.
+ - [์์ธ] ๊ฒ์ ์งํ ์ค์ start๋ฅผ ์
๋ ฅํ๋ฉด ์์ธ๊ฐ ๋ฐ์ํ๋ค.
+3. status๋ฅผ ์
๋ ฅ ๋ฐ์ ๊ฐ ์ง์์ score๋ฅผ ์ถ๋ ฅํ๊ณ ์นํจ๋ฅผ ์ถ๋ ฅํ๋ค.
+4. ํน์ด ๋จผ์ ์กํ๋ ์ง์์ด ํจํ๊ณ , ์ฆ์ ๊ฒ์์ ์ข
๋ฃํ๋ค.
+5. end๋ฅผ ์
๋ ฅ ๋ฐ์ ๊ฒ์์ ์ข
๋ฃํ๋ค.
-## ์ฐ์ํํ
ํฌ์ฝ์ค ์ฝ๋๋ฆฌ๋ทฐ
+### ์ฒด์ค ๊ฒ์(ChessGame)
-- [์จ๋ผ์ธ ์ฝ๋ ๋ฆฌ๋ทฐ ๊ณผ์ ](https://github.com/woowacourse/woowacourse-docs/blob/master/maincourse/README.md)
+- [x] ์ฒด์ค ๊ฒ์์
+ - [x] ์์น์ ๋ฐ๋ฅธ ๊ธฐ๋ฌผ ์ ๋ณด๋ฅผ ๊ฐ์ง๊ณ ์๋ค.
+ - [x] ํ์ฌ ์ด๋ ์ง์์ ํด์ธ์ง ๊ฐ์ง๊ณ ์๋ค.
+ - [x] ๊ฐ ์ง์์ ์ ์๋ฅผ ๊ณ์ฐํ ์ ์๋ค.
+ - [x] ์์ด ์ฃฝ์ผ๋ฉด ๊ฒ์์ด ๋๋๋ค.
+ - [x] ์ด๋ค ์ง์์ด ์ด๊ฒผ๋์ง ์ถ๋ ฅํ๊ณ ๊ฒ์์ ๋๋ธ๋ค.
+
+## ๊ธฐ๋ฌผ(Piece)
+
+- [x] ๊ธฐ๋ฌผ์
+ - [x] ๊ธฐ๋ฌผ์ ํ์
(PieceType)๊ณผ ์ง์(Team), ์ด๋ ์ ๋ต(MovingStrategies)์ ๊ฐ์ง๊ณ ์๋ค.
+ - [x] ๊ฐ๊ฐ์ ๊ณ ์ ํ์
์ผ๋ก ๊ตฌ๋ถ๋๋ค.
+ - [x] ์์ง์ด๋ คํ ๊ธฐ๋ฌผ์ด ์ด๊ธฐ ํฐ์ด๋ผ๋ฉด ์ผ๋ฐ ํฐ์ผ๋ก ๋ฐ๊ฟ์ค๋ค.
+ - [์์ธ] ํ๋ง๋ฒ์ ์์ง์ด์ง ๋ชปํ๋ ๊ณณ์ผ๋ก ์ด๋ํ๋ ค๊ณ ํ๋ฉด ์์ธ๊ฐ ๋ฐ์ํ๋ค.
+ - [์์ธ] ์ด๋ํ๊ณ ์ ํ๋ ์ง์ ์ ์๊ตฐ ๊ธฐ๋ฌผ์ด ์์ผ๋ฉด ์์ธ๊ฐ ๋ฐ์ํ๋ค.
+ - [์์ธ] ๋น ๊ธฐ๋ฌผ(EMPTY)๋ฅผ ์์ง์ด๋ ค ํ๋ฉด ์์ธ๊ฐ ๋ฐ์ํ๋ค.
+
+### ์ฌ๋ผ์ด๋ฉ ๊ฐ๋ฅํ ๊ธฐ๋ฌผ (SlidingPiece)
+
+- [x] ๋ฃฉ(Rook)
+ - [x] ์, ํ, ์ข, ์ฐ๋ก ์์ง์ผ ์ ์๋ค.
+- [x] ๋น์(Bishop)
+ - [x] ๋๊ฐ์ ์ผ๋ก ์์ง์ผ ์ ์๋ค.
+- [x] ํธ(Queen)
+ - [x] ์, ํ, ์ข, ์ฐ, ๋๊ฐ์ ์ผ๋ก ์์ง์ผ ์ ์๋ค.
+
+### ์ฌ๋ผ์ด๋ฉ ๋ถ๊ฐํ ๊ธฐ๋ฌผ (NonSlidingPiece)
+
+- [x] ๋์ดํธ(Knight)
+ - [x] ๋์ดํธ ๊ณ ์ ์ ์ฌ๋ ๋ฐฉํฅ์ผ๋ก ์์ง์ผ ์ ์๋ค.
+- [x] ํน(King)
+ - [x] ์, ํ, ์ข, ์ฐ๋ก ์์ง์ผ ์ ์๋ค.
+
+### Empty
+
+- [x] ๋น ๊ธฐ๋ฌผ์ ๋ปํ๊ณ , ์์ง์ผ ์ ์๋ค.
+
+### ํฐ(Pawn)
+
+- [x] InitialWhitePawn
+ - [x] ์ด๋ ์ ๋ต : ์๋ก ๋ ์นธ, ์๋ก ํ ์นธ ์์ง์ผ ์ ์๋ค.
+ - [x] ๊ณต๊ฒฉ ์ ๋ต : ์ผ์ชฝ ์, ์ค๋ฅธ์ชฝ ์๋ก ํ ์นธ ์์ง์ผ ์ ์๋ค.
+- [x] InitialBlackPawn
+ - [x] ์ด๋ ์ ๋ต : ์๋๋ก ๋ ์นธ, ์๋๋ก ํ ์นธ ์์ง์ผ ์ ์๋ค.
+ - [x] ๊ณต๊ฒฉ ์ ๋ต : ์ผ์ชฝ ์๋, ์ค๋ฅธ์ชฝ ์๋๋ก ํ ์นธ ์์ง์ผ ์ ์๋ค.
+- [x] WhitePawn
+ - [x] ์ด๋ ์ ๋ต : ์๋ก ํ ์นธ ์์ง์ผ ์ ์๋ค.
+ - [x] ๊ณต๊ฒฉ ์ ๋ต : ์ผ์ชฝ ์, ์ค๋ฅธ์ชฝ ์๋ก ํ ์นธ ์์ง์ผ ์ ์๋ค.
+- [x] BlackPawn
+ - [x] ์ด๋ ์ ๋ต : ์๋๋ก ํ ์นธ ์์ง์ผ ์ ์๋ค.
+ - [x] ๊ณต๊ฒฉ ์ ๋ต : ์ผ์ชฝ ์๋, ์ค๋ฅธ์ชฝ ์๋๋ก ํ ์นธ ์์ง์ผ ์ ์๋ค.
+
+### Turn
+
+- [x] ์ด๊ธฐ ํด์ WHITE๋ถํฐ ์์๋๋ค.
+- [x] WHITE์์ BLACK์ผ๋ก, BLACK์์ WHITE๋ก ํด์ ์ฐจ๋ก๋ก ๋ฐ๊พผ๋ค.
+- [์์ธ] ์์ ์ ํด์ด ์๋์๋ ์์ ์ ๋ง์ ์์ง์ด๋ ค๊ณ ํ๋ฉด ์์ธ๊ฐ ๋ฐ์ํ๋ค.
+
+### Score
+
+- [x] ํ์ฌ๊น์ง ๋จ์ ์๋ ๋ง์ ๋ฐ๋ผ ์ ์๋ฅผ ๊ณ์ฐํ ์ ์์ด์ผ ํ๋ค.
+- [x] ๊ฐ ๋ง์ ์ ์๋ queen์ 9์ , rook์ 5์ , bishop์ 3์ , knight๋ 2.5์ ์ด๋ค.
+- [x] pawn์ ๊ธฐ๋ณธ ์ ์๋ 1์ ์ด๋ค.
+ - [x] ํ์ง๋ง ๊ฐ์ ์ธ๋ก์ค์ ๊ฐ์ ์์ ํฐ์ด ์๋ ๊ฒฝ์ฐ 1์ ์ด ์๋ 0.5์ ์ ์ค๋ค.
+
+### DB ์๋๋ฆฌ์ค
+- [x] ๊ฒ์ ์์์
+ - [x] ์งํ์ค์ด๋ ๊ฒ์์ด ์๋ค๋ฉด ํด๋น ๊ฒ์์ ๋ก๋ํด์ ์งํํ๋ค.
+ - [x] ์งํ์ค์ด๋ ๊ฒ์์ด ์๋ค๋ฉด ์๋ก์ด ๊ฒ์์ ์์ํ๋ค.
+- [x] ๊ฒ์ ์งํ์ค
+ - [x] status๋ฅผ ์
๋ ฅํ๊ฑฐ๋, ์๋๋ฐฉ์ ํน์ ์ก์ผ๋ฉด ๊ฒ์์ ์ข
๋ฃํ๋ค. ๊ทธ๋ฆฌ๊ณ DB๋ฅผ ๋ชจ๋ ์ง์ด๋ค.
+ - [x] ๊ทธ๋ ์ง ์๊ณ , end๋ฅผ ์
๋ ฅํ๋ค๋ฉด ๋ง์ง๋ง ๊ฒ์ ์ํ๋ฅผ DB์ ์ ์ฅํ๋ค.
+
+### DB DDL
+``` sql
+create table chess_game
+(
+ piece_id int auto_increment primary key,
+ piece_file varchar(20) not null,
+ piece_rank varchar(20) not null,
+ piece_type varchar(20) not null,
+ piece_team varchar(20) not null,
+ last_turn varchar(20) not null
+);
+``` | Unknown | DDL ๋ช
์ ์ข์์~
์ ๋ ๋ฆฌ๋ทฐ์ด ๋ถ๊ป ๋ฆฌ๋ทฐ๋ฐ์ ์ฌํญ ์ค ํ๋๋ฅผ ๋ง์๋๋ฆฌ๋ฉด ํ์ฌ chess_game ํ
์ด๋ธ์์ ๊ด๋ฆฌ๋๋ ๋ฐ์ดํฐ๋ค์ ๋ณด๋ฉด ํ
์ด๋ธ ๋ช
์ด chess_game์ด ์๋๋ผ piece๊ฐ ๋์ด์ผ ํ์ง ์์๊น ํ๋ ๊ฒ์
๋๋ค. |
@@ -43,7 +43,7 @@ set JAVA_EXE=java.exe
if "%ERRORLEVEL%" == "0" goto execute
echo.
-echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo ERROR: JAVA_HOME is not set and no 'java' gameCommand could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
@@ -65,7 +65,7 @@ echo location of your Java installation.
goto fail
:execute
-@rem Setup the command line
+@rem Setup the gameCommand line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
| Unknown | ์...? ์ด ํ์ผ์ command ๋ผ๋ ๋จ์ด๋ฅผ ์ ์ฒด ์นํํ๋ค๊ฐ ๊ฐ์ด ์์ ๋์ด ๋ฒ๋ฆฐ ๊ฒ ๊ฐ์ ๋ณด์ฌ์~ |
@@ -0,0 +1,12 @@
+package chess.database;
+
+public final class DbInfo {
+
+ public static String service_url = "jdbc:mysql://127.0.0.1:13306/chess?useSSL=false&serverTimezone=UTC";
+ public static String service_user = "root";
+ public static String service_password = "root";
+
+ public static String test_url = "jdbc:mysql://127.0.0.1:13306/chess_test?useSSL=false&serverTimezone=UTC";
+ public static String test_user = "root";
+ public static String test_password = "root";
+} | Java | ์ด ํด๋์ค์์ connection์ ๋ง๋ค์ด์ ๋์ ธ์ฃผ๋ ๊ฑด ์ด๋จ๊น์? |
@@ -0,0 +1,21 @@
+package chess;
+
+import chess.controller.ChessController;
+import chess.view.IOViewResolver;
+import chess.view.InputView;
+import chess.view.OutputView;
+
+import java.util.Scanner;
+
+public final class MainApp {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ final ChessController chessController = new ChessController(
+ new IOViewResolver(new InputView(scanner), new OutputView()));
+ chessController.process();
+ } catch (Exception exception) {
+ exception.printStackTrace();
+ }
+ }
+} | Java | ์์๊ด๋ฆฌ ์ฟ ์ธ ๐ |
@@ -0,0 +1,70 @@
+package chess.controller;
+
+import chess.domain.game.File;
+import chess.domain.game.Position;
+import chess.domain.game.Rank;
+
+import java.util.Arrays;
+import java.util.List;
+
+public enum GameCommand {
+ INIT,
+ START,
+ FIRST_MOVE,
+ MOVE,
+ STATUS,
+ END;
+
+ public static final String INVALID_COMMAND_MESSAGE = "์๋ชป๋ ์ปค๋งจ๋๋ฅผ ์
๋ ฅํ์์ต๋๋ค.";
+ public static final int SOURCE_INDEX = 1;
+ public static final int TARGET_INDEX = 2;
+ public static final int SOURCE_AND_TARGET_LENGTH = 2;
+ public static final int INPUT_SIZE = 3;
+ private static final int DEFAULT_COMMAND_INDEX = 0;
+
+ public static GameCommand from(final List<String> input) {
+ GameCommand result = Arrays.stream(values())
+ .filter(value -> value.name().equalsIgnoreCase(input.get(DEFAULT_COMMAND_INDEX)))
+ .findFirst()
+ .orElseThrow(() -> new IllegalArgumentException(INVALID_COMMAND_MESSAGE));
+ if (result == MOVE) {
+ validateMoveCommand(input);
+ }
+ return result;
+ }
+
+ private static void validateMoveCommand(List<String> input) {
+ if (input.size() != INPUT_SIZE) {
+ throw new IllegalArgumentException(INVALID_COMMAND_MESSAGE);
+ }
+ if (input.get(SOURCE_INDEX).length() != SOURCE_AND_TARGET_LENGTH ||
+ input.get(TARGET_INDEX).length() != SOURCE_AND_TARGET_LENGTH) {
+ throw new IllegalArgumentException(INVALID_COMMAND_MESSAGE);
+ }
+ }
+
+ public static Position getPosition(final List<String> input, final int index) {
+ final String targetPosition = input.get(index);
+ final int fileOrder = getFileOrder(targetPosition);
+ final int rankOrder = getRankOrder(targetPosition);
+ return Position.of(File.of(fileOrder), Rank.of(rankOrder));
+ }
+
+ private static int getFileOrder(final String command) {
+ final int charToIntDifference = 96;
+ return command.charAt(0) - charToIntDifference;
+ }
+
+ private static int getRankOrder(final String command) {
+ final char charToIntDifference = '0';
+ return command.charAt(1) - charToIntDifference;
+ }
+
+ public boolean isEnd() {
+ return this == END;
+ }
+
+ public boolean isFirstMove() {
+ return this == FIRST_MOVE;
+ }
+} | Java | ์ฒ์ GameCommand ํด๋์ค๋ฅผ ๋ณด๋๋ฐ Position์ ๊ตฌํ๋ ์ฝ๋๋ค์ด ์ ์ฌ๊ธฐ์ ๋ค์ด๊ฐ ์์๊น๊ฐ ์ข ๊ถ๊ธํ์์ต๋๋ค. ์๋ง ํํฌ๊ฐ input์ผ๋ก ๋ค์ด์จ command๋ฅผ ๊ฐ์ง๊ณ position์ ๊ตฌํ๋ ๊ธฐ๋ฅ์ด๋ผ๊ณ ์๊ฐํด์ GameCommand๋ก ๋ถ๋ฆฌํ์ ๊ฒ ๊ฐ์์.
์ ๋ผ๋ฉด ํด๋น ๊ธฐ๋ฅ๋ค์ file, rank, Position Enum์์ ์ฑ
์์ ์ง๋๋ก ํ์ ๊ฒ ๊ฐ์๋ฐ ํํฌ ์๊ฒฌ์ ์ด๋ ์ ์ง ๊ถ๊ธํด์~ |
@@ -0,0 +1,113 @@
+package chess.domain.game;
+
+import chess.domain.piece.Empty;
+import chess.domain.piece.Piece;
+import chess.domain.piece.PieceType;
+import chess.domain.piece.Team;
+import chess.domain.piece.pawn.BlackPawn;
+import chess.domain.piece.pawn.WhitePawn;
+import chess.dto.mapper.ParseToDto;
+import chess.dto.outputView.PrintBoardDto;
+import chess.dto.outputView.PrintTotalScoreDto;
+import chess.dto.outputView.PrintWinnerDto;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public final class ChessGame {
+
+ private static final int BOARD_LENGTH = 8;
+ public static final double TOTAL_BOARD_SIZE = Math.pow(BOARD_LENGTH, 2);
+
+ private final Map<Position, Piece> board;
+ private Turn turn;
+
+ private ChessGame(final Map<Position, Piece> board, final Turn turn) {
+ this.board = new HashMap<>(board);
+ this.turn = turn;
+ }
+
+ public static ChessGame of(final Map<Position, Piece> board) {
+ return of(board, Turn.create());
+ }
+
+ public static ChessGame of(final Map<Position, Piece> board, final Turn turn) {
+ if (board.size() != TOTAL_BOARD_SIZE) {
+ throw new IllegalArgumentException(
+ String.format("์ฒด์คํ์ ์ฌ์ด์ฆ๋ %d x %d ์ฌ์ผํฉ๋๋ค.", BOARD_LENGTH, BOARD_LENGTH));
+ }
+ return new ChessGame(board, turn);
+ }
+
+ public Piece move(final Position source, final Position target) {
+ final Piece sourcePiece = board.get(source);
+ final Piece targetPiece = board.get(target);
+ validateEmptyPiece(sourcePiece);
+ validateTurn(sourcePiece);
+ validatePath(sourcePiece.findPath(source, target, targetPiece.getTeam()));
+
+ switchPiece(source, target, sourcePiece);
+ turn = turn.next();
+ return targetPiece;
+ }
+
+ private void validateEmptyPiece(final Piece sourcePiece) {
+ if (sourcePiece.isEmpty()) {
+ throw new IllegalArgumentException("๊ธฐ๋ฌผ์ด ์๋ ๊ณณ์ ์ ํํ์
จ์ต๋๋ค.");
+ }
+ }
+
+ private void validateTurn(final Piece piece) {
+ if (!turn.isValidTurn(piece)) {
+ throw new IllegalStateException("ํด์ด ์ฌ๋ฐ๋ฅด์ง ์์ต๋๋ค. ํ์ฌ ํด : " + turn.getTeam());
+ }
+ }
+
+ private void validatePath(final List<Position> path) {
+ final boolean result = path.stream()
+ .allMatch(position -> board.get(position).isEmpty());
+ if (!result) {
+ throw new IllegalArgumentException("์ด๋ํ๋ ค๋ ๊ฒฝ๋ก์ ๊ธฐ๋ฌผ์ด ์กด์ฌํฉ๋๋ค.");
+ }
+ }
+
+ private void switchPiece(final Position source, final Position target, final Piece sourcePiece) {
+ board.put(target, checkInitialPawn(sourcePiece));
+ board.put(source, Empty.instance());
+ }
+
+ private Piece checkInitialPawn(final Piece piece) {
+ if (piece.isSamePieceTypeAs(PieceType.INITIAL_WHITE_PAWN)) {
+ return WhitePawn.instance();
+ }
+ if (piece.isSamePieceTypeAs(PieceType.INITIAL_BLACK_PAWN)) {
+ return BlackPawn.instance();
+ }
+ return piece;
+ }
+
+ public PrintWinnerDto getWinnerTeam(final Piece deadPiece) {
+ final Team deadPieceTeam = deadPiece.getTeam();
+ final Team opponentTeam = deadPieceTeam.getOpponentTeam();
+ return new PrintWinnerDto(opponentTeam.name());
+ }
+
+ public PrintTotalScoreDto calculateScore() {
+ return new PrintTotalScoreDto(
+ ScoreCalculator.calculateScoreByTeam(Team.WHITE, board),
+ ScoreCalculator.calculateScoreByTeam(Team.BLACK, board));
+ }
+
+ public PrintBoardDto printBoard() {
+ return ParseToDto.parseToPrintBoardDto(getBoard());
+ }
+
+ public Map<Position, Piece> getBoard() {
+ return Map.copyOf(board);
+ }
+
+ public Team getTurn() {
+ return turn.getTeam();
+ }
+} | Java | pawn์ ๋ํ ์ฒ๋ฆฌ ๋ก์ง์ ํฌํจํด์ ๊ธฐ๋ฌผ ์ด๋ ๋ก์ง์ด ์ ๋ง ๊น๋ํ๋ค์! ๐ฏ |
@@ -0,0 +1,31 @@
+//
+// SceneDelegate.swift
+// DrawingApp
+//
+// Created by ๊นํ๋ฆผ on 2023/03/28.
+//
+
+import UIKit
+
+class SceneDelegate: UIResponder, UIWindowSceneDelegate {
+
+ var window: UIWindow?
+
+
+ func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
+ guard let _ = (scene as? UIWindowScene) else { return }
+ }
+
+ func sceneDidDisconnect(_ scene: UIScene) { }
+
+ func sceneDidBecomeActive(_ scene: UIScene) { }
+
+ func sceneWillResignActive(_ scene: UIScene) { }
+
+ func sceneWillEnterForeground(_ scene: UIScene) { }
+
+ func sceneDidEnterBackground(_ scene: UIScene) { }
+
+
+}
+ | Swift | ํ์์๊ฑฐ๋ ์ฌ์ฉํ์ง ์๋ ๋ฉ์๋๋ ํ๋จํ์ฌ ์ญ์ ํ๋๊ฒ๋ ์ข์ ๊ฑฐ ๊ฐ์ต๋๋ค |
@@ -0,0 +1,91 @@
+//
+// ViewController.swift
+// DrawingApp
+//
+// Created by ๊นํ๋ฆผ on 2023/03/28.
+//
+
+import UIKit
+import OSLog
+
+class ViewController: UIViewController {
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ let rect1 = RectangleFactory.createRectangle()
+ os_log("\(rect1.description)")
+ }
+}
+
+protocol RectangleComponent {
+ var id:String { get }
+ var size:RectangleSize { get }
+ var position:RectanglePosition { get }
+ var backGroundColor:(red:Int, green:Int, blue:Int) { get }
+ var alpha:Int { get }
+}
+
+class RectangleSize {
+ private var width:Double = 150
+ private var height:Double = 120
+
+ func getWidth() -> Double {
+ return self.width
+ }
+ func getHeight() -> Double {
+ return self.height
+ }
+}
+class RectanglePosition {
+ private var X:Double
+ private var Y:Double
+
+ init(X: Double, Y: Double) {
+ self.X = X
+ self.Y = Y
+ }
+ func randomPosition() -> RectanglePosition {
+ let x = Double.random(in: 0...UIScreen.main.bounds.width)
+ let y = Double.random(in: 0...UIScreen.main.bounds.height)
+ return RectanglePosition(X: x, Y: y)
+ }
+ func getPositionX() -> Double {
+ return self.X
+ }
+ func getPositionY() -> Double {
+ return self.Y
+ }
+}
+
+
+class IdRandomizer {
+ func randomString() -> String {
+ let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
+ var randomString = ""
+ for _ in 0..<9 {
+ let randomIndex = Int.random(in: 0..<letters.count)
+ let letter = letters[letters.index(letters.startIndex, offsetBy: randomIndex)]
+ randomString.append(letter)
+ }
+ return "\(randomString.prefix(3))-\(randomString.prefix(6).suffix(3))-\(randomString.suffix(3))"
+ }
+}
+
+class RectangleFactory {
+ static func createRectangle() -> Rectangle {
+ let id = IdRandomizer().randomString()
+ let size = RectangleSize()
+ let position = RectanglePosition(X: 0, Y: 0).randomPosition()
+ let backGroundColor = (red: Int.random(in: 0...255), green: Int.random(in: 0...255), blue: Int.random(in: 0...255))
+ let alpha = Int.random(in: 1...10)
+
+ return Rectangle(
+ id: id,
+ size: size,
+ position: position,
+ backGroundColor: backGroundColor,
+ alpha: alpha
+ )
+ }
+} | Swift | ์ขํ ์์ ํ ๊ฐ๋ฅ์ฑ์ด ์๋ค๋ฉด ์์๋ก ์ ์ธํ๋ ๊ฒ๋ ์ข์๋ณด์
๋๋ค |
@@ -0,0 +1,91 @@
+//
+// ViewController.swift
+// DrawingApp
+//
+// Created by ๊นํ๋ฆผ on 2023/03/28.
+//
+
+import UIKit
+import OSLog
+
+class ViewController: UIViewController {
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ let rect1 = RectangleFactory.createRectangle()
+ os_log("\(rect1.description)")
+ }
+}
+
+protocol RectangleComponent {
+ var id:String { get }
+ var size:RectangleSize { get }
+ var position:RectanglePosition { get }
+ var backGroundColor:(red:Int, green:Int, blue:Int) { get }
+ var alpha:Int { get }
+}
+
+class RectangleSize {
+ private var width:Double = 150
+ private var height:Double = 120
+
+ func getWidth() -> Double {
+ return self.width
+ }
+ func getHeight() -> Double {
+ return self.height
+ }
+}
+class RectanglePosition {
+ private var X:Double
+ private var Y:Double
+
+ init(X: Double, Y: Double) {
+ self.X = X
+ self.Y = Y
+ }
+ func randomPosition() -> RectanglePosition {
+ let x = Double.random(in: 0...UIScreen.main.bounds.width)
+ let y = Double.random(in: 0...UIScreen.main.bounds.height)
+ return RectanglePosition(X: x, Y: y)
+ }
+ func getPositionX() -> Double {
+ return self.X
+ }
+ func getPositionY() -> Double {
+ return self.Y
+ }
+}
+
+
+class IdRandomizer {
+ func randomString() -> String {
+ let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
+ var randomString = ""
+ for _ in 0..<9 {
+ let randomIndex = Int.random(in: 0..<letters.count)
+ let letter = letters[letters.index(letters.startIndex, offsetBy: randomIndex)]
+ randomString.append(letter)
+ }
+ return "\(randomString.prefix(3))-\(randomString.prefix(6).suffix(3))-\(randomString.suffix(3))"
+ }
+}
+
+class RectangleFactory {
+ static func createRectangle() -> Rectangle {
+ let id = IdRandomizer().randomString()
+ let size = RectangleSize()
+ let position = RectanglePosition(X: 0, Y: 0).randomPosition()
+ let backGroundColor = (red: Int.random(in: 0...255), green: Int.random(in: 0...255), blue: Int.random(in: 0...255))
+ let alpha = Int.random(in: 1...10)
+
+ return Rectangle(
+ id: id,
+ size: size,
+ position: position,
+ backGroundColor: backGroundColor,
+ alpha: alpha
+ )
+ }
+} | Swift | ๊ฐ์ธ์ ์ผ๋ก ํ์ ๊ฐ์ฒด๋ ํ๋กํ ์ฝ๋ค์ ๋ค๋ฅธ ํ์ผ๋ก ๋ถ๋ฆฌํ๋ ๊ฒ๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค
์ ๋ ๋ถ๋ฆฌํ์ ๋ ์ถํ์ ์ฝ๋ ์์ ์ ์ฐพ์๊ฐ๊ธฐ ์ฌ์์ ์ข์์ต๋๋ค |
@@ -0,0 +1,91 @@
+//
+// ViewController.swift
+// DrawingApp
+//
+// Created by ๊นํ๋ฆผ on 2023/03/28.
+//
+
+import UIKit
+import OSLog
+
+class ViewController: UIViewController {
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ let rect1 = RectangleFactory.createRectangle()
+ os_log("\(rect1.description)")
+ }
+}
+
+protocol RectangleComponent {
+ var id:String { get }
+ var size:RectangleSize { get }
+ var position:RectanglePosition { get }
+ var backGroundColor:(red:Int, green:Int, blue:Int) { get }
+ var alpha:Int { get }
+}
+
+class RectangleSize {
+ private var width:Double = 150
+ private var height:Double = 120
+
+ func getWidth() -> Double {
+ return self.width
+ }
+ func getHeight() -> Double {
+ return self.height
+ }
+}
+class RectanglePosition {
+ private var X:Double
+ private var Y:Double
+
+ init(X: Double, Y: Double) {
+ self.X = X
+ self.Y = Y
+ }
+ func randomPosition() -> RectanglePosition {
+ let x = Double.random(in: 0...UIScreen.main.bounds.width)
+ let y = Double.random(in: 0...UIScreen.main.bounds.height)
+ return RectanglePosition(X: x, Y: y)
+ }
+ func getPositionX() -> Double {
+ return self.X
+ }
+ func getPositionY() -> Double {
+ return self.Y
+ }
+}
+
+
+class IdRandomizer {
+ func randomString() -> String {
+ let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
+ var randomString = ""
+ for _ in 0..<9 {
+ let randomIndex = Int.random(in: 0..<letters.count)
+ let letter = letters[letters.index(letters.startIndex, offsetBy: randomIndex)]
+ randomString.append(letter)
+ }
+ return "\(randomString.prefix(3))-\(randomString.prefix(6).suffix(3))-\(randomString.suffix(3))"
+ }
+}
+
+class RectangleFactory {
+ static func createRectangle() -> Rectangle {
+ let id = IdRandomizer().randomString()
+ let size = RectangleSize()
+ let position = RectanglePosition(X: 0, Y: 0).randomPosition()
+ let backGroundColor = (red: Int.random(in: 0...255), green: Int.random(in: 0...255), blue: Int.random(in: 0...255))
+ let alpha = Int.random(in: 1...10)
+
+ return Rectangle(
+ id: id,
+ size: size,
+ position: position,
+ backGroundColor: backGroundColor,
+ alpha: alpha
+ )
+ }
+} | Swift | ํ๋ผ๋ฏธํฐ๋ฅผ ์ค๋ก ๋๋ ์ฃผ์ ๋ฐฉ์ ์ฝ๊ธฐ ํธํ๊ณ ๊น ๊ด๋ฆฌํ๊ธฐ ์์ํ๋ค์
์ ๋ ์นดํผ์นดํผ ํด๋๋ ๊น์? |
@@ -0,0 +1,32 @@
+//
+// Rectangle.swift
+// DrawingApp
+//
+// Created by ๊นํ๋ฆผ on 2023/03/30.
+//
+
+import Foundation
+
+class Rectangle : RectangleComponent {
+ let id:String
+ let size:RectangleSize
+ let position:RectanglePosition
+ let backGroundColor:(red:Int, green:Int, blue:Int)
+ let alpha:Int
+
+ init(id:String, size:RectangleSize, position:RectanglePosition, backGroundColor:(red:Int, green:Int, blue:Int), alpha:Int) {
+
+ self.id = id
+ self.size = size
+ self.position = position
+ self.backGroundColor = backGroundColor
+ self.alpha = alpha
+ }
+
+}
+
+extension Rectangle : CustomStringConvertible {
+ var description: String {
+ return "(\(id), X:\(position.getPositionX()), Y\(position.getPositionY()):, W\(size.getWidth()), H\(size.getHeight()), R:\(backGroundColor.red), G:\(backGroundColor.green), B:\(backGroundColor.blue), Alpha:\(alpha))"
+ }
+} | Swift | Color ํํํ์์ผ๋ก ํ๋ฒ์ ์ฌ๋ฌ๊ฐ์ ํ๋ผ๋ฏธํฐ๋ฅผ ๋ฐ์ ์ ์๋์ง ๋ชฐ๋๋ค์
ํ ์ ๋ฐฐ์๊ฐ์ |
@@ -0,0 +1,91 @@
+//
+// ViewController.swift
+// DrawingApp
+//
+// Created by ๊นํ๋ฆผ on 2023/03/28.
+//
+
+import UIKit
+import OSLog
+
+class ViewController: UIViewController {
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ let rect1 = RectangleFactory.createRectangle()
+ os_log("\(rect1.description)")
+ }
+}
+
+protocol RectangleComponent {
+ var id:String { get }
+ var size:RectangleSize { get }
+ var position:RectanglePosition { get }
+ var backGroundColor:(red:Int, green:Int, blue:Int) { get }
+ var alpha:Int { get }
+}
+
+class RectangleSize {
+ private var width:Double = 150
+ private var height:Double = 120
+
+ func getWidth() -> Double {
+ return self.width
+ }
+ func getHeight() -> Double {
+ return self.height
+ }
+}
+class RectanglePosition {
+ private var X:Double
+ private var Y:Double
+
+ init(X: Double, Y: Double) {
+ self.X = X
+ self.Y = Y
+ }
+ func randomPosition() -> RectanglePosition {
+ let x = Double.random(in: 0...UIScreen.main.bounds.width)
+ let y = Double.random(in: 0...UIScreen.main.bounds.height)
+ return RectanglePosition(X: x, Y: y)
+ }
+ func getPositionX() -> Double {
+ return self.X
+ }
+ func getPositionY() -> Double {
+ return self.Y
+ }
+}
+
+
+class IdRandomizer {
+ func randomString() -> String {
+ let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
+ var randomString = ""
+ for _ in 0..<9 {
+ let randomIndex = Int.random(in: 0..<letters.count)
+ let letter = letters[letters.index(letters.startIndex, offsetBy: randomIndex)]
+ randomString.append(letter)
+ }
+ return "\(randomString.prefix(3))-\(randomString.prefix(6).suffix(3))-\(randomString.suffix(3))"
+ }
+}
+
+class RectangleFactory {
+ static func createRectangle() -> Rectangle {
+ let id = IdRandomizer().randomString()
+ let size = RectangleSize()
+ let position = RectanglePosition(X: 0, Y: 0).randomPosition()
+ let backGroundColor = (red: Int.random(in: 0...255), green: Int.random(in: 0...255), blue: Int.random(in: 0...255))
+ let alpha = Int.random(in: 1...10)
+
+ return Rectangle(
+ id: id,
+ size: size,
+ position: position,
+ backGroundColor: backGroundColor,
+ alpha: alpha
+ )
+ }
+} | Swift | ๋ชจ๋ธ ํ์ ํ์
์ ํด๋์ค๋ก ํ์
จ๋๋ฐ ์ ํํ์ ๊ธฐ์ค์ด ์๋์ง ๊ถ๊ธํด์ |
@@ -0,0 +1,91 @@
+//
+// ViewController.swift
+// DrawingApp
+//
+// Created by ๊นํ๋ฆผ on 2023/03/28.
+//
+
+import UIKit
+import OSLog
+
+class ViewController: UIViewController {
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ let rect1 = RectangleFactory.createRectangle()
+ os_log("\(rect1.description)")
+ }
+}
+
+protocol RectangleComponent {
+ var id:String { get }
+ var size:RectangleSize { get }
+ var position:RectanglePosition { get }
+ var backGroundColor:(red:Int, green:Int, blue:Int) { get }
+ var alpha:Int { get }
+}
+
+class RectangleSize {
+ private var width:Double = 150
+ private var height:Double = 120
+
+ func getWidth() -> Double {
+ return self.width
+ }
+ func getHeight() -> Double {
+ return self.height
+ }
+}
+class RectanglePosition {
+ private var X:Double
+ private var Y:Double
+
+ init(X: Double, Y: Double) {
+ self.X = X
+ self.Y = Y
+ }
+ func randomPosition() -> RectanglePosition {
+ let x = Double.random(in: 0...UIScreen.main.bounds.width)
+ let y = Double.random(in: 0...UIScreen.main.bounds.height)
+ return RectanglePosition(X: x, Y: y)
+ }
+ func getPositionX() -> Double {
+ return self.X
+ }
+ func getPositionY() -> Double {
+ return self.Y
+ }
+}
+
+
+class IdRandomizer {
+ func randomString() -> String {
+ let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
+ var randomString = ""
+ for _ in 0..<9 {
+ let randomIndex = Int.random(in: 0..<letters.count)
+ let letter = letters[letters.index(letters.startIndex, offsetBy: randomIndex)]
+ randomString.append(letter)
+ }
+ return "\(randomString.prefix(3))-\(randomString.prefix(6).suffix(3))-\(randomString.suffix(3))"
+ }
+}
+
+class RectangleFactory {
+ static func createRectangle() -> Rectangle {
+ let id = IdRandomizer().randomString()
+ let size = RectangleSize()
+ let position = RectanglePosition(X: 0, Y: 0).randomPosition()
+ let backGroundColor = (red: Int.random(in: 0...255), green: Int.random(in: 0...255), blue: Int.random(in: 0...255))
+ let alpha = Int.random(in: 1...10)
+
+ return Rectangle(
+ id: id,
+ size: size,
+ position: position,
+ backGroundColor: backGroundColor,
+ alpha: alpha
+ )
+ }
+} | Swift | ๋ง์ฝ ์ธ๋ถ์์ ๋ฐ๋์ ์ ๊ทผํด์ผ๋ง ํ๋ค๋ฉด private์ ๋นผ๋๊ฒ๋ ์ข์๋ณด์
๋๋ค |
@@ -0,0 +1,91 @@
+//
+// ViewController.swift
+// DrawingApp
+//
+// Created by ๊นํ๋ฆผ on 2023/03/28.
+//
+
+import UIKit
+import OSLog
+
+class ViewController: UIViewController {
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ let rect1 = RectangleFactory.createRectangle()
+ os_log("\(rect1.description)")
+ }
+}
+
+protocol RectangleComponent {
+ var id:String { get }
+ var size:RectangleSize { get }
+ var position:RectanglePosition { get }
+ var backGroundColor:(red:Int, green:Int, blue:Int) { get }
+ var alpha:Int { get }
+}
+
+class RectangleSize {
+ private var width:Double = 150
+ private var height:Double = 120
+
+ func getWidth() -> Double {
+ return self.width
+ }
+ func getHeight() -> Double {
+ return self.height
+ }
+}
+class RectanglePosition {
+ private var X:Double
+ private var Y:Double
+
+ init(X: Double, Y: Double) {
+ self.X = X
+ self.Y = Y
+ }
+ func randomPosition() -> RectanglePosition {
+ let x = Double.random(in: 0...UIScreen.main.bounds.width)
+ let y = Double.random(in: 0...UIScreen.main.bounds.height)
+ return RectanglePosition(X: x, Y: y)
+ }
+ func getPositionX() -> Double {
+ return self.X
+ }
+ func getPositionY() -> Double {
+ return self.Y
+ }
+}
+
+
+class IdRandomizer {
+ func randomString() -> String {
+ let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
+ var randomString = ""
+ for _ in 0..<9 {
+ let randomIndex = Int.random(in: 0..<letters.count)
+ let letter = letters[letters.index(letters.startIndex, offsetBy: randomIndex)]
+ randomString.append(letter)
+ }
+ return "\(randomString.prefix(3))-\(randomString.prefix(6).suffix(3))-\(randomString.suffix(3))"
+ }
+}
+
+class RectangleFactory {
+ static func createRectangle() -> Rectangle {
+ let id = IdRandomizer().randomString()
+ let size = RectangleSize()
+ let position = RectanglePosition(X: 0, Y: 0).randomPosition()
+ let backGroundColor = (red: Int.random(in: 0...255), green: Int.random(in: 0...255), blue: Int.random(in: 0...255))
+ let alpha = Int.random(in: 1...10)
+
+ return Rectangle(
+ id: id,
+ size: size,
+ position: position,
+ backGroundColor: backGroundColor,
+ alpha: alpha
+ )
+ }
+} | Swift | class func ๋์ static func์ ์ฐ์ ์ด์ ๋ ์ค๋ฒ๋ผ์ด๋ฉ์ด ๋ถ๊ฐ๋ฅํ๋๋ก ์๋ํ์ ๊ฑฐ ๋ง์๊น์?๐๐ป |
@@ -0,0 +1,91 @@
+//
+// ViewController.swift
+// DrawingApp
+//
+// Created by ๊นํ๋ฆผ on 2023/03/28.
+//
+
+import UIKit
+import OSLog
+
+class ViewController: UIViewController {
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ let rect1 = RectangleFactory.createRectangle()
+ os_log("\(rect1.description)")
+ }
+}
+
+protocol RectangleComponent {
+ var id:String { get }
+ var size:RectangleSize { get }
+ var position:RectanglePosition { get }
+ var backGroundColor:(red:Int, green:Int, blue:Int) { get }
+ var alpha:Int { get }
+}
+
+class RectangleSize {
+ private var width:Double = 150
+ private var height:Double = 120
+
+ func getWidth() -> Double {
+ return self.width
+ }
+ func getHeight() -> Double {
+ return self.height
+ }
+}
+class RectanglePosition {
+ private var X:Double
+ private var Y:Double
+
+ init(X: Double, Y: Double) {
+ self.X = X
+ self.Y = Y
+ }
+ func randomPosition() -> RectanglePosition {
+ let x = Double.random(in: 0...UIScreen.main.bounds.width)
+ let y = Double.random(in: 0...UIScreen.main.bounds.height)
+ return RectanglePosition(X: x, Y: y)
+ }
+ func getPositionX() -> Double {
+ return self.X
+ }
+ func getPositionY() -> Double {
+ return self.Y
+ }
+}
+
+
+class IdRandomizer {
+ func randomString() -> String {
+ let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
+ var randomString = ""
+ for _ in 0..<9 {
+ let randomIndex = Int.random(in: 0..<letters.count)
+ let letter = letters[letters.index(letters.startIndex, offsetBy: randomIndex)]
+ randomString.append(letter)
+ }
+ return "\(randomString.prefix(3))-\(randomString.prefix(6).suffix(3))-\(randomString.suffix(3))"
+ }
+}
+
+class RectangleFactory {
+ static func createRectangle() -> Rectangle {
+ let id = IdRandomizer().randomString()
+ let size = RectangleSize()
+ let position = RectanglePosition(X: 0, Y: 0).randomPosition()
+ let backGroundColor = (red: Int.random(in: 0...255), green: Int.random(in: 0...255), blue: Int.random(in: 0...255))
+ let alpha = Int.random(in: 1...10)
+
+ return Rectangle(
+ id: id,
+ size: size,
+ position: position,
+ backGroundColor: backGroundColor,
+ alpha: alpha
+ )
+ }
+} | Swift | [UIScreen.main ๊ณต์๋ฌธ์](https://developer.apple.com/documentation/uikit/uiscreen/1617815-main)
์ฐ์ฐํ Apple Documentation์์ ๋ฐ๊ฒฌํ๋๋ฐ, main์ Deprecated ๋์๋๋ผ๊ณ ์
์๋จ ๊ณต์๋ฌธ์ ๋ด์ฉ์์ ์ถ์ฒํ๋ ๋ค๋ฅธ๋ฐฉ๋ฒ์ ์ฌ์ฉํด๋ณด์๋ ๊ฒ๋ ์ข์๊ฑฐ๊ฐ์์ |
@@ -0,0 +1,91 @@
+//
+// ViewController.swift
+// DrawingApp
+//
+// Created by ๊นํ๋ฆผ on 2023/03/28.
+//
+
+import UIKit
+import OSLog
+
+class ViewController: UIViewController {
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ let rect1 = RectangleFactory.createRectangle()
+ os_log("\(rect1.description)")
+ }
+}
+
+protocol RectangleComponent {
+ var id:String { get }
+ var size:RectangleSize { get }
+ var position:RectanglePosition { get }
+ var backGroundColor:(red:Int, green:Int, blue:Int) { get }
+ var alpha:Int { get }
+}
+
+class RectangleSize {
+ private var width:Double = 150
+ private var height:Double = 120
+
+ func getWidth() -> Double {
+ return self.width
+ }
+ func getHeight() -> Double {
+ return self.height
+ }
+}
+class RectanglePosition {
+ private var X:Double
+ private var Y:Double
+
+ init(X: Double, Y: Double) {
+ self.X = X
+ self.Y = Y
+ }
+ func randomPosition() -> RectanglePosition {
+ let x = Double.random(in: 0...UIScreen.main.bounds.width)
+ let y = Double.random(in: 0...UIScreen.main.bounds.height)
+ return RectanglePosition(X: x, Y: y)
+ }
+ func getPositionX() -> Double {
+ return self.X
+ }
+ func getPositionY() -> Double {
+ return self.Y
+ }
+}
+
+
+class IdRandomizer {
+ func randomString() -> String {
+ let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
+ var randomString = ""
+ for _ in 0..<9 {
+ let randomIndex = Int.random(in: 0..<letters.count)
+ let letter = letters[letters.index(letters.startIndex, offsetBy: randomIndex)]
+ randomString.append(letter)
+ }
+ return "\(randomString.prefix(3))-\(randomString.prefix(6).suffix(3))-\(randomString.suffix(3))"
+ }
+}
+
+class RectangleFactory {
+ static func createRectangle() -> Rectangle {
+ let id = IdRandomizer().randomString()
+ let size = RectangleSize()
+ let position = RectanglePosition(X: 0, Y: 0).randomPosition()
+ let backGroundColor = (red: Int.random(in: 0...255), green: Int.random(in: 0...255), blue: Int.random(in: 0...255))
+ let alpha = Int.random(in: 1...10)
+
+ return Rectangle(
+ id: id,
+ size: size,
+ position: position,
+ backGroundColor: backGroundColor,
+ alpha: alpha
+ )
+ }
+} | Swift | ํ์ต ๊ฐ์ด๋์์ ์ฐธ๊ณ ํ๋๋ฐ,
๋ฉ์๋ ๋ค์ด๋ฐ์ ํจ์๋ก ์์ฑํ๋๊ฒ ์ข๋ค๊ณ ๋์ด์์ด ์ฐธ๊ณ ํ์๋ฉด ์ข์ ๋ณด์
๋๋ค |
@@ -0,0 +1,91 @@
+//
+// ViewController.swift
+// DrawingApp
+//
+// Created by ๊นํ๋ฆผ on 2023/03/28.
+//
+
+import UIKit
+import OSLog
+
+class ViewController: UIViewController {
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ let rect1 = RectangleFactory.createRectangle()
+ os_log("\(rect1.description)")
+ }
+}
+
+protocol RectangleComponent {
+ var id:String { get }
+ var size:RectangleSize { get }
+ var position:RectanglePosition { get }
+ var backGroundColor:(red:Int, green:Int, blue:Int) { get }
+ var alpha:Int { get }
+}
+
+class RectangleSize {
+ private var width:Double = 150
+ private var height:Double = 120
+
+ func getWidth() -> Double {
+ return self.width
+ }
+ func getHeight() -> Double {
+ return self.height
+ }
+}
+class RectanglePosition {
+ private var X:Double
+ private var Y:Double
+
+ init(X: Double, Y: Double) {
+ self.X = X
+ self.Y = Y
+ }
+ func randomPosition() -> RectanglePosition {
+ let x = Double.random(in: 0...UIScreen.main.bounds.width)
+ let y = Double.random(in: 0...UIScreen.main.bounds.height)
+ return RectanglePosition(X: x, Y: y)
+ }
+ func getPositionX() -> Double {
+ return self.X
+ }
+ func getPositionY() -> Double {
+ return self.Y
+ }
+}
+
+
+class IdRandomizer {
+ func randomString() -> String {
+ let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
+ var randomString = ""
+ for _ in 0..<9 {
+ let randomIndex = Int.random(in: 0..<letters.count)
+ let letter = letters[letters.index(letters.startIndex, offsetBy: randomIndex)]
+ randomString.append(letter)
+ }
+ return "\(randomString.prefix(3))-\(randomString.prefix(6).suffix(3))-\(randomString.suffix(3))"
+ }
+}
+
+class RectangleFactory {
+ static func createRectangle() -> Rectangle {
+ let id = IdRandomizer().randomString()
+ let size = RectangleSize()
+ let position = RectanglePosition(X: 0, Y: 0).randomPosition()
+ let backGroundColor = (red: Int.random(in: 0...255), green: Int.random(in: 0...255), blue: Int.random(in: 0...255))
+ let alpha = Int.random(in: 1...10)
+
+ return Rectangle(
+ id: id,
+ size: size,
+ position: position,
+ backGroundColor: backGroundColor,
+ alpha: alpha
+ )
+ }
+} | Swift | uuid ์์ด ๋ง๋๋ ๋ฐฉ์์ด ์๋์ง๋ ๋ชฐ๋๋๋ฐ, ์ ์ ํ๊ณ ๋ ๊น๋ํ ๋ฐฉ์์ด๋ค์๐๐ป |
@@ -0,0 +1,91 @@
+//
+// ViewController.swift
+// DrawingApp
+//
+// Created by ๊นํ๋ฆผ on 2023/03/28.
+//
+
+import UIKit
+import OSLog
+
+class ViewController: UIViewController {
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ let rect1 = RectangleFactory.createRectangle()
+ os_log("\(rect1.description)")
+ }
+}
+
+protocol RectangleComponent {
+ var id:String { get }
+ var size:RectangleSize { get }
+ var position:RectanglePosition { get }
+ var backGroundColor:(red:Int, green:Int, blue:Int) { get }
+ var alpha:Int { get }
+}
+
+class RectangleSize {
+ private var width:Double = 150
+ private var height:Double = 120
+
+ func getWidth() -> Double {
+ return self.width
+ }
+ func getHeight() -> Double {
+ return self.height
+ }
+}
+class RectanglePosition {
+ private var X:Double
+ private var Y:Double
+
+ init(X: Double, Y: Double) {
+ self.X = X
+ self.Y = Y
+ }
+ func randomPosition() -> RectanglePosition {
+ let x = Double.random(in: 0...UIScreen.main.bounds.width)
+ let y = Double.random(in: 0...UIScreen.main.bounds.height)
+ return RectanglePosition(X: x, Y: y)
+ }
+ func getPositionX() -> Double {
+ return self.X
+ }
+ func getPositionY() -> Double {
+ return self.Y
+ }
+}
+
+
+class IdRandomizer {
+ func randomString() -> String {
+ let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
+ var randomString = ""
+ for _ in 0..<9 {
+ let randomIndex = Int.random(in: 0..<letters.count)
+ let letter = letters[letters.index(letters.startIndex, offsetBy: randomIndex)]
+ randomString.append(letter)
+ }
+ return "\(randomString.prefix(3))-\(randomString.prefix(6).suffix(3))-\(randomString.suffix(3))"
+ }
+}
+
+class RectangleFactory {
+ static func createRectangle() -> Rectangle {
+ let id = IdRandomizer().randomString()
+ let size = RectangleSize()
+ let position = RectanglePosition(X: 0, Y: 0).randomPosition()
+ let backGroundColor = (red: Int.random(in: 0...255), green: Int.random(in: 0...255), blue: Int.random(in: 0...255))
+ let alpha = Int.random(in: 1...10)
+
+ return Rectangle(
+ id: id,
+ size: size,
+ position: position,
+ backGroundColor: backGroundColor,
+ alpha: alpha
+ )
+ }
+} | Swift | ํ๋กํ ์ฝ์ ์ ์ธ๋ ํ๋กํผํฐ๋ค์ ์ฑํํ์ ๋ private ์ ๊ทผ์ ์ด์๋ฅผ ์ฌ์ฉํ์ง ๋ชปํ๋ ๊ฑธ๋ก ์๊ณ ์์ต๋๋ค.
์ ๊ทผ์ ์ด์๊ฐ ํ์ํ ์์๋ค๋ง ํ๋กํ ์ฝ์ ์ถ๊ฐํ๋ ๊ฒ๋ ์ข์ ๋ณด์
๋๋ค. |
@@ -0,0 +1,83 @@
+package christmas.service;
+
+import christmas.constant.Constant;
+import christmas.domain.Badge;
+import christmas.domain.Benefit;
+import christmas.domain.Event;
+import christmas.domain.OrderMenu;
+import christmas.view.input.template.InputCallback;
+import christmas.view.input.template.InputTemplate;
+
+public class ChristmasService {
+
+ private final InputTemplate inputTemplate;
+
+ public ChristmasService() {
+ this.inputTemplate = new InputTemplate();
+ }
+
+ public <T> T getInputRequestResult(InputCallback<T> callback) {
+ return inputTemplate.execute(callback);
+ }
+
+ public Benefit getBenefit(OrderMenu orderMenu, int day) {
+ Benefit benefit = new Benefit();
+ addDiscountIntoBenefitDetails(orderMenu, benefit, day);
+ return benefit;
+ }
+
+ public String getOrderMenuDetails(OrderMenu orderMenu) {
+ return orderMenu.detailsToString();
+ }
+
+ public String getTotalPriceBeforeDiscount(OrderMenu orderMenu) {
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), orderMenu.calculateTotalPrice());
+ }
+
+ public String getPresentationMenu(Benefit benefit) {
+ return benefit.presentationMenuToString();
+ }
+
+ public String getBenefitDetails(Benefit benefit) {
+ return benefit.detailsToString();
+ }
+
+ public String getTotalDiscount(Benefit benefit) {
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), benefit.calculateTotalDiscount());
+ }
+
+ public String getTotalPriceAfterDiscount(OrderMenu orderMenu, Benefit benefit) {
+ int totalPrice = orderMenu.calculateTotalPrice();
+ int totalDiscount = benefit.calculateTotalDiscount();
+ totalPrice += (totalDiscount - benefit.calculatePresentationPrice());
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), totalPrice);
+ }
+
+ public String getBadge(Benefit benefit) {
+ return Badge.findByTotalDiscount(benefit.calculateTotalDiscount());
+ }
+
+
+ private void addDiscountIntoBenefitDetails(OrderMenu orderMenu, Benefit benefit, int day) {
+ Event.findAllByDay(day)
+ .stream()
+ .filter(event -> orderMenu.calculateTotalPrice() > event.getCondition())
+ .forEach(event -> benefit.addDiscountIntoDetails(event, calculateDiscount(orderMenu, event, day)));
+ }
+
+ private int calculateDiscount(OrderMenu orderMenu, Event event, int day) {
+ int result = 0;
+ int orderMenuCount = orderMenu.countMenuByEventTarget(event.getTarget());
+ int discount = event.getDiscount();
+ int discountFromTotal = event.getDiscountFromTotal();
+ result -= (discount * orderMenuCount) + discountFromTotal;
+
+ if (event == Event.CHRISTMAS && day <= 25) {
+ result -= discount * (day - 1) + 1000;
+ }
+ if (event == Event.PRESENTATION) {
+ result -= discount;
+ }
+ return result;
+ }
+} | Java | ์์์ inputView์ ๋ฉ์๋๋ฅผ ๋๊ฒจ๋ฐ๊ณ ์คํํ๋ ๋ชจ์ต์ด๋๋ฐ, ๊ทธ๋ฅ ChristmasController์์ ์งํํ๋ ๊ฒ ์ข์์ ๊ฒ ๊ฐ์์. ๊ตณ์ด ์๋น์ค๊น์ง ๊ฑธ์น ํ์๊ฐ ์์์ ๊ฒ ๊ฐ์์.
์๋น์ค ๊ฐ์ฒด ๋ด์์ ํด๋น ๋ฉ์๋๊ฐ ์ฐ์ธ ๊ฒ๋ ์๋๊ณ , ์ค๋ก์ง ์ปจํธ๋กค๋ฌ์์๋ง ์ด ๋ฉ์๋๊ฐ ํธ์ถ๋๊ณ ์์ด์. |
@@ -0,0 +1,72 @@
+package christmas.domain;
+
+import christmas.constant.Constant;
+import java.util.EnumMap;
+import java.util.Map;
+import java.util.Map.Entry;
+
+public class Benefit {
+
+ private final Map<Event, Integer> details;
+
+ public Benefit() {
+ this.details = new EnumMap<>(Event.class);
+ initialBenefitDetails();
+ }
+
+ public int calculateTotalDiscount() {
+ return details.values()
+ .stream()
+ .reduce(0, Integer::sum);
+ }
+
+ public void addDiscountIntoDetails(Event event, int discount) {
+ details.computeIfPresent(event, (key, value) -> value + discount);
+ }
+
+ public String detailsToString() {
+ StringBuilder sb = new StringBuilder(Constant.NOTHING + System.lineSeparator());
+ if (calculateTotalDiscount() != 0) {
+ sb.setLength(0);
+ appendDetails(sb);
+ }
+ return sb.toString();
+ }
+
+ public int calculatePresentationPrice() {
+ return details.get(Event.PRESENTATION);
+ }
+
+ public String presentationMenuToString() {
+ Event presentation = Event.PRESENTATION;
+ StringBuilder sb = new StringBuilder(Constant.NOTHING + System.lineSeparator());
+ int discount = details.get(presentation);
+ if (discount != 0) {
+ sb.setLength(0);
+ sb.append(presentation.getTarget());
+ sb.append(Constant.SPACE);
+ sb.append(String.format(Constant.MENU_UNIT, Math.abs(discount / Event.PRESENTATION.getDiscount())));
+ sb.append(System.lineSeparator());
+ }
+ return sb.toString();
+ }
+
+
+ private void appendDetails(StringBuilder benefitDetail) {
+ for (Entry<Event, Integer> entry : details.entrySet()) {
+ String eventMessage = entry.getKey().getMessage();
+ int discount = entry.getValue();
+ if (discount != 0) {
+ benefitDetail.append(eventMessage);
+ benefitDetail.append(Constant.SPACE);
+ benefitDetail.append(String.format(Constant.PRICE_UNIT, discount));
+ benefitDetail.append(System.lineSeparator());
+ }
+ }
+ }
+
+ private void initialBenefitDetails() {
+ Event.getAllEvent().forEach(event -> details.put(event, 0));
+ }
+
+} | Java | add ๋ฉ์๋๋ฅผ ๊ตฌํํ๋ ๊ฒ๋ณด๋ค๋ ์์ฑ์์์ ์์ฑ๋ EnumMap์ ๋ฐ๋ ๊ฒ ์ข์ ๊ฒ ๊ฐ์์.
add ๋ฉ์๋๋ฅผ ์ด์ฉํด์ EnumMap์ ๋ง๋๋ ์ฑ
์์ BenefitBuilder ๊ฐ์ฒด๋ฅผ ์๋ก ๋ง๋ค์ด์ ๋งก๊ธฐ๋ ๊ฒ ์ข์์. |
@@ -0,0 +1,83 @@
+package christmas.service;
+
+import christmas.constant.Constant;
+import christmas.domain.Badge;
+import christmas.domain.Benefit;
+import christmas.domain.Event;
+import christmas.domain.OrderMenu;
+import christmas.view.input.template.InputCallback;
+import christmas.view.input.template.InputTemplate;
+
+public class ChristmasService {
+
+ private final InputTemplate inputTemplate;
+
+ public ChristmasService() {
+ this.inputTemplate = new InputTemplate();
+ }
+
+ public <T> T getInputRequestResult(InputCallback<T> callback) {
+ return inputTemplate.execute(callback);
+ }
+
+ public Benefit getBenefit(OrderMenu orderMenu, int day) {
+ Benefit benefit = new Benefit();
+ addDiscountIntoBenefitDetails(orderMenu, benefit, day);
+ return benefit;
+ }
+
+ public String getOrderMenuDetails(OrderMenu orderMenu) {
+ return orderMenu.detailsToString();
+ }
+
+ public String getTotalPriceBeforeDiscount(OrderMenu orderMenu) {
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), orderMenu.calculateTotalPrice());
+ }
+
+ public String getPresentationMenu(Benefit benefit) {
+ return benefit.presentationMenuToString();
+ }
+
+ public String getBenefitDetails(Benefit benefit) {
+ return benefit.detailsToString();
+ }
+
+ public String getTotalDiscount(Benefit benefit) {
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), benefit.calculateTotalDiscount());
+ }
+
+ public String getTotalPriceAfterDiscount(OrderMenu orderMenu, Benefit benefit) {
+ int totalPrice = orderMenu.calculateTotalPrice();
+ int totalDiscount = benefit.calculateTotalDiscount();
+ totalPrice += (totalDiscount - benefit.calculatePresentationPrice());
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), totalPrice);
+ }
+
+ public String getBadge(Benefit benefit) {
+ return Badge.findByTotalDiscount(benefit.calculateTotalDiscount());
+ }
+
+
+ private void addDiscountIntoBenefitDetails(OrderMenu orderMenu, Benefit benefit, int day) {
+ Event.findAllByDay(day)
+ .stream()
+ .filter(event -> orderMenu.calculateTotalPrice() > event.getCondition())
+ .forEach(event -> benefit.addDiscountIntoDetails(event, calculateDiscount(orderMenu, event, day)));
+ }
+
+ private int calculateDiscount(OrderMenu orderMenu, Event event, int day) {
+ int result = 0;
+ int orderMenuCount = orderMenu.countMenuByEventTarget(event.getTarget());
+ int discount = event.getDiscount();
+ int discountFromTotal = event.getDiscountFromTotal();
+ result -= (discount * orderMenuCount) + discountFromTotal;
+
+ if (event == Event.CHRISTMAS && day <= 25) {
+ result -= discount * (day - 1) + 1000;
+ }
+ if (event == Event.PRESENTATION) {
+ result -= discount;
+ }
+ return result;
+ }
+} | Java | benefit init์ ํด์ผ ํ๋ค๋ฉด, ์ธ๋ถ์์ ๋ฐ์์ค๋ ๊ฒ๋ณด๋ค๋ ๋ด๋ถ์์ benefit๋ฅผ ์์ฑํ๊ณ ๋ฐํํ๊ฒ ํ๋ ๊ฒ ์ข์์. ์ธ๋ถ์์ ๋ฐ์์จ benefit์ ๋ํด ์์
์ ์งํํ๋ฉด side effect๊ฐ ๋ฐ์ํ ์ฌ์ง๊ฐ ๋์์.
ํด๋น ์ฝ๋๋ ๋ฉ์๋๋ก ๋ถ๋ฆฌํ์ง ์๋ ๊ฒ ์ข์์ ๊ฒ ๊ฐ์์.
๋น๋๋ฅผ ํ์ฉํ๋ฉด ๋ ์ข์ต๋๋ค :DD |
@@ -0,0 +1,83 @@
+package christmas.service;
+
+import christmas.constant.Constant;
+import christmas.domain.Badge;
+import christmas.domain.Benefit;
+import christmas.domain.Event;
+import christmas.domain.OrderMenu;
+import christmas.view.input.template.InputCallback;
+import christmas.view.input.template.InputTemplate;
+
+public class ChristmasService {
+
+ private final InputTemplate inputTemplate;
+
+ public ChristmasService() {
+ this.inputTemplate = new InputTemplate();
+ }
+
+ public <T> T getInputRequestResult(InputCallback<T> callback) {
+ return inputTemplate.execute(callback);
+ }
+
+ public Benefit getBenefit(OrderMenu orderMenu, int day) {
+ Benefit benefit = new Benefit();
+ addDiscountIntoBenefitDetails(orderMenu, benefit, day);
+ return benefit;
+ }
+
+ public String getOrderMenuDetails(OrderMenu orderMenu) {
+ return orderMenu.detailsToString();
+ }
+
+ public String getTotalPriceBeforeDiscount(OrderMenu orderMenu) {
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), orderMenu.calculateTotalPrice());
+ }
+
+ public String getPresentationMenu(Benefit benefit) {
+ return benefit.presentationMenuToString();
+ }
+
+ public String getBenefitDetails(Benefit benefit) {
+ return benefit.detailsToString();
+ }
+
+ public String getTotalDiscount(Benefit benefit) {
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), benefit.calculateTotalDiscount());
+ }
+
+ public String getTotalPriceAfterDiscount(OrderMenu orderMenu, Benefit benefit) {
+ int totalPrice = orderMenu.calculateTotalPrice();
+ int totalDiscount = benefit.calculateTotalDiscount();
+ totalPrice += (totalDiscount - benefit.calculatePresentationPrice());
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), totalPrice);
+ }
+
+ public String getBadge(Benefit benefit) {
+ return Badge.findByTotalDiscount(benefit.calculateTotalDiscount());
+ }
+
+
+ private void addDiscountIntoBenefitDetails(OrderMenu orderMenu, Benefit benefit, int day) {
+ Event.findAllByDay(day)
+ .stream()
+ .filter(event -> orderMenu.calculateTotalPrice() > event.getCondition())
+ .forEach(event -> benefit.addDiscountIntoDetails(event, calculateDiscount(orderMenu, event, day)));
+ }
+
+ private int calculateDiscount(OrderMenu orderMenu, Event event, int day) {
+ int result = 0;
+ int orderMenuCount = orderMenu.countMenuByEventTarget(event.getTarget());
+ int discount = event.getDiscount();
+ int discountFromTotal = event.getDiscountFromTotal();
+ result -= (discount * orderMenuCount) + discountFromTotal;
+
+ if (event == Event.CHRISTMAS && day <= 25) {
+ result -= discount * (day - 1) + 1000;
+ }
+ if (event == Event.PRESENTATION) {
+ result -= discount;
+ }
+ return result;
+ }
+} | Java | ํ ์ธ์ก์ ๊ณ์ฐํ๋ ๋ก์ง์ด ์ธ๋ถ๋ก ๋
ธ์ถ๋์ด ์์ด์.
enum์ ํ์ฉํ์
จ์ผ๋ ์ ๋ค๋ฌ์ผ๋ฉด ์ด๋ ๊ฒ ๋ฐ๊ฟ ์ ์์ด์.
```suggestion
private int calculateDiscount(OrderMenu orderMenu, Event event, int day) {
return event.calculateDiscount(orderMenu, day);
}
```
์ด๋ฌ๋ฉด ๋ฉ์๋๋ก ๋ถ๋ฆฌํ ํ์๋ ์์ด์ง๊ณ ์ข์์.
์ด๋ฒคํธ enum๋ง๋ค ๋๋ค์์ ์์ฑํด์ ํํ์ก์ ๊ณ์ฐํด๋ณด์ธ์. |
@@ -0,0 +1,83 @@
+package christmas.service;
+
+import christmas.constant.Constant;
+import christmas.domain.Badge;
+import christmas.domain.Benefit;
+import christmas.domain.Event;
+import christmas.domain.OrderMenu;
+import christmas.view.input.template.InputCallback;
+import christmas.view.input.template.InputTemplate;
+
+public class ChristmasService {
+
+ private final InputTemplate inputTemplate;
+
+ public ChristmasService() {
+ this.inputTemplate = new InputTemplate();
+ }
+
+ public <T> T getInputRequestResult(InputCallback<T> callback) {
+ return inputTemplate.execute(callback);
+ }
+
+ public Benefit getBenefit(OrderMenu orderMenu, int day) {
+ Benefit benefit = new Benefit();
+ addDiscountIntoBenefitDetails(orderMenu, benefit, day);
+ return benefit;
+ }
+
+ public String getOrderMenuDetails(OrderMenu orderMenu) {
+ return orderMenu.detailsToString();
+ }
+
+ public String getTotalPriceBeforeDiscount(OrderMenu orderMenu) {
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), orderMenu.calculateTotalPrice());
+ }
+
+ public String getPresentationMenu(Benefit benefit) {
+ return benefit.presentationMenuToString();
+ }
+
+ public String getBenefitDetails(Benefit benefit) {
+ return benefit.detailsToString();
+ }
+
+ public String getTotalDiscount(Benefit benefit) {
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), benefit.calculateTotalDiscount());
+ }
+
+ public String getTotalPriceAfterDiscount(OrderMenu orderMenu, Benefit benefit) {
+ int totalPrice = orderMenu.calculateTotalPrice();
+ int totalDiscount = benefit.calculateTotalDiscount();
+ totalPrice += (totalDiscount - benefit.calculatePresentationPrice());
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), totalPrice);
+ }
+
+ public String getBadge(Benefit benefit) {
+ return Badge.findByTotalDiscount(benefit.calculateTotalDiscount());
+ }
+
+
+ private void addDiscountIntoBenefitDetails(OrderMenu orderMenu, Benefit benefit, int day) {
+ Event.findAllByDay(day)
+ .stream()
+ .filter(event -> orderMenu.calculateTotalPrice() > event.getCondition())
+ .forEach(event -> benefit.addDiscountIntoDetails(event, calculateDiscount(orderMenu, event, day)));
+ }
+
+ private int calculateDiscount(OrderMenu orderMenu, Event event, int day) {
+ int result = 0;
+ int orderMenuCount = orderMenu.countMenuByEventTarget(event.getTarget());
+ int discount = event.getDiscount();
+ int discountFromTotal = event.getDiscountFromTotal();
+ result -= (discount * orderMenuCount) + discountFromTotal;
+
+ if (event == Event.CHRISTMAS && day <= 25) {
+ result -= discount * (day - 1) + 1000;
+ }
+ if (event == Event.PRESENTATION) {
+ result -= discount;
+ }
+ return result;
+ }
+} | Java | ์ด๋ฐ ์๋ช
ํ ์ฝ๋๋ค์ ๋ฉ์๋๋ก ๋ถ๋ฆฌํ ํ์๊ฐ ์์ด์. ์๋น์ค ๊ฐ์ฒด๊น์ง ์ด์ฉํ ํ์๋ ๋๋์ฑ ์์ด์. |
@@ -0,0 +1,58 @@
+package christmas.constant;
+
+import christmas.constant.MenuConstant.MenuType;
+import christmas.domain.Menu;
+import java.util.List;
+
+public class EventConstant {
+ public static class Condition {
+
+ public static final int CASE_A = 10000;
+ public static final int CASE_B = 120000;
+ }
+
+ public static class Days {
+
+ public static final List<Integer> EVERY = List.of(1, 2, 3, 4, 5, 6);
+ public static final List<Integer> WEEKDAY = List.of(0, 3, 4, 5, 6);
+ public static final List<Integer> WEEKEND = List.of(1, 2);
+ public static final List<Integer> SPECIAL = List.of(3, 25);
+
+ }
+
+ public static class Target {
+
+ public static final String WEEKDAY = MenuType.DESSERT;
+ public static final String WEEKEND = MenuType.MAIN;
+ public static final String CHRISTMAS = MenuType.NONE;
+ public static final String SPECIAL = MenuType.NONE;
+ public static final String PRESENTATION = Menu.CHAMPAGNE.getName();
+
+ }
+
+ public static class Discount {
+
+ public static final int WEEKDAY = 2023;
+ public static final int WEEKEND = 2023;
+ public static final int CHRISTMAS = 100;
+ public static final int SPECIAL = 0;
+ public static final int PRESENTATION = Menu.CHAMPAGNE.getPrice() * 1;
+
+ }
+
+ public static class TotalDiscount {
+ public static final int SPECIAL = 1000;
+ public static final int OTHER = 0;
+ }
+
+ public static class Message {
+
+ public static final String SPECIAL = "ํน๋ณ ํ ์ธ:";
+ public static final String WEEKDAY = "ํ์ผ ํ ์ธ:";
+ public static final String WEEKEND = "์ฃผ๋ง ํ ์ธ:";
+ public static final String CHRISTMAS = "ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ:";
+ public static final String PRESENTATION = "์ฆ์ ์ด๋ฒคํธ:";
+
+ }
+
+} | Java | ์ด๊ฒ ๋ฌด์จ ์์์ธ์ง ์ ์๊ฐ ์์ด์. ์ด๋ฆ์ ๋ช
ํํ ์ง์ด์ฃผ์ธ์.
์์ด๊ฐ ์๋ง์ด๋๋ผ๋ EventAvailablePrice ๊ฐ์ ์์ผ๋ก ์ ์ด์ฃผ์ธ์. |
@@ -0,0 +1,72 @@
+package christmas.domain;
+
+import christmas.constant.Constant;
+import java.util.EnumMap;
+import java.util.Map;
+import java.util.Map.Entry;
+
+public class Benefit {
+
+ private final Map<Event, Integer> details;
+
+ public Benefit() {
+ this.details = new EnumMap<>(Event.class);
+ initialBenefitDetails();
+ }
+
+ public int calculateTotalDiscount() {
+ return details.values()
+ .stream()
+ .reduce(0, Integer::sum);
+ }
+
+ public void addDiscountIntoDetails(Event event, int discount) {
+ details.computeIfPresent(event, (key, value) -> value + discount);
+ }
+
+ public String detailsToString() {
+ StringBuilder sb = new StringBuilder(Constant.NOTHING + System.lineSeparator());
+ if (calculateTotalDiscount() != 0) {
+ sb.setLength(0);
+ appendDetails(sb);
+ }
+ return sb.toString();
+ }
+
+ public int calculatePresentationPrice() {
+ return details.get(Event.PRESENTATION);
+ }
+
+ public String presentationMenuToString() {
+ Event presentation = Event.PRESENTATION;
+ StringBuilder sb = new StringBuilder(Constant.NOTHING + System.lineSeparator());
+ int discount = details.get(presentation);
+ if (discount != 0) {
+ sb.setLength(0);
+ sb.append(presentation.getTarget());
+ sb.append(Constant.SPACE);
+ sb.append(String.format(Constant.MENU_UNIT, Math.abs(discount / Event.PRESENTATION.getDiscount())));
+ sb.append(System.lineSeparator());
+ }
+ return sb.toString();
+ }
+
+
+ private void appendDetails(StringBuilder benefitDetail) {
+ for (Entry<Event, Integer> entry : details.entrySet()) {
+ String eventMessage = entry.getKey().getMessage();
+ int discount = entry.getValue();
+ if (discount != 0) {
+ benefitDetail.append(eventMessage);
+ benefitDetail.append(Constant.SPACE);
+ benefitDetail.append(String.format(Constant.PRICE_UNIT, discount));
+ benefitDetail.append(System.lineSeparator());
+ }
+ }
+ }
+
+ private void initialBenefitDetails() {
+ Event.getAllEvent().forEach(event -> details.put(event, 0));
+ }
+
+} | Java | StringBuilder๋ฅผ ์ธ๋ถ์์ ๋ฐ์์์ผ ํ๋ ์ด์ ๊ฐ ์์์๊น์?
์๋๋ผ๋ฉด ๋ด๋ถ์์ StringBuilder๋ฅผ ์์ฑํด์ ์ฌ์ฉํ์ธ์.
๊ผญ ์ธ๋ถ์์ StringBuilder๋ฅผ ๋ฐ์์์ผ๋ง ํ๋ ๊ฒฝ์ฐ๋ผ๋ฉด, ์ค๊ณ๊ฐ ์๋ชป๋ ๊ฑฐ์์. |
@@ -0,0 +1,106 @@
+package christmas.domain;
+
+
+import christmas.constant.Constant;
+import christmas.constant.ErrorMessage;
+import christmas.constant.MenuConstant.MenuType;
+import java.util.EnumMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+public class OrderMenu {
+
+ private final Map<Menu, Integer> details;
+
+ public OrderMenu(List<String> menus) {
+ validateMenus(menus);
+ this.details = createDetail(menus);
+ }
+
+ public String detailsToString() {
+ StringBuilder sb = new StringBuilder();
+ for (Entry<Menu, Integer> entry : details.entrySet()) {
+ sb.append(entry.getKey().getName());
+ sb.append(Constant.SPACE);
+ sb.append(String.format(Constant.MENU_UNIT, entry.getValue()));
+ sb.append(System.lineSeparator());
+ }
+ return sb.toString();
+ }
+
+ public int calculateTotalPrice() {
+ return details.entrySet()
+ .stream()
+ .mapToInt(entry -> entry.getKey().getPrice() * entry.getValue())
+ .sum();
+ }
+
+ public int countMenuByEventTarget(String eventTarget) {
+ return details.entrySet()
+ .stream()
+ .filter(entry -> entry.getKey().getType().equals(eventTarget))
+ .mapToInt(Entry::getValue)
+ .sum();
+ }
+
+ private Map<Menu, Integer> createDetail(List<String> menus) {
+ Map<Menu, Integer> detail = new EnumMap<>(Menu.class);
+ for (String menu : menus) {
+ putMenuIntoDetail(menu, detail);
+ }
+ return detail;
+ }
+
+ private void putMenuIntoDetail(String menu, Map<Menu, Integer> detail) {
+ String[] menuAndQuantity = menu.split(Constant.DELIMITER_HYPHEN);
+ detail.put(Menu.findByName(menuAndQuantity[0]), Integer.parseInt(menuAndQuantity[1]));
+ }
+
+ private void validateMenus(List<String> menus) {
+ if (isDuplicate(menus) || isNothing(menus)) {
+ throw new IllegalArgumentException(ErrorMessage.WRONG_MENU);
+ }
+ validateQuantity(menus);
+ validateOnlyBeverage(menus);
+ }
+
+ private boolean isNothing(List<String> menus) {
+ return menus.stream()
+ .map(menu -> menu.substring(0, menu.indexOf(Constant.DELIMITER_HYPHEN)))
+ .anyMatch(menu -> !Menu.isExistByName(menu));
+ }
+
+ private boolean isDuplicate(List<String> menus) {
+ return menus.stream()
+ .map(menu -> menu.substring(0, menu.indexOf(Constant.DELIMITER_HYPHEN)))
+ .distinct()
+ .count() != menus.size();
+ }
+
+ private void validateQuantity(List<String> menus) {
+ if (calculateQuantity(menus) > Constant.MENU_MAXIMUM_QUANTITY) {
+ throw new IllegalArgumentException(ErrorMessage.QUANTITY_OVER);
+ }
+ }
+
+ private int calculateQuantity(List<String> menus) {
+ return menus.stream()
+ .map(menu -> menu.split(Constant.DELIMITER_HYPHEN)[1])
+ .map(Integer::parseInt)
+ .reduce(0, Integer::sum);
+ }
+
+ private void validateOnlyBeverage(List<String> menus) {
+ if (isOnlyBeverage(menus)) {
+ throw new IllegalArgumentException(ErrorMessage.ONLY_DRINK);
+ }
+ }
+
+ private boolean isOnlyBeverage(List<String> menus) {
+ return menus.stream()
+ .map(menu -> menu.substring(0, menu.indexOf(Constant.DELIMITER_HYPHEN)))
+ .allMatch(menu -> Menu.findByName(menu).getType().equals(MenuType.DRINK));
+ }
+
+} | Java | ๋ฑํ ์ค์ํ ๋ถ๋ถ์ ์๋๋ฐ, ์๋ก ์ฐ๊ด๋ ๋ฉ์๋๋ผ๋ฆฌ ๊ฐ๊น์ด ๋ถ์ด ์๋๋ก ์ฝ๋๋ฅผ ์ ๋ฆฌํด์ฃผ๋ ๊ฒ ์ข์์.
๋ฉ์๋ ์์๊ฐ ๊ผฌ์ฌ ์์ผ๋ฉด ๋ฆฌ๋ทฐํ๋ ์
์ฅ์์ ๊ฝค ํ๋ค์ด์. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.