Skip to content

Commit

Permalink
Converter 전부 static으로 수정 및 변환로직 Converter로 통일 (#196)
Browse files Browse the repository at this point in the history
* delete: 나쁜 주석 제거

* refactor: MatchGameConverter static으로 변경

* delete: 불필요한 setter 삭제

* refactor: Post Redis Cache로 변환하는 로직 PostConverter로 이동

* delete: 불필요한 DTO 삭제

* refactor: CommentSaveRequest web 폴더로 이동

* refactor: DTO 접미사 삭제

* config: querydsl build 옵션 변경
  • Loading branch information
rookedsysc authored Oct 12, 2024
1 parent 3dc827d commit 4011735
Show file tree
Hide file tree
Showing 26 changed files with 240 additions and 359 deletions.
11 changes: 4 additions & 7 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -112,13 +112,10 @@ tasks.named('test') {
}

// === ⭐ QueryDsl 빌드 옵션 (선택) ===
def querydslDir = "$buildDir/generated/querydsl"
sourceSets {
main.java.srcDirs += [querydslDir]
def querydslSrcDir = 'src/main/generated'
clean {
delete file(querydslSrcDir)
}
tasks.withType(JavaCompile) {
options.annotationProcessorGeneratedSourcesDirectory = file(querydslDir)
}
clean.doLast {
file(querydslDir).deleteDir()
options.generatedSourceOutputDirectory = file(querydslSrcDir)
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import com.gamemoonchul.domain.entity.Comment;
import com.gamemoonchul.domain.entity.Member;
import com.gamemoonchul.domain.entity.Post;
import com.gamemoonchul.domain.model.dto.CommentSaveDto;
import com.gamemoonchul.infrastructure.web.dto.request.CommentSaveRequest;
import com.gamemoonchul.domain.status.MemberStatus;
import com.gamemoonchul.domain.status.PostStatus;
import com.gamemoonchul.infrastructure.repository.CommentRepository;
Expand Down Expand Up @@ -49,7 +49,7 @@ public List<Comment> searchByPostId(Long postId, Long requestMemberId) {
maxDelay = 10000
) // 재시도 간의 대기 시간 (1000ms)
)
public Comment save(CommentSaveDto request, Member member) {
public Comment save(CommentSaveRequest request, Member member) {
validatePostNotReplied(request);
Post post = postRepository.findById(request.postId())
.orElseThrow(() -> new NotFoundException(PostStatus.POST_NOT_FOUND));
Expand All @@ -69,7 +69,7 @@ public Comment save(CommentSaveDto request, Member member) {
/**
* 부모의 Comment가 또 부모를 가지지 않는지 검증
*/
private void validatePostNotReplied(CommentSaveDto request) {
private void validatePostNotReplied(CommentSaveRequest request) {
if (request.parentId() != null) {
Comment parentComment = commentRepository.findById(request.parentId())
.orElseThrow(() -> new BadRequestException(PostStatus.COMMENT_NOT_FOUND));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,13 @@
@RequiredArgsConstructor
public class MatchGameService {
private final MatchGameRepository matchGameRepository;
private final MatchGameConverter matchConverter;

public Optional<MatchGame> findByGameId(String gameId) {
return matchGameRepository.findByGameId(gameId);
}

public MatchGame save(MatchRecord vo) {
MatchGame matchGame = matchConverter.toMatchGame(vo);
MatchGame matchGame = MatchGameConverter.toMatchGame(vo);
return matchGameRepository.save(matchGame);
}
}
}
53 changes: 4 additions & 49 deletions src/main/java/com/gamemoonchul/application/YoutubeService.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,61 +28,33 @@
@Slf4j
@Transactional
public class YoutubeService {
/**
* Define a global variable that specifies the MIME type of the video
* being uploaded.
*/
private static final String VIDEO_FILE_FORMAT = "video/*";
/**
* Define a global instance of a Youtube object, which will be used
* to make YouTube Data API requests.
*/
private static YouTube youtube;

/**
* Upload the user-selected video to the user's YouTube channel. The code
* looks for the video in the application's project folder and uses OAuth
* 2.0 to authorize the API request.
*/
public String upload(Path filePath) {

// This OAuth 2.0 access scope allows an application to upload files
// to the authenticated user's YouTube channel, but doesn't allow
// other types of access.
List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.upload");

try {
// Authorize the request.
Credential credential = YoutubeAuth.authorize(scopes, "uploadvideo");

// This object is used to make YouTube Data API requests.
youtube = new YouTube.Builder(YoutubeAuth.HTTP_TRANSPORT, YoutubeAuth.JSON_FACTORY, credential).setApplicationName(
"gamemuncheol").build();
"gamemuncheol").build();

log.info("Uploading: {}", filePath);

// Add extra information to the video before uploading.
Video videoObjectDefiningMetadata = new Video();

// Set the video to be publicly visible. This is the default
// setting. Other supporting settings are "unlisted" and "private."
VideoStatus status = new VideoStatus();
status.setPrivacyStatus("public");
videoObjectDefiningMetadata.setStatus(status);

// Most of the video's metadata is set on the VideoSnippet object.
VideoSnippet snippet = new VideoSnippet();

// This code uses a Calendar instance to create a unique name and
// description for test purposes so that you can easily upload
// multiple files. You should remove this code from your project
// and use your own standard names instead.
Calendar cal = Calendar.getInstance();
snippet.setTitle("Test Upload via Java on " + cal.getTime());
snippet.setDescription(
"Video uploaded via YouTube Data API V3 using the Java library " + "on " + cal.getTime());
"Video uploaded via YouTube Data API V3 using the Java library " + "on " + cal.getTime());

// Set the keyword tags that you want to associate with the video.
List<String> tags = new ArrayList<String>();
tags.add("test");
tags.add("example");
Expand All @@ -91,31 +63,16 @@ public String upload(Path filePath) {
tags.add("erase me");
snippet.setTags(tags);

// Add the completed snippet object to the video resource.
videoObjectDefiningMetadata.setSnippet(snippet);

InputStreamContent mediaContent = new InputStreamContent(VIDEO_FILE_FORMAT,
Files.newInputStream(filePath));
Files.newInputStream(filePath));

// Insert the video. The command sends three arguments. The first
// specifies which information the API request is setting and which
// information the API response should return. The second argument
// is the video resource that contains metadata about the new video.
// The third argument is the actual video content.
YouTube.Videos.Insert videoInsert = youtube.videos()
.insert("snippet,statistics,status", videoObjectDefiningMetadata, mediaContent);
.insert("snippet,statistics,status", videoObjectDefiningMetadata, mediaContent);

// Set the upload type and add an event listener.
MediaHttpUploader uploader = videoInsert.getMediaHttpUploader();

// Indicate whether direct media upload is enabled. A value of
// "True" indicates that direct media upload is enabled and that
// the entire media content will be uploaded in a single request.
// A value of "False," which is the default, indicates that the
// request will use the resumable media upload protocol, which
// supports the ability to resume an upload operation after a
// network interruption or other transmission failure, saving
// time and bandwidth in the event of network failures.
uploader.setDirectUploadEnabled(false);

MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() {
Expand Down Expand Up @@ -146,10 +103,8 @@ public void progressChanged(MediaHttpUploader uploader) throws IOException {
};
uploader.setProgressListener(progressListener);

// Call the API and upload the video.
Video returnedVideo = videoInsert.execute();

// Print data about the newly inserted video from the API response.
System.out.println("\n================== Returned Video ==================\n");
log.info("\n================== Returned Video ==================\n");
log.info(" - Id: {}", returnedVideo.getId());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import com.gamemoonchul.domain.entity.Member;
import com.gamemoonchul.domain.entity.redis.RedisMember;
import com.gamemoonchul.domain.enums.MemberRole;
import com.gamemoonchul.infrastructure.web.dto.response.MemberResponseDto;
import com.gamemoonchul.infrastructure.web.dto.response.MemberResponse;

import java.time.LocalDateTime;
import java.util.Optional;
Expand All @@ -13,39 +13,39 @@
public class MemberConverter {
private static String randomNickname() {
return UUID.randomUUID()
.toString()
.substring(0, 30);
.toString()
.substring(0, 30);
}

public static RedisMember toRedisMember(OAuth2UserInfo userInfo) {
return RedisMember.builder()
.name(userInfo.getName())
.provider(userInfo.getProvider())
.identifier(userInfo.getIdentifier())
.nickname(userInfo.getNickname())
.email(userInfo.getEmail())
.picture(userInfo.getProfileImageUrl())
.birth(null)
.build();
.name(userInfo.getName())
.provider(userInfo.getProvider())
.identifier(userInfo.getIdentifier())
.nickname(userInfo.getNickname())
.email(userInfo.getEmail())
.picture(userInfo.getProfileImageUrl())
.birth(null)
.build();
}

public static Member redisMemberToEntity(RedisMember redisMember) {
String nickname = ifNicknameNotExistGetRandom(redisMember
.getNickname());
.getNickname());

Member member = Member.builder()
.role(MemberRole.USER)
.name(redisMember.getName())
.identifier(redisMember.getIdentifier())
.provider(redisMember.getProvider())
.nickname(nickname)
.privacyAgreed(true)
.privacyAgreedAt(LocalDateTime.now())
.score(0.0)
.email(redisMember.getEmail())
.picture(redisMember.getPicture())
.birth(null)
.build();
.role(MemberRole.USER)
.name(redisMember.getName())
.identifier(redisMember.getIdentifier())
.provider(redisMember.getProvider())
.nickname(nickname)
.privacyAgreed(true)
.privacyAgreedAt(LocalDateTime.now())
.score(0.0)
.email(redisMember.getEmail())
.picture(redisMember.getPicture())
.birth(null)
.build();
return member;
}

Expand All @@ -57,15 +57,15 @@ private static String ifNicknameNotExistGetRandom(String currentNickname) {
return nickname.get();
}

public static MemberResponseDto toResponseDto(Member entity) {
return MemberResponseDto.builder()
.id(entity.getId())
.name(entity.getName())
.nickname(entity.getNickname())
.email(entity.getEmail())
.privacyAgreed(entity.isPrivacyAgreed())
.picture(entity.getPicture())
.score(entity.getScore())
.build();
public static MemberResponse toResponseDto(Member entity) {
return MemberResponse.builder()
.id(entity.getId())
.name(entity.getName())
.nickname(entity.getNickname())
.email(entity.getEmail())
.privacyAgreed(entity.isPrivacyAgreed())
.picture(entity.getPicture())
.score(entity.getScore())
.build();
}
}
Original file line number Diff line number Diff line change
@@ -1,19 +1,79 @@
package com.gamemoonchul.application.converter;

import com.gamemoonchul.common.util.StringUtils;
import com.gamemoonchul.domain.entity.Member;
import com.gamemoonchul.domain.entity.Post;
import com.gamemoonchul.domain.entity.redis.RedisPostDetail;
import com.gamemoonchul.infrastructure.web.dto.request.PostUploadRequest;
import com.gamemoonchul.infrastructure.web.dto.response.MatchGameResponse;
import com.gamemoonchul.infrastructure.web.dto.response.VoteRatioResponse;

import java.util.HashMap;
import java.util.List;
import java.util.Optional;

public class PostConverter {
public static Post requestToEntity(PostUploadRequest request, Member member) {
Post entity = Post.builder()
.title(request.title())
.videoUrl(request.videoUrl())
.thumbnailUrl(request.thumbnailUrl())
.content(request.content())
.tags(request.tags())
.build();
entity.setMember(member);
.title(request.title())
.videoUrl(request.videoUrl())
.thumbnailUrl(request.thumbnailUrl())
.content(request.content())
.tags(request.tags())
.member(member)
.build();
return entity;
}

public static RedisPostDetail toCache(Post post) {
return RedisPostDetail.builder()
.id(post.getId())
.author(MemberConverter.toResponseDto(post.getMember()))
.videoUrl(post.getVideoUrl())
.thumbnailUrl(post.getThumbnailUrl())
.commentCount(post.getCommentCount())
.title(post.getTitle())
.content(post.getContent())
.timesAgo(StringUtils.getTimeAgo(post.getCreatedAt()))
.viewCount(post.getViewCount())
.voteDetail(getVoteDetail(post))
.build();
}

private static List<VoteRatioResponse> getVoteDetail(Post post) {
HashMap<Long, Double> voteRatioMap = new HashMap<>();
post.getVoteOptions()
.forEach(vo -> {
voteRatioMap.put(vo.getId(), 0.0);
Optional.ofNullable(vo.getVotes())
.ifPresent(votes -> {
votes.forEach(v -> voteRatioMap.put(v.getId(), 0.0));
});
});

Double totalVoteCnt = voteRatioMap.values()
.stream()
.mapToDouble(Double::doubleValue)
.sum();

voteRatioMap.forEach((k, v) -> {
if (totalVoteCnt == 0) {
voteRatioMap.put(k, 0.0);
} else {
voteRatioMap.put(k, (v / totalVoteCnt) * 100);
}
});

List<VoteRatioResponse> result = post.getVoteOptions()
.stream()
.map(vo -> {
Double voteRatio = voteRatioMap.get(vo.getId());
MatchGameResponse.MatchUserResponse matchUserResponse = MatchGameResponse.MatchUserResponse.toResponseVoId(vo.getMatchUser(), vo.getId());
return new VoteRatioResponse(matchUserResponse, voteRatio);
})
.toList();

return result;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,25 @@

import com.gamemoonchul.domain.entity.riot.MatchGame;
import com.gamemoonchul.domain.model.vo.riot.MatchRecord;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

@Service
public class MatchGameConverter {

public MatchGame toMatchGame(MatchRecord matchVO) {
public static MatchGame toMatchGame(MatchRecord matchVO) {
MatchGame entity = MatchGame.builder()
.gameId(matchVO.metadata().matchId())
.gameDuration(matchVO.info().gameDuration())
.gameMode(matchVO.info().gameMode())
.gameCreation(convertUnixToUtcTime(matchVO.info().gameCreation()))
.build();
.gameId(matchVO.metadata().matchId())
.gameDuration(matchVO.info().gameDuration())
.gameMode(matchVO.info().gameMode())
.gameCreation(convertUnixToUtcTime(matchVO.info().gameCreation()))
.build();

return entity;
}

public String convertUnixToUtcTime(long unixTimestamp) {
public static String convertUnixToUtcTime(long unixTimestamp) {
Instant instant = Instant.ofEpochMilli(unixTimestamp);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'").withZone(ZoneId.of("UTC"));
String utcTime = formatter.format(instant);
Expand Down
Loading

0 comments on commit 4011735

Please sign in to comment.