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) ์˜์ƒ์„ ํ†ตํ•ด ๊ณต๋ถ€ํ•ด๋ณด์‹œ๋ฉด ์กฐ๊ธˆ ๋” ์ดํ•ด๊ฐ€ ์‰ฌ์šฐ์‹ค ๊ฒƒ ๊ฐ™์•„์š” ๐Ÿ”ฅ ![1_0u-ekVHFu7Om7Z-VTwFHvg](https://user-images.githubusercontent.com/17218212/185444984-fd35acf7-3f97-47e7-be29-ed00ac40509b.png)
@@ -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
๊ณต๊ฐ„๊ณผ ๊ด€๋ จ๋œ ์•Œ๊ณ ๋ฆฌ์ฆ˜์— ํ…Œ์ŠคํŠธ๋ฅผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๋‚˜์ค‘์— ์ž์‹ ์ด ๋ณด๊ฑฐ๋‚˜ ๋‹ค๋ฅธ ๊ฐœ๋ฐœ์ž๊ฐ€ ์ด ํ…Œ์ŠคํŠธ ์ฝ๊ณ  ํŒŒ์•…ํ•˜๊ธฐ๊ฐ€ ํž˜๋“ค ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ![image](https://user-images.githubusercontent.com/34268173/184039651-2c8a60f0-3d6f-4c37-9e62-c3c0ecedc02a.png) ์ด๋ฒˆ ๋‹จ๊ณ„ ์˜ˆ์‹œ์— ์žˆ๋˜ ๊ฒƒ ์ฒ˜๋Ÿผ ์ฃผ์„์œผ๋กœ ํ”ฝ์Šค์ณ๋ฅผ ์„ค๋ช…ํ•ด์ฃผ๋ฉด ๋‚˜์ค‘์— ๋‹ค์‹œ ๋ณด์•˜์„ ๋•Œ๋„ ์‰ฝ๊ฒŒ ํ…Œ์ŠคํŠธ๋ฅผ ํŒŒ์•…ํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค :)
@@ -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
์ถ”๊ฐ€์ ์œผ๋กœ ์˜ˆ์™ธ ์ƒํ™ฉ์— ๋Œ€ํ•ด์„œ ํ…Œ์ŠคํŠธ๋ฅผ ํ•ด์ฃผ์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ![image](https://user-images.githubusercontent.com/34268173/184040674-834af3fb-ce97-41eb-84d9-7a723ebbf570.png) ๋Œ€์‹ ์— ์ง€๊ธˆ๊ณผ ๊ฐ™์ด 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
๋”ฑํžˆ ์ค‘์š”ํ•œ ๋ถ€๋ถ„์€ ์•„๋‹Œ๋ฐ, ์„œ๋กœ ์—ฐ๊ด€๋œ ๋ฉ”์†Œ๋“œ๋ผ๋ฆฌ ๊ฐ€๊นŒ์ด ๋ถ™์–ด ์žˆ๋„๋ก ์ฝ”๋“œ๋ฅผ ์ •๋ฆฌํ•ด์ฃผ๋Š” ๊ฒŒ ์ข‹์•„์š”. ๋ฉ”์†Œ๋“œ ์ˆœ์„œ๊ฐ€ ๊ผฌ์—ฌ ์žˆ์œผ๋ฉด ๋ฆฌ๋ทฐํ•˜๋Š” ์ž…์žฅ์—์„œ ๊ฝค ํž˜๋“ค์–ด์š”.