Loading...

Spring/Tistory / / 2022. 5. 2. 10:33

블로그-V3. 서비스 의존관계 분리 및 메서드화

반응형

DB와 관련된 로직은 서비스파일에 만들어준다.

복잡하게 if문에 if문으로 적힌 코드를 분리시켜 메서드화시킬것이다.

 

private로 메서드를 만들어 내부에서만 호출가능하게 만들어보자.

 

크게 3가지로 코드를 분리시킬 수 있다.

 

1. postId로 게시글 찾기

// 책임 : 로그인 유저가 게시글의 주인인지 확인.
private boolean authCheck(Integer pageOwnerId, Integer principalId) {
    boolean isAuth = false;
    if (principalId == pageOwnerId) {
        isAuth = true;
    } else {
        isAuth = false;
    }
    return isAuth;
}

 

2. 로그인 한 유저가 게시글의 주인인지 확인하기

// 책임 : 로그인 유저가 게시글의 주인인지 확인.
private boolean authCheck(Integer pageOwnerId, Integer principalId) {
    boolean isAuth = false;
    if (principalId == pageOwnerId) {
        isAuth = true;
    } else {
        isAuth = false;
    }
    return isAuth;
}

 

3. 방문자 수 증가하기

// 책임 : 방문자수 증가
private Visit visitIncrease(Integer pageOwnerId) {
    Optional<Visit> visitOp = visitRepository.findById(pageOwnerId);
    if (visitOp.isPresent()) {
        Visit visitEntity = visitOp.get();
        Long totalCount = visitEntity.getTotalCount();
        visitEntity.setTotalCount(totalCount + 1);
        return visitEntity;
    } else {
        log.error("미친 심각", "회원가입할때 Visit이 안 만들어지는 심각한 오류가 있습니다.");
        // sms 메시지 전송
        // email 전송
        // file 쓰기
        throw new CustomException("일시적 문제가 생겼습니다. 관리자에게 문의해주세요.");
    }
}

 

메서드를 분리시키고 나면 포스트 서비스의 로직이 훨씬 가독성이 좋고 깔끔해진다.

다음과 같이 원래 코드를 수정할 수 있다.

 

분리 전

@Transactional
public PostDetailRespDto 게시글상세보기(Integer id, User principal) {
    PostDetailRespDto postDetailRespDto = new PostDetailRespDto();

    // 해당 페이지의 postId를 찾아서
    Integer postId = id;
    // 해당 페이지의 주인 userId가 무엇인지 알아야함
    Integer pageOwnerId = null;
    // 로그인한 사용자의 userId를 알아야함
    Integer loginUserId = principal.getId();

    Optional<Post> postOp = postRepository.findById(id);

    if (postOp.isPresent()) {

        Post postEntity = postOp.get();
        postDetailRespDto.setPost(postEntity);

        pageOwnerId = postEntity.getUser().getId();

        if (pageOwnerId == loginUserId) {
            postDetailRespDto.setPageOwner(true);
        } else {
            postDetailRespDto.setPageOwner(false);
        }

        // 방문자 카운트 증가
        Optional<Visit> visitOp = visitRepository.findById(postEntity.getUser().getId());

        if (visitOp.isPresent()) {
            Visit visitEntity = visitOp.get();
            Long totalCount = visitEntity.getTotalCount();
            visitEntity.setTotalCount(totalCount + 1);
        } else {
            log.error("미친 심각", "회원가입할 때 visit이 안만들어지는 심각한 오류가 있습니다.");
            // sms 메시지, email 전송, file 쓰기
            throw new CustomException("일시적 문제가 생겼습니다. 관리자에게 문의해주세요.");
        }
        return postDetailRespDto;
    } else {
        throw new CustomException("해당 게시글을 찾을 수 없습니다.");
    }

 

분리 후

@Transactional
public PostDetailRespDto 게시글상세보기(Integer id, User principal) {

    PostDetailRespDto postDetailRespDto = new PostDetailRespDto();

    // 게시글 찾기
    Post postEntity = basicFindById(id);

    // 권한체크
    boolean isAuth = authCheck(postEntity.getUser().getId(), principal.getId());

    // 방문자 카운트 증가
    visitIncrease(postEntity.getUser().getId());

    // 리턴값 만들기
    postDetailRespDto.setPost(postEntity);
    postDetailRespDto.setPageOwner(isAuth);

    return postDetailRespDto;
}

 

게시글상세보기 메서드와 같이 게시글목록보기, 게시글삭제 등 포스트서비스 코드를 수정해보자.

 

 

 

[출처]

 

https://cafe.naver.com/metacoding

 

메타코딩 : 네이버 카페

코린이들의 궁금증

cafe.naver.com

메타 코딩 유튜브

https://www.youtube.com/c/%EB%A9%94%ED%83%80%EC%BD%94%EB%94%A9

 

메타코딩

문의사항 : getinthere@naver.com 인스타그램 : https://www.instagram.com/meta4pm 깃헙 : https://github.com/codingspecialist 유료강좌 : https://www.easyupclass.com

www.youtube.com

 
반응형