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

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

๋์ ์ ์ง๊ธ๊ณผ ๊ฐ์ด service layer์ ๋น์ฆ๋์ค ๋ก์ง์ด ๋ค์ด๊ฐ๊ฒ ๋๋ฉด ํ
์คํธ ํด๋ด์ ์์๊ฒ ์ง๋ง
service์์ ํ์ํ (test double์ด๋ ์ค์ ๊ฐ์ฒด๋ )์์กด์ฑ์ด ๊ฐ์ถฐ์ง ์ํ์์ ํ
์คํธ๋ฅผ ํด์ผํ๋ ํ
์คํธ ์์ฑ์ด ๋ฒ๊ฑฐ๋กญ๊ฑฐ๋ ๊น๋ค๋ก์์ง๋๋ฐ์.
์ฒซ๋ฒ์งธ ๋จ๊ณ์ ์๊ตฌ์ฌํญ์ ํตํด ๊ฒฝํํ์
จ๋ฏ, `๊ธธ ์ฐพ๊ธฐ`์ ๋ํ `๋๋ฉ์ธ ๊ฐ์ฒด`๋ฅผ ๋ง๋ค์ด์ ๋จ์ ํ
์คํธ๋ฅผ ํด๋ณด์๋๊ฑด ์ด๋จ๊น์? :) |
@@ -0,0 +1,39 @@
+package nextstep.subway.unit;
+
+import nextstep.subway.applicaion.LineService;
+import nextstep.subway.applicaion.PathService;
+import nextstep.subway.applicaion.StationService;
+import nextstep.subway.domain.Station;
+import nextstep.subway.utils.TestObjectFactory;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+@ExtendWith(MockitoExtension.class)
+public class PathServiceMockTest {
+
+ @Mock
+ LineService lineService;
+
+ @Mock
+ StationService stationService;
+
+ @InjectMocks
+ PathService pathService;
+
+ TestObjectFactory testObjectFactory = new TestObjectFactory();
+
+ @Test
+ @DisplayName("์คํจ_์ถ๋ฐ์ญ๊ณผ ๋์ฐฉ์ญ์ด ๊ฐ์ ๊ฒฝ์ฐ")
+ void fail_same_start_end() {
+ Station ๊ฐ๋จ์ญ = testObjectFactory.์ญ์์ฑ("๊ฐ๋จ์ญ");
+ Station ์์ฌ์ญ = testObjectFactory.์ญ์์ฑ("์์ฌ์ญ");
+
+ assertThrows(IllegalArgumentException.class, () -> pathService.getPath(๊ฐ๋จ์ญ.getId(), ์์ฌ์ญ.getId()));
+ }
+} | Java | ํด๋น ๋ฆฌ๋ทฐ๋ฅผ ๋ฐ์ํ๋ฉด์
`์ถ๋ฐ์ญ๊ณผ ๋์ฐฉ์ญ์ด ์ฐ๊ฒฐ์ด ๋์ด ์์ง ์์ ๊ฒฝ์ฐ` ์ ๋ํด pathService ์๋น์ค ๋ ์ด์ด mock ํ
์คํธ๋ฅผ ์ง๋๋ฐ,
์ด๋ฅผ pathService์์ ํ
์คํธํ๋ ค๋ stationService๋ฅผ ๋ชฉ์ฒ๋ฆฌํด๋ฌ์, ํ
์คํธ๋ฅผ ์ง๋ ค๋ฉด stationService.findById์์ ์๋ฌ๋ฅผ ๋์ง๋๋ก ๋ชฉ ํ
์คํธ๋ฅผ ์งํํด์ผ ํ์ต๋๋ค. ํ์ง๋ง, ์ด๋ ์ฝ๋์ ๋ํ ํ
์คํธ๋ฅผ ์ง๊ธฐ๋ณด๋ค๋ ํ
์คํธ๋ฅผ ์ํ ํ
์คํธ๋ผ๋ ์๊ฐ์ด ๋ค์ด์ ๊ฒฐ๊ตญ ์ด ๊ฒฝ์ฐ๋ ์ค์ ๊ฐ์ฒด ํ
์คํธ์์ ์งํํด์ผ ํ๋๋ฐ์.
์ด์ ๊ฐ์ ๊ฒฝ์ฐ๋ ์ ๊ฐ ํ ๊ฒ์ฒ๋ผ mockํ
์คํธ๋ฅผ ํผํ๋๊ฒ ๋ง๋ ๊ฒ์ธ์ง? ์๋๋ฉด ๋ค๋ฅธ ๋ฐฉ๋ฒ์ด ์๋์ง ๊ถ๊ธํฉ๋๋ค! |
@@ -0,0 +1,39 @@
+package nextstep.subway.unit;
+
+import nextstep.subway.applicaion.LineService;
+import nextstep.subway.applicaion.PathService;
+import nextstep.subway.applicaion.StationService;
+import nextstep.subway.domain.Station;
+import nextstep.subway.utils.TestObjectFactory;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+@ExtendWith(MockitoExtension.class)
+public class PathServiceMockTest {
+
+ @Mock
+ LineService lineService;
+
+ @Mock
+ StationService stationService;
+
+ @InjectMocks
+ PathService pathService;
+
+ TestObjectFactory testObjectFactory = new TestObjectFactory();
+
+ @Test
+ @DisplayName("์คํจ_์ถ๋ฐ์ญ๊ณผ ๋์ฐฉ์ญ์ด ๊ฐ์ ๊ฒฝ์ฐ")
+ void fail_same_start_end() {
+ Station ๊ฐ๋จ์ญ = testObjectFactory.์ญ์์ฑ("๊ฐ๋จ์ญ");
+ Station ์์ฌ์ญ = testObjectFactory.์ญ์์ฑ("์์ฌ์ญ");
+
+ assertThrows(IllegalArgumentException.class, () -> pathService.getPath(๊ฐ๋จ์ญ.getId(), ์์ฌ์ญ.getId()));
+ }
+} | Java | @sang-eun
๋ค๋ค mock์ ์ฌ์ฉํ ํ
์คํ
์ ๊ฒฝ์ฐ ์์กดํ๋ ๊ฐ์ฒด๋ฅผ ๋งค๋ฒ ์ค์ ์ ํ๋ ๊ฒ์ด ๋งค์ฐ ๋ฒ๊ฑฐ๋กญ์ฃ ...!
๊ทธ๋์ ์ฒซ๋ฒ์งธ ๋จ๊ณ์์ ์๊ธฐ๋๋ ธ๋ฏ์ด ์ ๋ fake ๊ฐ์ฒด๋ฅผ ์ฌ์ฉํ๋ ๊ฑธ ์ ํธํ๋ ํธ์
๋๋ค!
์ง๊ธ๊ณผ ๊ฐ์ ๊ฒฝ์ฐ ๊ธธ์ ์ฐพ๋ ์ญํ ์ ๊ฐ๋ ๊ฐ์ฒด๋ฅผ ๋ฐ๋ก ๋ง๋ ๋ค๋ฉด ์ข ๋ ๊ฐ๋ฒผ์ด ํ
์คํ
์ด ๊ฐ๋ฅํ ๊ฒ ๊ฐ์ต๋๋ค!
(์ด๋ฏธ `Path` ๊ฐ์ฒด์์ ์ฒ๋ฆฌํ๋๋ก ํ์
จ๋ค์ ๐ ) |
@@ -0,0 +1,32 @@
+package nextstep.subway.exception;
+
+import nextstep.subway.auth.application.AuthorizationException;
+import org.springframework.dao.DataIntegrityViolationException;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.RestControllerAdvice;
+
+@RestControllerAdvice
+public class GlobalExceptionAdvisor {
+
+ @ExceptionHandler({IllegalArgumentException.class})
+ public ResponseEntity handleIllegalArgsException(Exception e) {
+ return ResponseEntity.badRequest().build();
+ }
+
+ @ExceptionHandler({RuntimeException.class})
+ public ResponseEntity handleRuntimeException(Exception e) {
+ return ResponseEntity.badRequest().build();
+ }
+
+ @ExceptionHandler(AuthorizationException.class)
+ public ResponseEntity handleAuthorizationException(Exception e) {
+ return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
+ }
+
+ @ExceptionHandler(DataIntegrityViolationException.class)
+ public ResponseEntity handleIllegalArgsException(DataIntegrityViolationException e) {
+ return ResponseEntity.badRequest().build();
+ }
+} | Java | ๊ณตํต ์์ธ ์ฒ๋ฆฌ ์ข์ต๋๋ค. ๐ |
@@ -0,0 +1,50 @@
+package nextstep.subway.fare.domain;
+
+import java.util.Arrays;
+
+public enum DiscountPolicy {
+ ADULT(19, 500, 0, 0),
+ TEENAGER(13, 19, 350, 0.2),
+ CHILD(6, 13, 350, 0.5),
+ INFANT(0, 6, 0, 1);
+
+ private int ageStart;
+ private final int ageEnd;
+ private final int minusFare;
+ private final double discountRatio;
+
+ DiscountPolicy(int ageStart, int ageEnd, int minusFare, double discountRatio) {
+
+ this.ageStart = ageStart;
+ this.ageEnd = ageEnd;
+ this.minusFare = minusFare;
+ this.discountRatio = discountRatio;
+ }
+
+ public int getDiscount(int fare) {
+ if (fare < 0) {
+ throw new IllegalArgumentException();
+ }
+ double discounted = (fare - this.minusFare) * (1 - this.discountRatio);
+ return (int) discounted;
+ }
+
+ public static DiscountPolicy getPolicy(int age) {
+ return Arrays.stream(values()).filter(
+ policy -> policy.isMatch(age)
+ ).findFirst()
+ .orElseThrow(IllegalArgumentException::new);
+ }
+
+ public int getAgeStart() {
+ return ageStart;
+ }
+
+ public int getAgeEnd() {
+ return ageEnd;
+ }
+
+ public boolean isMatch(int age) {
+ return getAgeStart() <= age && age < getAgeEnd();
+ }
+} | Java | ๋์ด์ ๋ฐ๋ฅธ ํ ์ธ ์๊ธ ๊ณ์ฐ ๋ก์ง ์ ๊ตฌํํด์ฃผ์
จ์ต๋๋ค. ๐
`ageStart`, `ageEnd`๋ ์ถฉ๋ถํ ๋ฌด์จ ์ญํ ์ ํ๋์ง ์ ์ ์๋ ์ด๋ฆ์ธ๋ฐ, ๋น๊ต์ ์ฌ์ฉ๋๋๊น ์ด์/์ด๊ณผ, ์ดํ/๋ฏธ๋ง ๊ตฌ๋ถ์ ์ํด `ageMinInclusive`, ageMaxExclusive`์ ๊ฐ์ด ์์ ํด๋ณด์
๋ ์ข๊ฒ ์ต๋๋ค. |
@@ -0,0 +1,50 @@
+package nextstep.subway.fare.domain;
+
+import java.util.Arrays;
+
+public enum DiscountPolicy {
+ ADULT(19, 500, 0, 0),
+ TEENAGER(13, 19, 350, 0.2),
+ CHILD(6, 13, 350, 0.5),
+ INFANT(0, 6, 0, 1);
+
+ private int ageStart;
+ private final int ageEnd;
+ private final int minusFare;
+ private final double discountRatio;
+
+ DiscountPolicy(int ageStart, int ageEnd, int minusFare, double discountRatio) {
+
+ this.ageStart = ageStart;
+ this.ageEnd = ageEnd;
+ this.minusFare = minusFare;
+ this.discountRatio = discountRatio;
+ }
+
+ public int getDiscount(int fare) {
+ if (fare < 0) {
+ throw new IllegalArgumentException();
+ }
+ double discounted = (fare - this.minusFare) * (1 - this.discountRatio);
+ return (int) discounted;
+ }
+
+ public static DiscountPolicy getPolicy(int age) {
+ return Arrays.stream(values()).filter(
+ policy -> policy.isMatch(age)
+ ).findFirst()
+ .orElseThrow(IllegalArgumentException::new);
+ }
+
+ public int getAgeStart() {
+ return ageStart;
+ }
+
+ public int getAgeEnd() {
+ return ageEnd;
+ }
+
+ public boolean isMatch(int age) {
+ return getAgeStart() <= age && age < getAgeEnd();
+ }
+} | Java | ์์ธ๋ฅผ ๋ฐ์์ํฌ ๋ ์์ธ ๋ด์ฉ, ๋๋ฒ๊น
์ ํ์ํ ๊ฐ์ ๋ฉ์์ง๋ก ํจ๊ป ์ ๋ฌํ์๋ฉด, ๋ฌธ์ ์ํฉ์์ ์์ธ ์ถ์ ์ด ์์ํด์ ์ข์ต๋๋ค. :) |
@@ -0,0 +1,42 @@
+package nextstep.subway.fare.domain;
+
+import java.util.Arrays;
+
+public enum DistanceExtraFare {
+ NEAR(10, 50, 100, 5),
+ FAR(50, 500, 100, 8);
+
+ private final int distanceStart;
+ private final int distanceEnd;
+ private final int fare;
+ private final int unitDistanceInKiloMeter;
+
+ DistanceExtraFare(int distanceStart, int distanceEnd, int fare, int unitDistanceInKiloMeter) {
+
+ this.distanceStart = distanceStart;
+ this.distanceEnd = distanceEnd;
+ this.fare = fare;
+ this.unitDistanceInKiloMeter = unitDistanceInKiloMeter;
+ }
+
+ public static int calculate(int distance) {
+ return Arrays.stream(values())
+ .map(distanceExtraFare -> distanceExtraFare.calculateBy(distance))
+ .reduce(Integer::sum)
+ .orElse(0);
+ }
+
+ private int calculateBy(int distance) {
+ if (distance <= this.distanceStart) {
+ return 0;
+ }
+ if (distance > this.distanceEnd) {
+ distance = this.distanceEnd;
+ }
+ return ((distance - this.distanceStart) / this.unitDistanceInKiloMeter) * this.fare;
+ }
+
+ public int getFare() {
+ return this.fare;
+ }
+} | Java | 16km๋ฅผ ๊ฐ๋ ๊ฒฝ์ฐ ์ถ๊ฐ ์๊ธ์ ((16 - 10) / 5) * 100 = 100์์ด ๋ ๊ฒ ๊ฐ์์!
์ฐธ๊ณ ๋งํฌ์ ์๋ ๊ฐ๊ณผ ๊ฒฐ๊ณผ๊ฐ ๋ค๋ฅธ ๊ฒ ๊ฐ์ต๋๋ค.
> http://www.seoulmetro.co.kr/kr/page.do?menuIdx=354
๋ฏธ์
ํ์ด์ง์ ์๋ ์์ ์ฌ์ฉํด์ ์ถ๊ฐ ์๊ธ์ ๊ณ์ฐํด๋ณด์๋ฉด ์ข๊ฒ ์ต๋๋ค. :)
> https://edu.nextstep.camp/s/urD8knTu/ls/4r6iyUcO |
@@ -0,0 +1,44 @@
+package nextstep.subway.fare.domain;
+
+import java.util.Objects;
+
+public class Fare {
+ private static final int basicFare = 1250;
+
+ private int fare;
+ private final DiscountPolicy discountPolicy;
+
+ private Fare(int fare, DiscountPolicy discountPolicy) {
+ this.fare = fare;
+ this.discountPolicy = discountPolicy;
+ }
+
+ public static Fare of(DiscountPolicy discountPolicy) {
+ return new Fare(Fare.basicFare, discountPolicy);
+ }
+
+ public static Fare of(int fare, DiscountPolicy discountPolicy) {
+ return new Fare(fare, discountPolicy);
+ }
+
+ public Fare plus(int fare) {
+ return Fare.of(this.fare + fare, this.discountPolicy);
+ }
+
+ public int discount() {
+ return this.discountPolicy.getDiscount(this.fare);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Fare fare1 = (Fare) o;
+ return fare == fare1.fare && discountPolicy == fare1.discountPolicy;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(fare, discountPolicy);
+ }
+} | Java | ๊ฐ ๊ฐ์ฒด ์ฌ์ฉ ์ข์ต๋๋ค. ๐
๊ณ ๋ฏผํด๋ณด์๋ฉด ์ข์ ๊ฒ ๊ฐ์ ๋ถ๋ถ์, `Fare` ํด๋์ค๋ฅผ ์ฌ์ฉํ๋ ์ฌ๋์ด `plus`, `discount` ์์๋ฅผ ์ ์๊ณ ํธ์ถํด์ผ ์๊ธ ๊ณ์ฐ์ด ์ ์์ ์ผ๋ก ๋ ๊ฒ ๊ฐ์์. ๊ทธ๋ฆฌ๊ณ , ํ ์ธ ์ ์ฑ
์ ์์ฑํ๋ ์์ ์ ๋ฐ์ง๋ง, ์ค์ ๋ก๋ ์ถ๊ฐ ์๊ธ ๊ณ์ฐ์ด ๋๋ ํ ์ฌ์ฉ์ด ๋์ด์ผ ํ๋ค์.
์๊ธ ๊ณ์ฐ์ `FareCalculator`๊ฐ ๋ด๋นํ๋ ๊ฒ์ผ๋ก ๋ณด์ด๋, `DiscountPolicy`๋ฅผ ์๊ธ ๊ณ์ฐ ๋ฉ์๋์์ ๊ด๋ฆฌํด๋ณด์
๋ ์ข๊ฒ ์ต๋๋ค. :) |
@@ -17,12 +17,11 @@
import java.util.stream.Collectors;
@Service
-@Transactional(readOnly = true)
+@Transactional
public class FavoriteService {
private final String MESSAGE_FAVORITE_ENTITY_NOT_FOUND = "์ฆ๊ฒจ์ฐพ๊ธฐ๊ฐ๊ฐ ์กด์ฌํ์ง ์์ต๋๋ค";
-
private FavoriteRepository favoriteRepository;
private MemberService memberService;
private StationService stationService;
@@ -42,7 +41,7 @@ public FavoriteResponse saveFavorite(Long memberId, FavoriteRequest favoriteRequ
Long sourceStationId = favoriteRequest.getSourceId();
Long targetStationId = favoriteRequest.getTargetId();
- checkSourceTargetHasPath(sourceStationId, targetStationId);
+ checkSourceTargetHasPath(memberId, sourceStationId, targetStationId);
Favorite favorite = saveFavoriteEntity(memberId, sourceStationId, targetStationId);
return FavoriteResponse.of(favorite);
@@ -55,10 +54,11 @@ private Favorite saveFavoriteEntity(Long memberId, Long sourceStationId, Long ta
return favoriteRepository.save(new Favorite(member, sourceStation, targetStation));
}
- private void checkSourceTargetHasPath(Long sourceStationId, Long targetStationId) {
- pathService.findShortestPath(sourceStationId, targetStationId);
+ private void checkSourceTargetHasPath(Long memberId, Long sourceStationId, Long targetStationId) {
+ pathService.findShortestPath(memberId, sourceStationId, targetStationId);
}
+ @Transactional(readOnly = true)
public List<FavoriteResponse> findFavorites(Long memberId) {
Member member = findMember(memberId);
List<Favorite> favorites = favoriteRepository.findByMemberId(member.getId()); | Java | ์ต๋จ ๊ฒฝ๋ก๋ฅผ ์กฐํํ๋ ๋ฉ์๋๊ฐ ์๊ธ ๊ณ์ฐ๋ ํ๊ธฐ ๋๋ฌธ์ `memberId`๊ฐ ํ์ํ๊ฒ ๋ ๊ฑธ๊น์?
๊ฒฝ๋ก ์กฐํ์ ์๊ธ ๊ณ์ฐ์ ๋ถ๋ฆฌํด๋ด๋ ์ข์ ๊ฒ ๊ฐ๋ค์! :) |
@@ -1,14 +1,16 @@
package nextstep.subway.path.application;
import nextstep.subway.line.domain.Section;
+import nextstep.subway.path.domain.SectionEdge;
+import nextstep.subway.path.domain.ShortestPath;
import nextstep.subway.station.domain.Station;
-import org.jgrapht.graph.DefaultWeightedEdge;
+import org.jgrapht.GraphPath;
import org.jgrapht.graph.WeightedMultigraph;
import java.util.List;
public class PathFinder {
- private final WeightedMultigraph<Station, DefaultWeightedEdge> graph;
+ private final WeightedMultigraph<Station, SectionEdge> graph;
private PathFindAlgorithm algorithm;
private PathFinder(List<Section> allSections, PathFindAlgorithm algorithm) {
@@ -17,13 +19,13 @@ private PathFinder(List<Section> allSections, PathFindAlgorithm algorithm) {
}
- private WeightedMultigraph<Station, DefaultWeightedEdge> makeGraph(final List<Section> allSections) {
- WeightedMultigraph<Station, DefaultWeightedEdge> graph = new WeightedMultigraph<>(DefaultWeightedEdge.class);
+ private WeightedMultigraph<Station, SectionEdge> makeGraph(final List<Section> allSections) {
+ WeightedMultigraph<Station, SectionEdge> graph = new WeightedMultigraph<>(SectionEdge.class);
allSections.forEach(
section -> {
graph.addVertex(section.getUpStation());
graph.addVertex(section.getDownStation());
- graph.setEdgeWeight(graph.addEdge(section.getUpStation(), section.getDownStation()), section.getDistance());
+ graph.addEdge(section.getUpStation(), section.getDownStation(), SectionEdge.of(section));
}
);
return graph;
@@ -34,6 +36,11 @@ public static PathFinder of(List<Section> allSections, PathFindAlgorithm algorit
}
public List<Station> find(Station departStation, Station destStation) {
- return algorithm.findShortestPath(graph, departStation, destStation);
+ return algorithm.findShortestPathStations(graph, departStation, destStation);
+ }
+
+ public ShortestPath getShortestGraph(Station departStation, Station destStation) {
+ GraphPath<Station, SectionEdge> shortestPathGraph = algorithm.getShortestPathGraph(graph, departStation, destStation);
+ return ShortestPath.of(shortestPathGraph);
}
} | Java | ์ฌ์ฉ์ฒ๊ฐ ์์ด์ง ๊ฒ ๊ฐ์ผ๋, ์ด ๋ฉ์๋๋ฅผ ํฌํจํด `PathFindAlgorithm`์ `findShortestPathStations`๋ฅผ ์ญ์ ํ์๋ฉด ์ข๊ฒ ์ต๋๋ค. :) |
@@ -1,8 +1,12 @@
package nextstep.subway.path.application;
+import nextstep.subway.fare.domain.FareCalculator;
import nextstep.subway.line.domain.Section;
import nextstep.subway.line.domain.SectionRepository;
import nextstep.subway.line.dto.PathResponse;
+import nextstep.subway.member.application.MemberService;
+import nextstep.subway.member.domain.Member;
+import nextstep.subway.path.domain.ShortestPath;
import nextstep.subway.station.application.StationService;
import nextstep.subway.station.domain.Station;
import org.springframework.stereotype.Service;
@@ -20,22 +24,30 @@ public class PathService {
private final StationService stationService;
private final SectionRepository sectionRepository;
-
private final PathFindAlgorithm pathFinder;
+ private final MemberService memberService;
- public PathService(StationService stationService, SectionRepository sectionRepository, PathFindAlgorithm pathFinder) {
+ public PathService(StationService stationService, SectionRepository sectionRepository, PathFindAlgorithm pathFinder,
+ MemberService memberService) {
this.stationService = stationService;
this.sectionRepository = sectionRepository;
this.pathFinder = pathFinder;
+ this.memberService = memberService;
}
- public PathResponse findShortestPath(Long source, Long target) {
+ public PathResponse findShortestPath(Long loginId, Long source, Long target) {
validateInput(source, target);
Station departStation = stationService.findStationById(source);
Station destStation = stationService.findStationById(target);
List<Section> allSections = sectionRepository.findAll();
- return PathResponse.from(PathFinder.of(allSections, pathFinder).find(departStation, destStation));
+ ShortestPath shortestGraph = PathFinder.of(allSections, this.pathFinder)
+ .getShortestGraph(departStation, destStation);
+
+ Member memberEntity = memberService.findMemberEntity(loginId);
+ int fare = FareCalculator.calculate(shortestGraph.getPathDistance(),
+ shortestGraph.getMaxLineFare(), memberEntity.getAge());
+ return PathResponse.from(shortestGraph, fare);
}
private static void validateInput(Long sourceStationId, Long targetStationId) {
@@ -46,5 +58,4 @@ private static void validateInput(Long sourceStationId, Long targetStationId) {
throw new IllegalArgumentException(MESSAGE_SOURCE_TARGET_SHOULD_BE_DIFFERENT);
}
}
-
} | Java | ๊ฒฝ๋ก ๊ณ์ฐํ๋ ๋ถ๋ถ๊ณผ ์๊ธ ๊ณ์ฐํ๋ ๋ก์ง์ ์ ๋ถ๋ฆฌํ ์ ์๊ฒ ๊ตฌํํ์ ๊ฒ์ผ๋ก ๋ณด์ฌ์.
์ค์ ๋ก ๋ด๋นํ๋ ํด๋์ค๋ฅผ ๋๋ ๋ณด๋ฉด ์ด๋จ๊น์? `FavoriteService` ์์๋ ๊ฒฝ๋ก๊ฐ ์กด์ฌํ๋์ง๋ง ํ์ธํ๋ฉด ๋๋ ์ฌ์ฌ์ฉ๋ ์ข ๋ ํจ์จ์ ์ผ๋ก ํ ์ ์์ ๊ฒ ๊ฐ๋ค์! |
@@ -1,14 +1,13 @@
package nextstep.subway.path.ui;
+import nextstep.subway.auth.domain.AuthenticationPrincipal;
+import nextstep.subway.auth.domain.LoginMember;
import nextstep.subway.line.dto.PathResponse;
-import nextstep.subway.member.dto.MemberRequest;
-import nextstep.subway.member.dto.MemberResponse;
import nextstep.subway.path.application.PathService;
import org.springframework.http.ResponseEntity;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.*;
-
-import java.net.URI;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
@RestController
public class PathController {
@@ -20,18 +19,10 @@ public PathController(PathService service) {
@GetMapping("/paths")
public ResponseEntity<PathResponse> findShortestPath(
- @RequestParam("source") Long source,
- @RequestParam("target") Long target) {
- PathResponse response = service.findShortestPath(source, target);
+ @AuthenticationPrincipal LoginMember loginMember,
+ @RequestParam("source") Long source,
+ @RequestParam("target") Long target) {
+ PathResponse response = service.findShortestPath(loginMember.getId(), source, target);
return ResponseEntity.ok(response);
}
-
- @ExceptionHandler({IllegalArgumentException.class})
- public ResponseEntity handleIllegalArgsException(Exception e) {
- return ResponseEntity.badRequest().build();
- }
- @ExceptionHandler({RuntimeException.class})
- public ResponseEntity handleRuntimeException(Exception e) {
- return ResponseEntity.badRequest().build();
- }
} | Java | ๋ก๊ทธ์ธํ์ง ์์ ๊ฒฝ์ฐ์๋ ๊ฒฝ๋ก๋ฅผ ์กฐํํ ์ ์์ด์ผ ํ ๊ฒ ๊ฐ์์.
์ด๋ฅผ ์ํด AuthenticationPrincipal์ ์ธ์ฆ์ด ํ์ํ์ง ์ฌ๋ถ ํ๋๋ฅผ ์ถ๊ฐํ๊ณ , ์ด๋ฅผ ํตํด ์ธ์ฆ์ ํ์ง ์์ ํ์๋ ์ฌ์ฉํ ์ ์๋ ๊ธฐ๋ฅ(๊ฒฝ๋ก ์กฐํ ๋ฑ)๊ณผ ์ธ์ฆ์ ํด์ผ๋ง ์ฌ์ฉํ ์ ์๋ ๊ธฐ๋ฅ(ํ์ ์ ๋ณด ๋ณ๊ฒฝ ๋ฑ)์์ ๋ชจ๋ LoginMember๋ฅผ ์ด์ฉํ ์ ์๋๋ก ๊ด๋ฆฌํด๋ณด์๋ฉด ์ข๊ฒ ์ต๋๋ค.
> https://edu.nextstep.camp/s/urD8knTu/ls/4r6iyUcO
"/paths ์์ฒญ ์ LoginMember ๊ฐ์ฒด ์ฒ๋ฆฌ" ๋ถ๋ถ์ ์ฐธ๊ณ ๋ถํ๋๋ฆฝ๋๋ค. |
@@ -0,0 +1,49 @@
+package lotto.domain;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+public class LottoGame {
+ private static final int TICKET_PRICE = 1000;
+
+ List<LottoTicket> lottoTickets;
+ LottoMatch lottoMatch;
+
+ public LottoGame() {
+ this.lottoTickets = new ArrayList<>();
+ }
+
+ public List<LottoTicket> buyLottoTicket(int money) {
+ int ticketNum = money / TICKET_PRICE;
+
+ for (int i = 0; i < ticketNum; i++) {
+ this.lottoTickets.add(new LottoTicket());
+ }
+
+ return this.lottoTickets;
+ }
+
+ public HashMap<LottoMatchNumber, Integer> winLotto() {
+ return this.lottoMatch.matchResult(lottoTickets);
+ }
+
+ public void inputTargetNumbers(String input) {
+ lottoMatch = new LottoMatch(input);
+ }
+
+
+ public double checkIncome(HashMap<LottoMatchNumber, Integer> results, int money){
+ double income = 0;
+
+ int totalIncome = 0;
+ for (LottoMatchNumber lottoMatchNumber : LottoMatchNumber.values()) {
+ totalIncome += lottoMatchNumber.totalPrizeMoney(results.get(lottoMatchNumber));
+ }
+
+ income = (double) totalIncome/money;
+
+ return income;
+ }
+
+} | Java | ์ ๊ทผ ์ ํ์๋ฅผ ๋ถ์ด๋๊ฒ ์ข์ ๊ฒ ๊ฐ๋ค์. |
@@ -0,0 +1,28 @@
+package lotto.domain;
+
+import stringcalculator.Operation;
+
+public enum LottoMatchNumber {
+ MATCH3(3, 5000) {int totalPrizeMoney(int count) {return prizeMoney * count;}},
+ MATCH4(4, 50000) {int totalPrizeMoney(int count) {return prizeMoney * count;}},
+ MATCH5(5, 1500000) {int totalPrizeMoney(int count) {return prizeMoney * count;}},
+ MATCH6(6, 2000000000) {int totalPrizeMoney(int count) {return prizeMoney * count;}};
+
+ private final int matchNumber;
+ protected final int prizeMoney;
+ abstract int totalPrizeMoney(int count);
+
+ LottoMatchNumber(int matchNumber, int prizeMoney) {
+ this.matchNumber = matchNumber;
+ this.prizeMoney = prizeMoney;
+ }
+
+ public int getMatchNumber() {
+ return matchNumber;
+ }
+
+ @Override
+ public String toString() {
+ return matchNumber + "๊ฐ ์ผ์น (" + prizeMoney + "์)";
+ }
+} | Java | enum๋ ๋น์ฆ๋์ค ๋ก์ง์ ์ผ๋ถ์ด๋ฏ๋ก view ๋ถ๋ถ์ ๊ตฌํ์ enum์ ๋๋๊ฑด ์ข์ง ์์ ๊ฒ ๊ฐ์์. |
@@ -0,0 +1,28 @@
+package lotto.domain;
+
+import stringcalculator.Operation;
+
+public enum LottoMatchNumber {
+ MATCH3(3, 5000) {int totalPrizeMoney(int count) {return prizeMoney * count;}},
+ MATCH4(4, 50000) {int totalPrizeMoney(int count) {return prizeMoney * count;}},
+ MATCH5(5, 1500000) {int totalPrizeMoney(int count) {return prizeMoney * count;}},
+ MATCH6(6, 2000000000) {int totalPrizeMoney(int count) {return prizeMoney * count;}};
+
+ private final int matchNumber;
+ protected final int prizeMoney;
+ abstract int totalPrizeMoney(int count);
+
+ LottoMatchNumber(int matchNumber, int prizeMoney) {
+ this.matchNumber = matchNumber;
+ this.prizeMoney = prizeMoney;
+ }
+
+ public int getMatchNumber() {
+ return matchNumber;
+ }
+
+ @Override
+ public String toString() {
+ return matchNumber + "๊ฐ ์ผ์น (" + prizeMoney + "์)";
+ }
+} | Java | ๋ฑ์๋ณ๋ก ๋ชจ๋ ๋์ผํ ๊ตฌํ์ฒด๋ฅผ ๊ฐ์ง ๊ฒ ๊ฐ์๋ฐ์. ์ถ์ ๋ฉ์๋๋ก ์ ์๋ ํ์๊ฐ ์๋์ง ๊ณ ๋ฏผ์ด ํ์ํด๋ณด์ฌ์.
๊ทธ๋ฆฌ๊ณ ํ์ฌ ๋ก๋ ๋๋ฉ์ธ์์ enum์ด ๋ก๋์ ๋ฑ์๋ณ ๊ฐ์ ๋ฐ ๋น์ฒจ ๊ธ์ก์ ๋ํ๋ด๋ ์ญํ ์ ํ๊ณ ์์ต๋๋ค. ๊ณ ์ ๋ ์์๋ค๋ง ๊ฐ์ง๋๊ฒ ์๋๋ผ ๋ฐ์ ๊ฐ์๋งํผ ๊ณฑํด์ ๊ณ์ฐํด์ฃผ๋ ์ญํ ์ ๊ฐ์ง๋๊ฒ ์ ์ ํ ์ง๋ ๊ณ ๋ฏผํด๋ณด์๋ฉด ์ข๊ฒ ๋ค์. |
@@ -0,0 +1,49 @@
+package lotto.domain;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+public class LottoGame {
+ private static final int TICKET_PRICE = 1000;
+
+ List<LottoTicket> lottoTickets;
+ LottoMatch lottoMatch;
+
+ public LottoGame() {
+ this.lottoTickets = new ArrayList<>();
+ }
+
+ public List<LottoTicket> buyLottoTicket(int money) {
+ int ticketNum = money / TICKET_PRICE;
+
+ for (int i = 0; i < ticketNum; i++) {
+ this.lottoTickets.add(new LottoTicket());
+ }
+
+ return this.lottoTickets;
+ }
+
+ public HashMap<LottoMatchNumber, Integer> winLotto() {
+ return this.lottoMatch.matchResult(lottoTickets);
+ }
+
+ public void inputTargetNumbers(String input) {
+ lottoMatch = new LottoMatch(input);
+ }
+
+
+ public double checkIncome(HashMap<LottoMatchNumber, Integer> results, int money){
+ double income = 0;
+
+ int totalIncome = 0;
+ for (LottoMatchNumber lottoMatchNumber : LottoMatchNumber.values()) {
+ totalIncome += lottoMatchNumber.totalPrizeMoney(results.get(lottoMatchNumber));
+ }
+
+ income = (double) totalIncome/money;
+
+ return income;
+ }
+
+} | Java | ์ค์ํ ๋ถ๋ถ์ ์๋์ง๋ง Stream.generate๋ฅผ ํตํด ๋ถ๋ณ ํํ๋ก ํํํ ์ ์์ ๊ฒ ๊ฐ๋ค์. ๊ฐ๋ณ๋ณด๋ค๋ ๋ถ๋ณ ํํ๋ก ํํํ๋๊ฒ ์ฌ์ด๋ ์ดํํธ๋ ์ ๊ณ ๊ฐ๋
์ฑ ์ธก๋ฉด์์๋ ์ข์ ๊ฒ ๊ฐ์์. |
@@ -0,0 +1,49 @@
+package lotto.domain;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+public class LottoGame {
+ private static final int TICKET_PRICE = 1000;
+
+ List<LottoTicket> lottoTickets;
+ LottoMatch lottoMatch;
+
+ public LottoGame() {
+ this.lottoTickets = new ArrayList<>();
+ }
+
+ public List<LottoTicket> buyLottoTicket(int money) {
+ int ticketNum = money / TICKET_PRICE;
+
+ for (int i = 0; i < ticketNum; i++) {
+ this.lottoTickets.add(new LottoTicket());
+ }
+
+ return this.lottoTickets;
+ }
+
+ public HashMap<LottoMatchNumber, Integer> winLotto() {
+ return this.lottoMatch.matchResult(lottoTickets);
+ }
+
+ public void inputTargetNumbers(String input) {
+ lottoMatch = new LottoMatch(input);
+ }
+
+
+ public double checkIncome(HashMap<LottoMatchNumber, Integer> results, int money){
+ double income = 0;
+
+ int totalIncome = 0;
+ for (LottoMatchNumber lottoMatchNumber : LottoMatchNumber.values()) {
+ totalIncome += lottoMatchNumber.totalPrizeMoney(results.get(lottoMatchNumber));
+ }
+
+ income = (double) totalIncome/money;
+
+ return income;
+ }
+
+} | Java | ์ผ๋ฐ์ ์ผ๋ก ๋ฉ์๋ ๋ฆฌํด ํ์
์ด๋ ํ๋ผ๋ฏธํฐ ๋ฑ์ ๋คํ์ฑ ์ธก๋ฉด์์ ์ด์ ์ด ์๊ธฐ ๋๋ฌธ์ ๊ตฌ์ฒด ํ์
(HashMap)์ ์ฌ์ฉํ์ง ์์ต๋๋ค. ์ด์ ๊ฐ ์๋๊ฒ ์๋๋ผ๋ฉด ์ธํฐํ์ด์ค์ธ Map์ ๋ฆฌํด ํ์
์ผ๋ก ์ฐ์๋๊ฒ ์ด๋จ๊น์? |
@@ -0,0 +1,49 @@
+package lotto.domain;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+public class LottoGame {
+ private static final int TICKET_PRICE = 1000;
+
+ List<LottoTicket> lottoTickets;
+ LottoMatch lottoMatch;
+
+ public LottoGame() {
+ this.lottoTickets = new ArrayList<>();
+ }
+
+ public List<LottoTicket> buyLottoTicket(int money) {
+ int ticketNum = money / TICKET_PRICE;
+
+ for (int i = 0; i < ticketNum; i++) {
+ this.lottoTickets.add(new LottoTicket());
+ }
+
+ return this.lottoTickets;
+ }
+
+ public HashMap<LottoMatchNumber, Integer> winLotto() {
+ return this.lottoMatch.matchResult(lottoTickets);
+ }
+
+ public void inputTargetNumbers(String input) {
+ lottoMatch = new LottoMatch(input);
+ }
+
+
+ public double checkIncome(HashMap<LottoMatchNumber, Integer> results, int money){
+ double income = 0;
+
+ int totalIncome = 0;
+ for (LottoMatchNumber lottoMatchNumber : LottoMatchNumber.values()) {
+ totalIncome += lottoMatchNumber.totalPrizeMoney(results.get(lottoMatchNumber));
+ }
+
+ income = (double) totalIncome/money;
+
+ return income;
+ }
+
+} | Java | ์ด๋ฐ ํํ๋ก ์ฌ์ฉํ ๊ฑฐ๋ฉด ์ธ์คํด์ค ๋ณ์ ์์ด ๋ฐ๋ก ๋ฆฌํดํ๋ ํํ๋ก ์ฌ์ฉํ๋ฉด ์ด๋จ๊น์? |
@@ -0,0 +1,47 @@
+package lotto.domain;
+
+
+import java.util.*;
+
+public class LottoMatch {
+
+ List<Integer> targetNumbers;
+
+
+ public LottoMatch(String input) {
+ targetNumbers = new ArrayList<>();
+ String[] inputs = input.split(", ");
+
+ for (int i = 0; i < inputs.length; i++) {
+ targetNumbers.add(Integer.valueOf(inputs[i]));
+ }
+ }
+
+ public HashMap<LottoMatchNumber, Integer> matchResult(List<LottoTicket> myNumbers) {
+ HashMap<LottoMatchNumber, Integer> results = new HashMap<>();
+ results.put(LottoMatchNumber.MATCH3, 0);
+ results.put(LottoMatchNumber.MATCH4, 0);
+ results.put(LottoMatchNumber.MATCH5, 0);
+ results.put(LottoMatchNumber.MATCH6, 0);
+
+ for (LottoTicket myNumber : myNumbers) {
+ int matchCount = myNumber.checkMatch(targetNumbers);
+ inputMatchResult(matchCount, results);
+ }
+
+ return results;
+ }
+
+ private void inputMatchResult(int matchCount, HashMap<LottoMatchNumber, Integer> results) {
+ for (LottoMatchNumber lottoMatchNumber : LottoMatchNumber.values()) {
+ inputMatchCount(matchCount, results, lottoMatchNumber);
+ }
+ }
+
+ private void inputMatchCount(int matchCount, HashMap<LottoMatchNumber, Integer> results, LottoMatchNumber lottoMatchNumber) {
+ if (lottoMatchNumber.getMatchNumber() == matchCount) {
+ results.put(lottoMatchNumber, results.get(lottoMatchNumber) + 1);
+ }
+ }
+
+} | Java | Stream์ groupingBy๋ Function.identity๋ฅผ ํ์ฉํด๋ณด์๋ ์ข์ ๊ฒ ๊ฐ๋ค์. |
@@ -0,0 +1,47 @@
+package lotto.domain;
+
+
+import java.util.*;
+
+public class LottoMatch {
+
+ List<Integer> targetNumbers;
+
+
+ public LottoMatch(String input) {
+ targetNumbers = new ArrayList<>();
+ String[] inputs = input.split(", ");
+
+ for (int i = 0; i < inputs.length; i++) {
+ targetNumbers.add(Integer.valueOf(inputs[i]));
+ }
+ }
+
+ public HashMap<LottoMatchNumber, Integer> matchResult(List<LottoTicket> myNumbers) {
+ HashMap<LottoMatchNumber, Integer> results = new HashMap<>();
+ results.put(LottoMatchNumber.MATCH3, 0);
+ results.put(LottoMatchNumber.MATCH4, 0);
+ results.put(LottoMatchNumber.MATCH5, 0);
+ results.put(LottoMatchNumber.MATCH6, 0);
+
+ for (LottoTicket myNumber : myNumbers) {
+ int matchCount = myNumber.checkMatch(targetNumbers);
+ inputMatchResult(matchCount, results);
+ }
+
+ return results;
+ }
+
+ private void inputMatchResult(int matchCount, HashMap<LottoMatchNumber, Integer> results) {
+ for (LottoMatchNumber lottoMatchNumber : LottoMatchNumber.values()) {
+ inputMatchCount(matchCount, results, lottoMatchNumber);
+ }
+ }
+
+ private void inputMatchCount(int matchCount, HashMap<LottoMatchNumber, Integer> results, LottoMatchNumber lottoMatchNumber) {
+ if (lottoMatchNumber.getMatchNumber() == matchCount) {
+ results.put(lottoMatchNumber, results.get(lottoMatchNumber) + 1);
+ }
+ }
+
+} | Java | ์์ฑ์๋ ์ด๋ฏธ ์์ฑ์ด๋ ์ฑ
์์ ๊ฐ์ง๊ณ ์๋๋ฐ ์์ฑ์ ๋ด๋ถ์์ split์ ํตํ ํ์ฑ ๋ฐ ์ฌ๋ฌ ์ฑ
์์ด ํฌํจ๋์ด ์๋ค์.
์์ฑ์์ ๋ก์ง์ ๋ฃ๊ณ ์ถ๋ค๋ฉด ์ ์ ํฉํฐ๋ฆฌ๋ก ๋ถ๋ฆฌํ๊ณ ์ ์ ํฉํฐ๋ฆฌ์ ๋ก์ง์ ์ถ๊ฐํ ๋ค ๊ฑฐ๊ธฐ์ ์์ฑ์๋ฅผ ํธ์ถํ๊ฑฐ๋ ํ๋ ํํ๋ก ๊ตฌํํ๋๊ฑด ์ด๋จ๊น์? |
@@ -0,0 +1,65 @@
+package lotto.domain;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+public class LottoTicket {
+
+ private static final int PICK_NUMBERS = 6;
+
+ List<Integer> lottoNumbers;
+
+ public LottoTicket() {
+ this.lottoNumbers = new ArrayList<>();
+ for (int i = 1; i <= 45; i++) {
+ this.lottoNumbers.add(i);
+ }
+ lottoNumbers = issueTicket();
+ }
+
+ public LottoTicket(List<Integer> ticketNumbers) {
+ this.lottoNumbers = new ArrayList<>(ticketNumbers);
+ }
+
+ public List<Integer> issueTicket() {
+ Collections.shuffle(this.lottoNumbers);
+ this.lottoNumbers = this.lottoNumbers.subList(0, PICK_NUMBERS);
+ Collections.sort(this.lottoNumbers);
+
+ return this.lottoNumbers;
+ }
+
+
+ public int checkMatch(List<Integer> targetNumbers) {
+ if (targetNumbers.size() != this.lottoNumbers.size()) {
+ throw new IllegalArgumentException("๋น์ฒจ ๋ฒํธ ๊ฐ์๊ฐ ์ผ์น ํ์ง ์์ต๋๋ค.");
+ }
+
+ int count = 0;
+ for (int i = 0; i < this.lottoNumbers.size(); i++) {
+ count = compareTargetnumbers(targetNumbers, i, count);
+ }
+
+ return count;
+ }
+
+ private int compareTargetnumbers(List<Integer> targetNumbers, int i, int count) {
+ for (int j = 0; j < targetNumbers.size(); j++) {
+ count = compareNumbers(targetNumbers, i, count, j);
+ }
+ return count;
+ }
+
+ private int compareNumbers(List<Integer> targetNumbers, int i, int count, int j) {
+ if (this.lottoNumbers.get(i) == targetNumbers.get(j)) {
+ count++;
+ }
+ return count;
+ }
+
+ @Override
+ public String toString() {
+ return lottoNumbers.toString();
+ }
+} | Java | ์ ์ฝ ์กฐ๊ฑด ๊ฒ์ฆ์ด ์ ํ ํฌํจ๋์ด ์์ง ์๋ค์. ๋๋ฉ์ธ์ ํน์ฑ์ ์ ๋ํ๋ด์ง ๋ชปํ๋ ๊ฒ ๊ฐ์ต๋๋ค.
1. 1 - 45๊น์ง์ ์ซ์๋ง ์กด์ฌํด์ผ ํจ
2. 6๊ฐ์ ์ค๋ณต๋์ง ์์ ์ซ์๋ก ์ด๋ฃจ์ด์ ธ์ผ ํจ
์์ ๊ฐ์ด ๋ก๋ ๋๋ฉ์ธ์ ํน์ฑ์ด ํด๋์ค์ ๋ฐ์๋๋๋ก ์ค๊ณํด๋ณด์๋ฉด ์ข๊ฒ ์ต๋๋ค. |
@@ -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๋ผ๋ ํด๋์ค๊ฐ ์๋ ๊ฒ์ด๊ตฐ์. |
@@ -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,55 @@
+package christmas.controller;
+
+import christmas.domain.date.Date;
+import christmas.domain.badge.Badge;
+import christmas.domain.reward.Reward;
+import christmas.domain.order.Bill;
+import christmas.dto.RewardDto;
+import christmas.factory.ControllerFactory;
+import christmas.view.OutputView;
+
+public class GameController {
+ private final DateController dateController = ControllerFactory.getDateController();
+ private final OrderController orderController = ControllerFactory.getOrderController();
+ private final EventController eventController = ControllerFactory.getEventController();
+ private final BadgeController badgeController = ControllerFactory.getBadgeController();
+
+ public void run() {
+ printWelcomeMessage();
+
+ Date date = dateController.acceptVisitDate();
+ Bill bill = orderController.acceptOrder();
+ printOrderResult(date, bill);
+
+ Reward reward = eventController.confirmReward(date, bill);
+ RewardDto rewardDto = reward.toDto();
+
+ printRewardResult(rewardDto);
+ printFinalCheckoutPrice(bill, rewardDto);
+
+ printBadgeResult(badgeController.grantBadge(rewardDto));
+ }
+
+ public void printWelcomeMessage() {
+ OutputView.printWelcomeMessage();
+ }
+
+ public void printOrderResult(Date date, Bill bill) {
+ OutputView.printPreviewMessage(date);
+ OutputView.printOrderMessage(bill);
+ }
+
+ public void printFinalCheckoutPrice(Bill bill, RewardDto rewardDto) {
+
+ int checkoutPrice = bill.totalPrice() - rewardDto.getTotalDiscountReward();
+ OutputView.printFinalCheckoutPriceMessage(checkoutPrice);
+ }
+
+ public void printRewardResult(RewardDto rewardDto) {
+ OutputView.printRewardsMessage(rewardDto);
+ }
+
+ public void printBadgeResult(Badge badge) {
+ OutputView.printBadgeMessage(badge);
+ }
+} | Java | ์ทจํฅ ์ฐจ์ด ๋ผ๊ณ ์๊ฐํ๊ธด ํ์ง๋ง, ๊ฐ์ฒด๋ฅผ ์์ฑํด์ฃผ๋ ๋ผ์ธ๋ค์ ํ๋๋ก ๋ชจ์ผ๊ณ ์ถ๋ ฅprint๋ฉ์๋๋ค์ ์ ๋ถ ๋ชจ์์ฃผ๋๊ฒ๋ ํ๋์ ๋ฐฉ๋ฒ์ผ ๊ฒ ๊ฐ์์
printWelcomeMessage();
Date date = dateController.acceptVisitDate();
Bill bill = orderController.acceptOrder();
Reward reward = eventController.confirmReward(date, bill);
RewardDto rewardDto = reward.toDto();
printRewardResult(rewardDto);
printOrderResult(date, bill);
printFinalCheckoutPrice(bill, rewardDto);
printBadgeResult(badgeController.grantBadge(rewardDto));
์ด๋ฐ์์ผ๋ก์ |
@@ -0,0 +1,26 @@
+package christmas.domain.category;
+
+import christmas.domain.menu.Menu;
+import christmas.domain.menu.MenuItem;
+
+public enum Appetizer implements MenuItem {
+ MUSHROOM_SOUP("์์ก์ด์ํ", 6000),
+ TAPAS("ํํ์ค", 5500),
+ CAESAR_SALAD("์์ ์๋ฌ๋", 8000);
+
+ private Menu menu;
+
+ Appetizer(String name, int price) {
+ this.menu = new Menu(name, price);
+ }
+ @Override
+ public Menu get(){
+ return menu;
+ }
+
+ @Override
+ public String getName() {
+ return menu.name();
+ }
+
+} | Java | ์ธํฐํ์ด์ค๋ฅผ ์ฌ์ฉํ์
จ๊ตฐ์!! ์ด๋ ๊ฒ ๋๋ฉด ์ ์ง ๋ณด์์ ๋ ์ข์๊ฑฐ๋ผ๋ ์๊ฐ์ด ๋๋ค์ ๋ฉ์ ธ์ |
@@ -0,0 +1,32 @@
+package christmas.domain.date;
+
+import christmas.exception.DateException;
+import christmas.exception.message.DateExceptionMessage;
+import christmas.util.Calendar;
+
+import static christmas.constant.DateConstant.START_DAY;
+import static christmas.constant.DateConstant.END_DAY;
+
+public record Date(int day, DayOfWeek dayOfWeek) {
+ public static Date of(int day) {
+ validate(day);
+
+ DayOfWeek dayOfWeek = getDayOfWeek(day);
+ return new Date(day, dayOfWeek);
+ }
+
+ private static void validate(int day) {
+ validateDayRange(day);
+ }
+
+ private static void validateDayRange(int day) {
+ if (day < START_DAY || day > END_DAY) {
+ throw new DateException(DateExceptionMessage.INVALID_DAY);
+ }
+ }
+
+ private static DayOfWeek getDayOfWeek(int day) {
+ return Calendar.calculateDayOfWeek(day);
+ }
+
+} | Java | ์ ๋ ๋ฆฌ๋ทฐํ๋ค๊ฐ ๋ฐฐ์ด ๋ด์ฉ์ธ๋ฐ localDate.of() ๋ฅผ ์ฌ์ฉํ๋ ๋ฐฉ๋ฒ๋ ์์ด์ ์ถ์ฒ ๋๋ ค์!! |
@@ -0,0 +1,37 @@
+package christmas.domain.event.discount;
+
+import christmas.domain.date.Date;
+import christmas.domain.reward.DiscountEventReward;
+import christmas.lib.event.DiscountEvent;
+
+import static christmas.constant.EventConstant.CHRISTMAS_DAY;
+import static christmas.constant.EventConstant.D_DAY_DISCOUNT_UNIT;
+import static christmas.constant.EventConstant.CHRISTMAS_EVENT_MESSAGE;
+import static christmas.constant.EventConstant.D_DAY_START_PRICE;
+
+
+public class ChristmasDiscountEvent extends DiscountEvent<Date> {
+ private final Integer D_DAY = CHRISTMAS_DAY;
+ private final Integer START_PRICE = D_DAY_START_PRICE;
+ private final Integer DISCOUNT_UNIT = D_DAY_DISCOUNT_UNIT;
+ private final String EVENT_NAME = CHRISTMAS_EVENT_MESSAGE;
+
+ @Override
+ public boolean checkCondition(Date date) {
+ if (date.day() <= D_DAY) {
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public DiscountEventReward provideReward(Date date) {
+ int currentDay = date.day();
+ int discountPrice = calculateDiscountPrice(currentDay);
+ return new DiscountEventReward(EVENT_NAME, discountPrice);
+ }
+
+ private Integer calculateDiscountPrice(int currentDay) {
+ return START_PRICE + (currentDay - 1) * DISCOUNT_UNIT;
+ }
+} | Java | static import๋ฌธ๋ค์ด ์์ ์์นํ๋ ๊ฒ์ด ์๋ฐ ์ปจ๋ฒค์
์ ๋ถํฉํ๋ ๊ฒ์ผ๋ก ์๊ณ ์์ด์ |
@@ -0,0 +1,14 @@
+package christmas.controller;
+
+import christmas.domain.date.Date;
+import christmas.domain.reward.Reward;
+import christmas.domain.order.Bill;
+import christmas.factory.ServiceFactory;
+import christmas.service.EventService;
+
+public class EventController {
+ private final EventService eventService = ServiceFactory.getEventService();
+ public Reward confirmReward(Date date, Bill bill){
+ return eventService.createReward(date,bill);
+ }
+} | Java | ํ์ค ๊ณต๋ฐฑ ์ฝ์
์ด ๋น ์ง ๊ฒ ๊ฐ์์ |
@@ -0,0 +1,28 @@
+package christmas.domain.event.discount;
+
+import java.util.List;
+
+import christmas.domain.date.Date;
+import christmas.domain.reward.DiscountEventReward;
+import christmas.lib.event.DiscountEvent;
+
+import static christmas.constant.EventConstant.SPECIAL_DAY_MESSAGE;
+import static christmas.constant.EventConstant.SPECIAL_DAY_PRICE;
+
+public class SpecialDiscountEvent extends DiscountEvent<Void> {
+ private final List<Integer> SPECIAL_DAY = List.of(3, 10, 17, 24, 25, 31);
+ private final String EVENT_NAME = SPECIAL_DAY_MESSAGE;
+
+ @Override
+ public boolean checkCondition(Date date) {
+ if (SPECIAL_DAY.contains(date.day())) {
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public DiscountEventReward provideReward(Void object) {
+ return new DiscountEventReward(EVENT_NAME, SPECIAL_DAY_PRICE);
+ }
+} | Java | ํน๋ณ ํ ์ธ์ด ์ ์ฉ๋๋ ๋ ์ด ๋งค์ฃผ ์ผ์์ผ, ํฌ๋ฆฌ์ค๋ง์ค ๋ ์ด๋ผ๋ ์ ์ DayOfWeek๋ฅผ ํ์ฉํด์ ํํํ๋ ๊ฒ๋ ์ข์ ๋ฐฉ๋ฒ์ผ๊ฑฐ ๊ฐ์์! |
@@ -0,0 +1,96 @@
+package christmas.domain.order;
+
+import java.util.ArrayList;
+import java.util.EnumMap;
+import java.util.List;
+
+import christmas.domain.menu.Category;
+import christmas.exception.OrderException;
+import christmas.exception.message.OrderExceptionMessage;
+
+import static christmas.constant.OrderConstant.MAX_TOTAL_ORDER_COUNT;
+
+public record Bill(int totalPrice, EnumMap<Category, List<OrderInfo>> orderDetail) {
+ public static Bill of(List<RequestOrder> requestOrderList) {
+ EnumMap<Category, List<OrderInfo>> orderMenuBoard = confirmOrders(requestOrderList);
+
+ validate(orderMenuBoard);
+
+ int totalPrice = calculateTotalPrice(orderMenuBoard);
+ return new Bill(totalPrice, orderMenuBoard);
+ }
+
+ private static EnumMap<Category, List<OrderInfo>> confirmOrders(List<RequestOrder> requestOrderList) {
+ EnumMap<Category, List<OrderInfo>> orderMenuBoard = initOrderMenuBoard();
+
+ for (RequestOrder requestOrder : requestOrderList) {
+ confirmOrder(requestOrder, orderMenuBoard);
+ }
+ return orderMenuBoard;
+ }
+
+ private static void confirmOrder(RequestOrder requestOrder, EnumMap<Category, List<OrderInfo>> orderMenuBoard) {
+ String orderName = requestOrder.orderName();
+ int orderAmount = requestOrder.amount();
+
+ OrderResult orderResult = OrderResult.of(orderName, orderAmount);
+ orderMenuBoard.get(orderResult.category()).add(orderResult.orderInfo());
+ }
+
+
+ private static EnumMap<Category, List<OrderInfo>> initOrderMenuBoard() {
+ EnumMap<Category, List<OrderInfo>> orderMenuBoard = new EnumMap<>(Category.class);
+
+ for (Category category : Category.values()) {
+ orderMenuBoard.put(category, new ArrayList<>());
+ }
+ return orderMenuBoard;
+ }
+
+ private static void validate(EnumMap<Category, List<OrderInfo>> orderMenuBoard) {
+ int totalAmount = countTotalOrderMenu(orderMenuBoard);
+ validateTotalAmountInRange(totalAmount);
+ validateMenuIsOnlyDrink(orderMenuBoard.get(Category.DRINK), totalAmount);
+ }
+
+ private static void validateTotalAmountInRange(int totalAmount) {
+ if (totalAmount > MAX_TOTAL_ORDER_COUNT) {
+ throw new OrderException(OrderExceptionMessage.OVERALL_ORDER_COUNT);
+ }
+ }
+
+ private static void validateMenuIsOnlyDrink(List<OrderInfo> orderDrinks, int totalOrderCount) {
+ int drinkOrderCount = countOrderMenus(orderDrinks);
+ if (drinkOrderCount == totalOrderCount) {
+ throw new OrderException(OrderExceptionMessage.ONLY_DRINK);
+ }
+ }
+
+
+ private static Integer countTotalOrderMenu(EnumMap<Category, List<OrderInfo>> orderBoard) {
+ int totalOrderCount = 0;
+ for (List<OrderInfo> orderInfos : orderBoard.values()) {
+ totalOrderCount += countOrderMenus(orderInfos);
+ }
+ return totalOrderCount;
+ }
+
+ private static Integer countOrderMenus(List<OrderInfo> orderInfos) {
+ int orderCount = 0;
+ for (OrderInfo orderInfo : orderInfos) {
+ orderCount += orderInfo.amount();
+ }
+ return orderCount;
+ }
+
+ private static Integer calculateTotalPrice(EnumMap<Category, List<OrderInfo>> orderBoard) {
+ int totalPrice = 0;
+ for (List<OrderInfo> orderInfos : orderBoard.values()) {
+ for (OrderInfo orderInfo : orderInfos) {
+ int price = orderInfo.menu().price();
+ totalPrice += orderInfo.amount() * price;
+ }
+ }
+ return totalPrice;
+ }
+}
\ No newline at end of file | Java | record๋ฅผ ํ์ฉํด์ผ๊ฒ ๋ค๊ณ ์๊ฐํ ์ด์ ๊ฐ ์์๊น์? |
@@ -0,0 +1,27 @@
+package christmas.domain.category;
+
+import christmas.domain.menu.Menu;
+import christmas.domain.menu.MenuItem;
+
+public enum Dessert implements MenuItem {
+ CHOCO_CAKE("์ด์ฝ์ผ์ดํฌ", 15000),
+ ICE_CREAM("์์ด์คํฌ๋ฆผ", 5000);
+
+ private Menu menu;
+
+ Dessert(String name, int price) {
+ this.menu = new Menu(name, price);
+ }
+
+ @Override
+ public Menu get() {
+ return menu;
+ }
+
+ @Override
+ public String getName() {
+ return menu.name();
+ }
+
+
+} | Java | ๋ฉ๋ด ์นดํ
๊ณ ๋ฆฌ๋ง๋ค enum ํด๋์ค๋ฅผ ๋๋ ์๊ฐ์ ๋ชปํ๋๋ฐ ์ด๋ ๊ฒ ํ๋ฉด ์ ์ง๋ณด์๊ฐ ๋ ์ฝ๊ฒ ๋ค์!
์ข์ ์์ด๋์ด์ธ๊ฑฐ ๊ฐ์์! |
@@ -0,0 +1,6 @@
+package christmas.constant;
+
+public interface DateConstant {
+ public static int START_DAY = 1;
+ public static int END_DAY = 31;
+} | Java | ์ด ๋ถ๋ถ๋ ์ ์๊ฐ ๋ฐ๋๋ค๋ฉด?
12์์์ 1์๋ก ๋ฐ๋ ๋, 2์๋ก ๋ฐ๋ ๋ ์ผ์์ ๋ํ ์ ์ฝ์กฐ๊ฑด์ ์๋์ผ๋ก ์์ ํด์ฃผ์ด์ผ ํ ๊ฒ์ผ๋ก ์๊ฒฌ๋ฉ๋๋ค.
์ ์ญ์์ ์ค์ ํ๋ ์ฐ/์ ์ค์ ์ ๋ฐํ์ผ๋ก StartDay์ EndDay๋ฅผ ๋์ ์ผ๋ก ํ๋จํ๋ฉด ์ข์ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,9 @@
+package christmas.constant;
+
+public interface OrderConstant {
+ public static final String ORDER_SEPARATOR = ",";
+ public static final String REQUEST_SEPARATOR = "-";
+
+ public static final int MIN_AMOUNT = 1;
+ public static final int MAX_TOTAL_ORDER_COUNT = 20;
+} | Java | ์ด ๋ถ๋ถ๋ ์ ์ฝ์กฐ๊ฑด์ผ๋ก ๋ถ๋ฆฌํด์ ์ค์ ํ ๋ถ๋ถ ๋๋ฌด ์ข์ต๋๋ค ๐ |
@@ -0,0 +1,26 @@
+package christmas.domain.category;
+
+import christmas.domain.menu.Menu;
+import christmas.domain.menu.MenuItem;
+
+public enum Drink implements MenuItem {
+ ZERO_COKE("์ ๋ก์ฝ๋ผ", 3000),
+ RED_WINE("๋ ๋์์ธ", 60000),
+ CHAMPAGNE("์ดํ์ธ", 25000);
+ private Menu menu;
+
+ Drink(String name, int price) {
+ this.menu = new Menu(name, price);
+ }
+
+ @Override
+ public Menu get() {
+ return menu;
+ }
+
+ @Override
+ public String getName() {
+ return menu.name();
+ }
+
+} | Java | ์ด ๋ถ๋ถ๋ 25_000๊ณผ ๊ฐ์ด ์ผ๊ด์ ์ธ ํํ๋ก ์ฌ์ฉํ๋ฉด ์ข์ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,28 @@
+package christmas.domain.event.discount;
+
+import java.util.List;
+
+import christmas.domain.date.Date;
+import christmas.domain.reward.DiscountEventReward;
+import christmas.lib.event.DiscountEvent;
+
+import static christmas.constant.EventConstant.SPECIAL_DAY_MESSAGE;
+import static christmas.constant.EventConstant.SPECIAL_DAY_PRICE;
+
+public class SpecialDiscountEvent extends DiscountEvent<Void> {
+ private final List<Integer> SPECIAL_DAY = List.of(3, 10, 17, 24, 25, 31);
+ private final String EVENT_NAME = SPECIAL_DAY_MESSAGE;
+
+ @Override
+ public boolean checkCondition(Date date) {
+ if (SPECIAL_DAY.contains(date.day())) {
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public DiscountEventReward provideReward(Void object) {
+ return new DiscountEventReward(EVENT_NAME, SPECIAL_DAY_PRICE);
+ }
+} | Java | ์ ๋ ์ด ๋ถ๋ถ์ ๋ํด์๋ ๋ค๋ฅธ ์๊ฒฌ์
๋๋ค!
`๋ณ` ์ด ๋ฌ๋ ค์๋ ๋ ์ด ์ด๋ฒคํธ ๋ ๋ก ์ ์ฉํ๋ค๋ ์กฐ๊ฑด์ด์๊ธฐ ๋๋ฌธ์,
์ด ๋ถ๋ถ์ List๋ก ์ ์ ์ผ๋ก ํ ๋นํด์ฃผ๋๊ฒ ์คํ๋ ค ๋ ์ ์ ํ ์ค๊ณ์๋ค๊ณ ์๊ฐํด์! |
@@ -0,0 +1,96 @@
+package christmas.domain.order;
+
+import java.util.ArrayList;
+import java.util.EnumMap;
+import java.util.List;
+
+import christmas.domain.menu.Category;
+import christmas.exception.OrderException;
+import christmas.exception.message.OrderExceptionMessage;
+
+import static christmas.constant.OrderConstant.MAX_TOTAL_ORDER_COUNT;
+
+public record Bill(int totalPrice, EnumMap<Category, List<OrderInfo>> orderDetail) {
+ public static Bill of(List<RequestOrder> requestOrderList) {
+ EnumMap<Category, List<OrderInfo>> orderMenuBoard = confirmOrders(requestOrderList);
+
+ validate(orderMenuBoard);
+
+ int totalPrice = calculateTotalPrice(orderMenuBoard);
+ return new Bill(totalPrice, orderMenuBoard);
+ }
+
+ private static EnumMap<Category, List<OrderInfo>> confirmOrders(List<RequestOrder> requestOrderList) {
+ EnumMap<Category, List<OrderInfo>> orderMenuBoard = initOrderMenuBoard();
+
+ for (RequestOrder requestOrder : requestOrderList) {
+ confirmOrder(requestOrder, orderMenuBoard);
+ }
+ return orderMenuBoard;
+ }
+
+ private static void confirmOrder(RequestOrder requestOrder, EnumMap<Category, List<OrderInfo>> orderMenuBoard) {
+ String orderName = requestOrder.orderName();
+ int orderAmount = requestOrder.amount();
+
+ OrderResult orderResult = OrderResult.of(orderName, orderAmount);
+ orderMenuBoard.get(orderResult.category()).add(orderResult.orderInfo());
+ }
+
+
+ private static EnumMap<Category, List<OrderInfo>> initOrderMenuBoard() {
+ EnumMap<Category, List<OrderInfo>> orderMenuBoard = new EnumMap<>(Category.class);
+
+ for (Category category : Category.values()) {
+ orderMenuBoard.put(category, new ArrayList<>());
+ }
+ return orderMenuBoard;
+ }
+
+ private static void validate(EnumMap<Category, List<OrderInfo>> orderMenuBoard) {
+ int totalAmount = countTotalOrderMenu(orderMenuBoard);
+ validateTotalAmountInRange(totalAmount);
+ validateMenuIsOnlyDrink(orderMenuBoard.get(Category.DRINK), totalAmount);
+ }
+
+ private static void validateTotalAmountInRange(int totalAmount) {
+ if (totalAmount > MAX_TOTAL_ORDER_COUNT) {
+ throw new OrderException(OrderExceptionMessage.OVERALL_ORDER_COUNT);
+ }
+ }
+
+ private static void validateMenuIsOnlyDrink(List<OrderInfo> orderDrinks, int totalOrderCount) {
+ int drinkOrderCount = countOrderMenus(orderDrinks);
+ if (drinkOrderCount == totalOrderCount) {
+ throw new OrderException(OrderExceptionMessage.ONLY_DRINK);
+ }
+ }
+
+
+ private static Integer countTotalOrderMenu(EnumMap<Category, List<OrderInfo>> orderBoard) {
+ int totalOrderCount = 0;
+ for (List<OrderInfo> orderInfos : orderBoard.values()) {
+ totalOrderCount += countOrderMenus(orderInfos);
+ }
+ return totalOrderCount;
+ }
+
+ private static Integer countOrderMenus(List<OrderInfo> orderInfos) {
+ int orderCount = 0;
+ for (OrderInfo orderInfo : orderInfos) {
+ orderCount += orderInfo.amount();
+ }
+ return orderCount;
+ }
+
+ private static Integer calculateTotalPrice(EnumMap<Category, List<OrderInfo>> orderBoard) {
+ int totalPrice = 0;
+ for (List<OrderInfo> orderInfos : orderBoard.values()) {
+ for (OrderInfo orderInfo : orderInfos) {
+ int price = orderInfo.menu().price();
+ totalPrice += orderInfo.amount() * price;
+ }
+ }
+ return totalPrice;
+ }
+}
\ No newline at end of file | Java | ์ง์ญ๋ณ์ ์ฌํ ๋น์ ์๋ฐ๊ฐ ์ซ์ดํ๋ ๋ฌธ๋ฒ์ด๋ผ๊ณ ์๊ณ ์์ด์!
์คํธ๋ฆผ ๋ฌธ๋ฒ์ ํตํด ํํฐ๋งํด์ ๋ํ๋ ๋ก์ง์ ์ค๊ณํ๋ค๋ฉด,
๋ถํ์ํ ์ง์ญ๋ณ์ ์ฌํ ๋น์ ํผํ ์ ์์ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,96 @@
+package christmas.domain.order;
+
+import java.util.ArrayList;
+import java.util.EnumMap;
+import java.util.List;
+
+import christmas.domain.menu.Category;
+import christmas.exception.OrderException;
+import christmas.exception.message.OrderExceptionMessage;
+
+import static christmas.constant.OrderConstant.MAX_TOTAL_ORDER_COUNT;
+
+public record Bill(int totalPrice, EnumMap<Category, List<OrderInfo>> orderDetail) {
+ public static Bill of(List<RequestOrder> requestOrderList) {
+ EnumMap<Category, List<OrderInfo>> orderMenuBoard = confirmOrders(requestOrderList);
+
+ validate(orderMenuBoard);
+
+ int totalPrice = calculateTotalPrice(orderMenuBoard);
+ return new Bill(totalPrice, orderMenuBoard);
+ }
+
+ private static EnumMap<Category, List<OrderInfo>> confirmOrders(List<RequestOrder> requestOrderList) {
+ EnumMap<Category, List<OrderInfo>> orderMenuBoard = initOrderMenuBoard();
+
+ for (RequestOrder requestOrder : requestOrderList) {
+ confirmOrder(requestOrder, orderMenuBoard);
+ }
+ return orderMenuBoard;
+ }
+
+ private static void confirmOrder(RequestOrder requestOrder, EnumMap<Category, List<OrderInfo>> orderMenuBoard) {
+ String orderName = requestOrder.orderName();
+ int orderAmount = requestOrder.amount();
+
+ OrderResult orderResult = OrderResult.of(orderName, orderAmount);
+ orderMenuBoard.get(orderResult.category()).add(orderResult.orderInfo());
+ }
+
+
+ private static EnumMap<Category, List<OrderInfo>> initOrderMenuBoard() {
+ EnumMap<Category, List<OrderInfo>> orderMenuBoard = new EnumMap<>(Category.class);
+
+ for (Category category : Category.values()) {
+ orderMenuBoard.put(category, new ArrayList<>());
+ }
+ return orderMenuBoard;
+ }
+
+ private static void validate(EnumMap<Category, List<OrderInfo>> orderMenuBoard) {
+ int totalAmount = countTotalOrderMenu(orderMenuBoard);
+ validateTotalAmountInRange(totalAmount);
+ validateMenuIsOnlyDrink(orderMenuBoard.get(Category.DRINK), totalAmount);
+ }
+
+ private static void validateTotalAmountInRange(int totalAmount) {
+ if (totalAmount > MAX_TOTAL_ORDER_COUNT) {
+ throw new OrderException(OrderExceptionMessage.OVERALL_ORDER_COUNT);
+ }
+ }
+
+ private static void validateMenuIsOnlyDrink(List<OrderInfo> orderDrinks, int totalOrderCount) {
+ int drinkOrderCount = countOrderMenus(orderDrinks);
+ if (drinkOrderCount == totalOrderCount) {
+ throw new OrderException(OrderExceptionMessage.ONLY_DRINK);
+ }
+ }
+
+
+ private static Integer countTotalOrderMenu(EnumMap<Category, List<OrderInfo>> orderBoard) {
+ int totalOrderCount = 0;
+ for (List<OrderInfo> orderInfos : orderBoard.values()) {
+ totalOrderCount += countOrderMenus(orderInfos);
+ }
+ return totalOrderCount;
+ }
+
+ private static Integer countOrderMenus(List<OrderInfo> orderInfos) {
+ int orderCount = 0;
+ for (OrderInfo orderInfo : orderInfos) {
+ orderCount += orderInfo.amount();
+ }
+ return orderCount;
+ }
+
+ private static Integer calculateTotalPrice(EnumMap<Category, List<OrderInfo>> orderBoard) {
+ int totalPrice = 0;
+ for (List<OrderInfo> orderInfos : orderBoard.values()) {
+ for (OrderInfo orderInfo : orderInfos) {
+ int price = orderInfo.menu().price();
+ totalPrice += orderInfo.amount() * price;
+ }
+ }
+ return totalPrice;
+ }
+}
\ No newline at end of file | Java | calculateTotalPrice์ ๋ฆฌํดํ์ Integer์ธ๋ฐ, ๋ฐํ ๋ณ์๋ int๋ค์!
ํด๋น ๋ฉ์๋๋ฅผ Integer๋ก ๋ฐํํ๋๋ก ์ค๊ณํ์ ์ด์ ๊ฐ ์์๊น์? |
@@ -0,0 +1,9 @@
+package christmas.constant;
+
+public interface BadgeConstant {
+ public static final int SANTA_THRESHOLD = 20000;
+ public static final int TREE_THRESHOLD = 10000;
+ public static final int STAR_THRESHOLD = 5000;
+ public static final int NON_THRESHOLD = 0;
+
+} | Java | ํ์ฌ ๊ตฌํํ์ ์ฝ๋์์ `BadgeConstant` ๋ `Badge` enum ์์ ์์๋ก ๋ฐ์ ์ฌ์ฉ๋์ง ์์ ๊ฒ์ผ๋ก ์กฐ๊ธ ๋ถํ์ํ ์ธํฐํ์ด์ค์ง ์๋ ์๊ฐ์ด๋ญ๋๋ค. `Badge` enum ์์ ์ด ๋ถ๋ถ์ ํจ๊ป ๊ตฌํํ ์ ์๋ค๊ณ ์๊ฐํ๋๋ฐ ์ด๋ป๊ฒ ์๊ฐํ์๋์? |
@@ -0,0 +1,27 @@
+package christmas.constant;
+
+import christmas.domain.category.Drink;
+import christmas.domain.menu.Menu;
+
+public interface EventConstant {
+ public static final Integer EVENT_THRESHOLD_PRICE = 10000;
+
+ public static final Integer WEEKEND_DISCOUNT_PRICE = 2023;
+ public static final String WEEKEND_DISCOUNT_EVENT_MESSAGE = "์ฃผ๋ง ํ ์ธ";
+
+ public static final Integer WEEKDAY_DISCOUNT_PRICE = 2023;
+ public static final String WEEKDAY_DISCOUNT_EVENT_MESSAGE = "ํ์ผ ํ ์ธ";
+
+
+ public static final Integer D_DAY_DISCOUNT_UNIT = 100;
+ public static final Integer D_DAY_START_PRICE = 1000;
+ public static final Integer CHRISTMAS_DAY = 25;
+ public static final String CHRISTMAS_EVENT_MESSAGE = "ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ";
+
+ public static final Integer SPECIAL_DAY_PRICE = 1000;
+ public static final String SPECIAL_DAY_MESSAGE = "ํน๋ณ ํ ์ธ";
+
+
+ public static final Integer CHAMPAGNE_LIMIT_PRICE = 120000;
+ public static final Menu CHAMPAGNE_PRESENT = Drink.CHAMPAGNE.get();
+} | Java | ์ด๋ฒคํธ ๊ด๋ จ ์์๋ฅผ ์ ๋ enum ์ผ๋ก ๊ตฌํํ์ต๋๋ค. ์ธํฐํ์ด์ค๋ก ์์๋ค์ ์ ์ํ์ ์ด์ ๊ฐ ๊ถ๊ธํฉ๋๋ค! |
@@ -0,0 +1,32 @@
+package christmas.domain.date;
+
+import christmas.exception.DateException;
+import christmas.exception.message.DateExceptionMessage;
+import christmas.util.Calendar;
+
+import static christmas.constant.DateConstant.START_DAY;
+import static christmas.constant.DateConstant.END_DAY;
+
+public record Date(int day, DayOfWeek dayOfWeek) {
+ public static Date of(int day) {
+ validate(day);
+
+ DayOfWeek dayOfWeek = getDayOfWeek(day);
+ return new Date(day, dayOfWeek);
+ }
+
+ private static void validate(int day) {
+ validateDayRange(day);
+ }
+
+ private static void validateDayRange(int day) {
+ if (day < START_DAY || day > END_DAY) {
+ throw new DateException(DateExceptionMessage.INVALID_DAY);
+ }
+ }
+
+ private static DayOfWeek getDayOfWeek(int day) {
+ return Calendar.calculateDayOfWeek(day);
+ }
+
+} | Java | ๋ ์ง ์ ๋ณด๋ฅผ ๋ด์ ๋ถ๋ณ๊ฐ์ฒด๋ฅผ ์ด์ฉํ์
จ๊ตฐ์ ๐ ๋ค๋ง ํ์ฌ `Date` ๊ฐ์ฒด๋ ๋ ์ง ์ ๋ณด์ ์์ผ ์ ๋ณด๋ง ๊ฐ์ง๊ณ ์๋๊ฒ์ผ๋ก ๋ณด์ด๋๋ฐ ๊ทธ๋ ๋ค๋ฉด ์ด๋ฏธ ์๋ฐ์์ ์ ๊ณตํ๋ `LocalDate` ๋ฅผ ์ฌ์ฉํ๋๊ฒ ์ด๋จ๊น ํ๋ ์๊ฐ์ด ๋ญ๋๋ค! 1์ฃผ์ฐจ ํผ๋๋ฐฑ์๋ ๋์ค๋ ๋ด์ฉ์ด๋๊น ๊ณ ๋ คํด๋ณด์๋ฉด ์ข์๊ฒ ๊ฐ์ต๋๋ค ๐ |
@@ -0,0 +1,25 @@
+package christmas.domain.event;
+
+import christmas.lib.event.DiscountEvent;
+import christmas.lib.event.Event;
+import christmas.lib.event.PresentEvent;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public record InProgressEventList(List<DiscountEvent> discountEventList,
+ List<PresentEvent> presentEventList) {
+ public static InProgressEventList of(List<Event> eventList) {
+ List<DiscountEvent> discountEventList = new ArrayList<>();
+ List<PresentEvent> presentEventList = new ArrayList<>();
+ for (Event event : eventList) {
+ if (event instanceof DiscountEvent) {
+ discountEventList.add((DiscountEvent) event);
+ }
+ if (event instanceof PresentEvent) {
+ presentEventList.add((PresentEvent) event);
+ }
+ }
+ return new InProgressEventList(discountEventList, presentEventList);
+ }
+} | Java | ์ด ๋ถ๋ถ์ ์ฝ๊ฐ ๊ฐ์ ํ ์๋ ์์๊ฒ ๊ฐ์ต๋๋ค! ์ด ํด๋์ค์ `of` ๋ฉ์๋๋ `EventSercice` ์์ `EventFactory` ์ static ๋ณ์์ธ `EVENT_LIST` ๋ฅผ ํ๋ผ๋ฏธํฐ๋ก ๋ฃ์ด์ ์์ฑํ๋ ๋ถ๋ถ์์๋ง ์ฐ์ด๋๋ฐ `EVENT_LIST` ๋ ํญ์ ๊ฐ์ ๊ฐ์ ๊ฐ์ง๋ ๋ณ์๋ก ์์๋ฉ๋๋ค. ๊ทธ๋ ๋ค๋ฉด ์ฒ์๋ถํฐ ํ ์ธ ์ด๋ฒคํธ์ ์ฆ์ ์ด๋ฒคํธ๋ฅผ ๋ฐ๋ก ๊ด๋ฆฌํ๋ ๋ฐฉ๋ฒ์ ์ด๋จ๊น์? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.