์คํ๋ง ์ํ๋ฆฌํฐ๋ก ์ฝ๋ ์์ฑํ๋ ์ค์, ์ฝ๋์ ๋ฌธ์ ์ ์ด ์์๋ค๋ ๊ฒ์ ๋ฐ๊ฒฌํ๋ค. (์ ํํ๋ ๋ฐ๊ฒฌํด์ฃผ์ ๊ฒ)
๋ฌธ์ ๊ฐ ๋๋ ์ฝ๋๋ฅผ ๋ณด์.
@Service
@RequiredArgsConstructor
public class LoadUserService {
private final RestTemplate restTemplate = new RestTemplate();
private SocialLoadStrategy socialLoadStrategy;//์ถ์ ํด๋์ค, ๋ก๊ทธ์ธ์ ์งํํ๋ ์ฌ์ดํธ๋ ๋ฐ๋ผ ๋ฌ๋ผ์ง
public OAuth2UserDetails getOAuth2UserDetails(AccessTokenSocialTypeToken authentication) {
SocialType socialType = authentication.getSocialType();
setSocialLoadStrategy(socialType);//SocialLoadStrategy ์ค์
String socialPk = socialLoadStrategy.getSocialPk(authentication.getAccessToken());//PK ๊ฐ์ ธ์ค๊ธฐ
return OAuth2UserDetails.builder() //PK์ SocialType์ ํตํด ํ์ ์์ฑ
.socialId(socialPk)
.socialType(socialType)
.build();
}
private void setSocialLoadStrategy(SocialType socialType) {
this.socialLoadStrategy = switch (socialType){
case KAKAO -> new KakaoLoadStrategy();
case GOOGLE -> new GoogleLoadStrategy();
case NAVER -> new NaverLoadStrategy();
default -> throw new IllegalArgumentException("์ง์ํ์ง ์๋ ๋ก๊ทธ์ธ ํ์์
๋๋ค");
};
}
}
์ ์ฝ๋์์ ๋ฌด์์ด ๋ฌธ์ ๊ฐ ๋๋์ง ํ๋ฒ ๋ง์ถฐ๋ณด์.
SocialLoadStrategy ๊ฐ ๋ฌธ์ ์๋ค!
๋ฌด์์ด ๋ฌธ์ ์ธ์ง ์ดํด๋ณด์
LoadUserService๋ ์ฑ๊ธํค์ผ๋ก ๊ด๋ฆฌ๋๋ค. ๋ฐ๋ผ์ ๊ฐ์ฒด์ ์ธ์คํด์ค๊ฐ ํ๋๋ง ์์ฑ๋๊ณ ๊ณต์ ๋๋ค.
ํ์ฌ ์ฝ๋๋ฅผ ๋ณด๋ฉด SocialLoadStrategy๋ final๋ ์๋๊ณ ๋ฉ์๋ ๋ธ๋ก ์์์ ์ ์ธ๋ ์ง์ญ๋ณ์๋ ์๋๋ค.
LoadUserService๋ ๋ฉค๋ฒ๋ณ์์ด๋ฉฐ, setSocialLoadStrategy์ ๋ฐ๋ผ ์ํ๊ฐ ๋ฐ๋๋ค.
์ฆ ๋ฉํฐ ์ค๋ ๋ ํ๊ฒฝ์์ ์ฌ๋ฌ ์์ฒญ์ด LoadUserService์ ์ํ๋ฅผ ๋ฐ๊ฟ๋ฒ๋ฆด ์ ์๋ ๊ฒ์ด๋ค.
๋ฐ๋ผ์ ์์ ์ฝ๋๋ ๋ค์๊ณผ ๊ฐ์ด ๊ณ ์ณ์ผ ํ๋ค.
@Service
@RequiredArgsConstructor
public class LoadUserService {
private final RestTemplate restTemplate = new RestTemplate();
public OAuth2UserDetails getOAuth2UserDetails(AccessTokenSocialTypeToken authentication) {
SocialType socialType = authentication.getSocialType();
SocialLoadStrategy socialLoadStrategy = getSocialLoadStrategy(socialType);//SocialLoadStrategy ์ค์
String socialPk = socialLoadStrategy.getSocialPk(authentication.getAccessToken());//PK ๊ฐ์ ธ์ค๊ธฐ
return OAuth2UserDetails.builder() //PK์ SocialType์ ํตํด ํ์ ์์ฑ
.socialId(socialPk)
.socialType(socialType)
.build();
}
private SocialLoadStrategy getSocialLoadStrategy(SocialType socialType) {
return switch (socialType){
case KAKAO -> new KakaoLoadStrategy();
case GOOGLE -> new GoogleLoadStrategy();
case NAVER -> new NaverLoadStrategy();
default -> throw new IllegalArgumentException("์ง์ํ์ง ์๋ ๋ก๊ทธ์ธ ํ์์
๋๋ค");
};
}
}