[새싹] 현대IT&E 240125 2차 프로젝트 - SpringBoot 다이어리 / 친구 Rest API 리팩토링

최정윤·2024년 1월 26일
0

새싹

목록 보기
60/67
post-custom-banner

백엔드

다이어리 RestAPI 수정

CRUD 리팩토링

controller/dto/request/DiaryCreateRequest.java

package kr.sesac.aoao.server.diary.controller.dto.request;

import java.time.LocalDateTime;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.RequiredArgsConstructor;

@Getter
@RequiredArgsConstructor
public class DiaryCreateRequest {
	private final Long userId;
	private final LocalDateTime date;
	private final String content;
}

controller/dto/request/DiaryUpdateRequest.java

package kr.sesac.aoao.server.diary.controller.dto.request;

import java.time.LocalDateTime;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.RequiredArgsConstructor;

@Getter
@RequiredArgsConstructor
public class DiaryUpdateRequest {
	private final String content;
}

controller/dto/response/GetDiaryResponse.java

package kr.sesac.aoao.server.diary.controller.dto.response;

import java.time.LocalDateTime;

import lombok.Getter;
import lombok.RequiredArgsConstructor;

@Getter
@RequiredArgsConstructor
public class GetDiaryResponse {

	private final Long id;
	private final String content;
	private final LocalDateTime date;

}

controller/DiaryController.java

package kr.sesac.aoao.server.diary.controller;

import java.net.URI;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import kr.sesac.aoao.server.diary.controller.dto.request.DiaryCreateRequest;
import kr.sesac.aoao.server.diary.controller.dto.request.DiaryUpdateRequest;
import kr.sesac.aoao.server.diary.controller.dto.response.GetDiaryResponse;
import kr.sesac.aoao.server.diary.service.DiaryService;
import kr.sesac.aoao.server.global.controller.dto.response.ApplicationResponse;
import lombok.RequiredArgsConstructor;

/**
 * @since 2024.01.23
 * @author 최정윤
 */
@RestController
@RequestMapping("/diary")
@RequiredArgsConstructor
public class DiaryController {

	private final DiaryService diaryService;

	/**
	 * 다이어리 작성
	 * @since 2024.01.23
	 * @return createDiary
	 * @author 최정윤
	 */
	@PostMapping
	public ResponseEntity<ApplicationResponse<Void>> createDiary(@RequestParam Long userId, @PathVariable Long date, @RequestBody DiaryCreateRequest request) {
		Long diaryId = diaryService.createDiary(userId, date, request);
		return ResponseEntity.created(URI.create("/diary/" + diaryId)).build();
	}

	/**
	 * 다이어리 정보 조회
	 * @since 2024.01.23
	 * @return getDiaryInfo
	 * @author 최정윤
	 * 완료
	 */
	@GetMapping("/")
	public ResponseEntity<ApplicationResponse<GetDiaryResponse>> getDiaryInfo(@RequestParam Long userId) {
		GetDiaryResponse userDiaryResponse = diaryService.getDiaryInfo(userId);
		return ResponseEntity.ok(ApplicationResponse.success(userDiaryResponse));
	}

	/**
	 * 다이어리 수정
	 * @since 2024.01.23
	 * @return updateDiary
	 * @author 최정윤
	 */
	@PostMapping("/{diaryId}")
	public ResponseEntity<ApplicationResponse<Void>> updateDiary(
		@RequestParam Long userId, @PathVariable Long diaryId,
		@RequestBody DiaryUpdateRequest request) {
		diaryService.updateDiary(userId, diaryId, request);
		return ResponseEntity.ok().build();
	}

	/**
	 * 다이어리 삭제
	 * @since 2024.01.23
	 * @return deleteDiary
	 * @author 최정윤
	 */
	@DeleteMapping("/{diaryId}")
	public ResponseEntity<ApplicationResponse<Void>> deleteDiary(
		@RequestParam Long userId, @PathVariable Long diaryId) {
		diaryService.deleteDiary(userId, diaryId);
		return ResponseEntity.noContent().build();
	}

}

donmain/Diary.java

package kr.sesac.aoao.server.diary.domain;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;

import lombok.AllArgsConstructor;
import lombok.Getter;

/**
 * @since 2024.01.23
 * @author 최정윤
 */
@Getter
@AllArgsConstructor
public class Diary {
	private final Long diaryId; // 일기 id
	private final String content; // 일기 내용
	private final LocalDateTime date; // 캘린더 설정 날짜
	private final Long userId; // 일기 작성자 id
	private final LocalDateTime createdAt; // 일기 생성 일자
	private final LocalDateTime updateAt; // 일기 수정 일자

}

exception/DiaryErrorCode.java

package kr.sesac.aoao.server.diary.exception;

import org.springframework.http.HttpStatus;

import kr.sesac.aoao.server.global.exception.ErrorCode;
import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
public enum DiaryErrorCode implements ErrorCode {
	NO_DIARY(HttpStatus.BAD_REQUEST, "일기 정보가 존재하지 않습니다."),
	EMPTY_DIARY(HttpStatus.BAD_REQUEST, "내용이 비어있습니다.");

	private final HttpStatus httpStatus;
	private final String message;
	@Override
	public HttpStatus getStatusCode() {
		return httpStatus;
	}

	@Override
	public String getMessage() {
		return message;
	}
}

repository/DiaryEntity.java

package kr.sesac.aoao.server.diary.repository;

import java.time.LocalDate;
import java.time.LocalDateTime;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToOne;
import jakarta.persistence.Table;
import kr.sesac.aoao.server.diary.controller.dto.request.DiaryCreateRequest;
import kr.sesac.aoao.server.global.entity.BaseEntity;
import kr.sesac.aoao.server.global.exception.ApplicationException;
import kr.sesac.aoao.server.todo.exception.TodoFolderErrorCode;
import kr.sesac.aoao.server.todo.repository.PaletteEntity;
import kr.sesac.aoao.server.user.repository.UserEntity;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@Entity
@Table(name = "diary")
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor
public class DiaryEntity extends BaseEntity {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id; // 다이어리 아이디

	@Column
	private String content; // 일기 내용

	@Column
	private LocalDateTime date; // 캘린더 설정 날짜

	@ManyToOne
	@JoinColumn(name = "user_id")
	private UserEntity user; // 일기 작성자

	public DiaryEntity(String content, LocalDateTime date, UserEntity user) {
		this.content = content;
		this.date = date;
		this.user = user;
	}

	public void diaryUpdate(UserEntity user, String content) {
		validateUserIsWriter(user);
		this.content = content;
	}

	public void validateUserIsWriter(UserEntity user) {
		if (!this.user.isWriter(user)) {
			throw new ApplicationException(TodoFolderErrorCode.IS_NOT_WRITER);
		}
	}

}

repository/DiaryJpaRepository.java

package kr.sesac.aoao.server.diary.repository;

import java.util.Optional;

import org.springframework.data.jpa.repository.JpaRepository;

import kr.sesac.aoao.server.dino.repository.DinoEntity;
import kr.sesac.aoao.server.user.repository.UserEntity;

public interface DiaryJpaRepository extends JpaRepository <DiaryEntity, Long> {

	Optional<DiaryEntity> findByUser(UserEntity user);
}

service/DiaryService.java

package kr.sesac.aoao.server.diary.service;

import org.springframework.stereotype.Service;

import kr.sesac.aoao.server.diary.controller.dto.request.DiaryCreateRequest;
import kr.sesac.aoao.server.diary.controller.dto.request.DiaryUpdateRequest;
import kr.sesac.aoao.server.diary.controller.dto.response.GetDiaryResponse;

@Service
public interface DiaryService {

	GetDiaryResponse getDiaryInfo(Long userId);

	Long createDiary(Long userId, Long date, DiaryCreateRequest request);

	void updateDiary(Long userId, Long diaryId, DiaryUpdateRequest request);

	void deleteDiary(Long userId, Long diaryId);


}

DiaryServiceImpl.java

package kr.sesac.aoao.server.diary.service;

import org.springframework.stereotype.Service;
import jakarta.transaction.Transactional;
import kr.sesac.aoao.server.diary.controller.dto.request.DiaryCreateRequest;
import kr.sesac.aoao.server.diary.controller.dto.request.DiaryUpdateRequest;
import kr.sesac.aoao.server.diary.controller.dto.response.GetDiaryResponse;
import kr.sesac.aoao.server.diary.exception.DiaryErrorCode;
import kr.sesac.aoao.server.diary.repository.DiaryEntity;
import kr.sesac.aoao.server.diary.repository.DiaryJpaRepository;
import kr.sesac.aoao.server.global.exception.ApplicationException;
import kr.sesac.aoao.server.user.exception.UserErrorCode;
import kr.sesac.aoao.server.user.repository.UserEntity;
import kr.sesac.aoao.server.user.repository.UserJpaRepository;
import lombok.RequiredArgsConstructor;

/**
 * @since 2024.01.23
 * @author 최정윤
 */
@Service
@RequiredArgsConstructor
@Transactional
public class DiaryServiceImpl implements DiaryService{

	private final DiaryJpaRepository diaryJpaRepository;
	private final UserJpaRepository userRepository;
	private final DiaryJpaRepository diaryRepository;

	private GetDiaryResponse result(DiaryEntity diary){
		return new GetDiaryResponse(
			diary.getUser().getId(),
			diary.getContent(),
			diary.getDate()
		);
	}

	/**
	 * 다이어리 작성
	 * @since 2024.01.23
	 * @return saveDiary
	 * @author 최정윤
	 */
	@Override
	public Long createDiary(Long userId, Long date, DiaryCreateRequest request) {
		UserEntity savedUser = findUserById(userId);

		DiaryEntity diaryEntity = new DiaryEntity(
			request.getContent(),
			request.getDate(),
			savedUser
		);
		return diaryJpaRepository.save(diaryEntity).getId();
	}

	/**
	 * 다이어리 조회
	 * @since 2024.01.123
	 * @parameter userId
	 * @return GetDiaryResponse
	 * @author 최정윤
	 */
	@Override
	public GetDiaryResponse getDiaryInfo(Long userId) {
		UserEntity user = userRepository.findById(userId)
			.orElseThrow(() -> new ApplicationException(UserErrorCode.NOT_FOUND_USER));
		DiaryEntity diary = diaryRepository.findByUser(user)
			.orElseThrow(() -> new ApplicationException(DiaryErrorCode.NO_DIARY));
		return result(diary);
	}

	/**
	 * 다이어리 수정
	 * @since 2024.01.23
	 * @return updateDiary
	 * @author 최정윤
	 */

	@Override
	public void updateDiary(Long userId, Long diaryId, DiaryUpdateRequest request) {
		UserEntity savedUser = findUserById(userId);
		DiaryEntity savedDiary = findDiaryById(diaryId);

		savedDiary.diaryUpdate(savedUser, request.getContent());
	}


	/**
	 * 다이어리 삭제
	 * @since 2024.01.23
	 * @return deleteDiary
	 * @author 최정윤
	 */
	@Override
	public void deleteDiary(Long userId, Long diaryId) {
		UserEntity savedUser = findUserById(userId);
		DiaryEntity savedDiary = findDiaryById(diaryId);

		savedDiary.validateUserIsWriter(savedUser);
		diaryJpaRepository.deleteById(savedDiary.getId());
	}

	private UserEntity findUserById(Long userId) {
		return userRepository.findById(userId)
			.orElseThrow(() -> new ApplicationException(UserErrorCode.NOT_EXIST));
	}

	private DiaryEntity findDiaryById(Long diaryId) {
		return diaryRepository.findById(diaryId)
			.orElseThrow(() -> new ApplicationException(DiaryErrorCode.NO_DIARY));
	}

}

API 통신 테스트 완료 코드

DiaryCreateRequest.java

package kr.sesac.aoao.server.diary.controller.dto.request;

import lombok.Getter;
import lombok.RequiredArgsConstructor;

@Getter
@RequiredArgsConstructor
public class DiaryCreateRequest {
	private final String date;
	private final String content;
}

DiaryUpdateRequest.java

package kr.sesac.aoao.server.diary.controller.dto.request;

import lombok.Getter;
import lombok.RequiredArgsConstructor;

@Getter
@RequiredArgsConstructor
public class DiaryUpdateRequest {
	private final String content;
	private final boolean flag;
}

GetDiaryResponse.java

package kr.sesac.aoao.server.diary.controller.dto.response;

import java.time.LocalDateTime;

import lombok.Getter;
import lombok.RequiredArgsConstructor;

@Getter
@RequiredArgsConstructor
public class GetDiaryResponse {
	private final Long diaryId;
	private final String content;
	private final LocalDateTime date;

}

DiaryController.java

package kr.sesac.aoao.server.diary.controller;

import java.net.URI;

import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import kr.sesac.aoao.server.diary.controller.dto.request.DiaryCreateRequest;
import kr.sesac.aoao.server.diary.controller.dto.request.DiaryUpdateRequest;
import kr.sesac.aoao.server.diary.controller.dto.response.GetDiaryResponse;
import kr.sesac.aoao.server.diary.service.DiaryService;
import kr.sesac.aoao.server.global.controller.dto.response.ApplicationResponse;
import kr.sesac.aoao.server.user.jwt.UserCustomDetails;
import lombok.RequiredArgsConstructor;

/**
 * @since 2024.01.23
 * @author 최정윤
 */
@RestController
@RequestMapping("/diary")
@RequiredArgsConstructor
public class DiaryController {

	private final DiaryService diaryService;

	/**
	 * 다이어리 작성
	 * @since 2024.01.23
	 * @return createDiary
	 * @author 최정윤
	 */
	@PostMapping
	public ResponseEntity<ApplicationResponse<String>> createDiary(@AuthenticationPrincipal UserCustomDetails userDetails,
		@RequestBody DiaryCreateRequest request) {
		Long diaryId = diaryService.createDiary(userDetails.getUserEntity().getId(), request);
		return ResponseEntity.ok(ApplicationResponse.success(diaryId + "번 다이어리가 생성되었습니다."));

	}

	/**
	 * 다이어리 정보 조회
	 * @since 2024.01.23
	 * @return getDiaryInfo
	 * @author 최정윤
	 * 완료
	 */
	@GetMapping
	public ResponseEntity<ApplicationResponse<GetDiaryResponse>> getDiaryInfo(
		@AuthenticationPrincipal UserCustomDetails userDetails, @RequestParam("date") String date) {
		GetDiaryResponse userDiaryResponse = diaryService.getDiaryInfo(userDetails.getUserEntity().getId(), date);
		return ResponseEntity.ok(ApplicationResponse.success(userDiaryResponse));
	}

	/**
	 * 다이어리 수정
	 * @since 2024.01.23
	 * @return updateDiary
	 * @author 최정윤
	 */
	@PostMapping("/{diaryId}")
	public ResponseEntity<ApplicationResponse<String>> updateDiary(
		@AuthenticationPrincipal UserCustomDetails userDetails,
		@PathVariable Long diaryId,
		@RequestBody DiaryUpdateRequest request) {
		diaryService.updateDiary(userDetails.getUserEntity().getId(), diaryId, request);
		return ResponseEntity.ok(ApplicationResponse.success(diaryId + "번 다이어리가 수정되었습니다."));
	}

	/**
	 * 다이어리 삭제
	 * @since 2024.01.23
	 * @return deleteDiary
	 * @author 최정윤
	 */
	@DeleteMapping("/{diaryId}")
	public ResponseEntity<ApplicationResponse<String>> deleteDiary(
		@AuthenticationPrincipal UserCustomDetails userDetails, @PathVariable Long diaryId) {
		diaryService.deleteDiary(userDetails.getUserEntity().getId(), diaryId);
		return ResponseEntity.ok(ApplicationResponse.success(diaryId + "번 다이어리가 삭제되었습니다."));
	}

}

Diary.java

package kr.sesac.aoao.server.diary.domain;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;

import lombok.AllArgsConstructor;
import lombok.Getter;

/**
 * @since 2024.01.23
 * @author 최정윤
 */
@Getter
@AllArgsConstructor
public class Diary {
	private final Long diaryId; // 일기 아이디
	private final String content; // 일기 내용
	private final LocalDateTime date; // 캘린더 설정 날짜
	private final Long userId; // 일기 작성자 아이디
	private final LocalDateTime createdAt; // 일기 생성 일자
	private final LocalDateTime updateAt; // 일기 수정 일자
}

DiaryErrorCode.java

package kr.sesac.aoao.server.diary.exception;

import org.springframework.http.HttpStatus;

import kr.sesac.aoao.server.global.exception.ErrorCode;
import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
public enum DiaryErrorCode implements ErrorCode {
	NO_DIARY(HttpStatus.BAD_REQUEST, "일기 정보가 존재하지 않습니다."),
	EMPTY_DIARY(HttpStatus.BAD_REQUEST, "내용이 비어있습니다.");

	private final HttpStatus httpStatus;
	private final String message;
	@Override
	public HttpStatus getStatusCode() {
		return httpStatus;
	}

	@Override
	public String getMessage() {
		return message;
	}
}

DiaryEntity.java

package kr.sesac.aoao.server.diary.repository;

import java.time.LocalDateTime;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import kr.sesac.aoao.server.global.entity.BaseEntity;
import kr.sesac.aoao.server.global.exception.ApplicationException;
import kr.sesac.aoao.server.todo.exception.TodoFolderErrorCode;
import kr.sesac.aoao.server.user.repository.UserEntity;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@Entity
@Table(name = "diary")
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor
public class DiaryEntity extends BaseEntity {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id; // 다이어리 아이디

	@Column
	private String content; // 일기 내용

	@Column
	private LocalDateTime date; // 캘린더 설정 날짜

	@ManyToOne
	@JoinColumn(name = "user_id")
	private UserEntity user; // 일기 작성자

	public DiaryEntity(String content, LocalDateTime date, UserEntity user) {
		this.content = content;
		this.date = date;
		this.user = user;
	}

	public void diaryUpdate(UserEntity user, String content) {
		validateUserIsWriter(user);
		this.content = content;
	}

	public void validateUserIsWriter(UserEntity user) {
		if (!this.user.isWriter(user)) {
			throw new ApplicationException(TodoFolderErrorCode.IS_NOT_WRITER);
		}
	}

}

DiaryJpaRepository.java

package kr.sesac.aoao.server.diary.repository;

import java.time.LocalDateTime;
import java.util.Optional;

import org.springframework.data.jpa.repository.JpaRepository;

import kr.sesac.aoao.server.user.repository.UserEntity;

public interface DiaryJpaRepository extends JpaRepository<DiaryEntity, Long> {

	Optional<DiaryEntity> findByUser(UserEntity user);

	Optional<DiaryEntity> findByUserAndDate(UserEntity user, LocalDateTime date);
}

DiaryService.java

package kr.sesac.aoao.server.diary.service;

import org.springframework.stereotype.Service;

import kr.sesac.aoao.server.diary.controller.dto.request.DiaryCreateRequest;
import kr.sesac.aoao.server.diary.controller.dto.request.DiaryUpdateRequest;
import kr.sesac.aoao.server.diary.controller.dto.response.GetDiaryResponse;

@Service
public interface DiaryService {

	GetDiaryResponse getDiaryInfo(Long userId, String date);

	Long createDiary(Long userId, DiaryCreateRequest request);

	void updateDiary(Long userId, Long diaryId, DiaryUpdateRequest request);

	void deleteDiary(Long userId, Long diaryId);

}

DiaryServiceImpl.java

package kr.sesac.aoao.server.diary.service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

import org.springframework.stereotype.Service;

import jakarta.transaction.Transactional;
import kr.sesac.aoao.server.diary.controller.dto.request.DiaryCreateRequest;
import kr.sesac.aoao.server.diary.controller.dto.request.DiaryUpdateRequest;
import kr.sesac.aoao.server.diary.controller.dto.response.GetDiaryResponse;
import kr.sesac.aoao.server.diary.exception.DiaryErrorCode;
import kr.sesac.aoao.server.diary.repository.DiaryEntity;
import kr.sesac.aoao.server.diary.repository.DiaryJpaRepository;
import kr.sesac.aoao.server.global.exception.ApplicationException;
import kr.sesac.aoao.server.user.exception.UserErrorCode;
import kr.sesac.aoao.server.user.repository.UserEntity;
import kr.sesac.aoao.server.user.repository.UserJpaRepository;
import lombok.RequiredArgsConstructor;

/**
 * @since 2024.01.23
 * @author 최정윤
 */
@Service
@RequiredArgsConstructor
@Transactional
public class DiaryServiceImpl implements DiaryService {

	private final DiaryJpaRepository diaryJpaRepository;
	private final UserJpaRepository userRepository;
	private final DiaryJpaRepository diaryRepository;

	private GetDiaryResponse result(DiaryEntity diary) {
		return new GetDiaryResponse(
			diary.getId(),
			diary.getContent(),
			diary.getDate()
		);
	}

	/**
	 * 다이어리 작성
	 * @since 2024.01.23
	 * @return saveDiary
	 * @author 최정윤
	 */
	@Override
	public Long createDiary(Long userId, DiaryCreateRequest request) {

		// Long 값을 "yyyyMMdd" 형식의 날짜 문자열로 변환
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
		String dateString = String.valueOf(request.getDate());
		LocalDate localDate = LocalDate.parse(dateString, formatter);

		UserEntity savedUser = findUserById(userId);

		DiaryEntity diaryEntity = new DiaryEntity(
			request.getContent(),
			localDate.atStartOfDay(),
			savedUser
		);
		return diaryJpaRepository.save(diaryEntity).getId();
	}

	/**
	 * 다이어리 조회
	 * @since 2024.01.23
	 * @parameter userId
	 * @return GetDiaryResponse
	 * @author 최정윤
	 */
	@Override
	public GetDiaryResponse getDiaryInfo(Long userId, String date) {
		// Long 값을 "yyyyMMdd" 형식의 날짜 문자열로 변환
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
		String dateString = String.valueOf(date);
		LocalDate localDate = LocalDate.parse(dateString, formatter);

		UserEntity user = userRepository.findById(userId)
			.orElseThrow(() -> new ApplicationException(UserErrorCode.NOT_FOUND_USER));
		DiaryEntity diary = diaryRepository.findByUserAndDate(user, localDate.atStartOfDay())
			.orElseThrow(() -> new ApplicationException(DiaryErrorCode.NO_DIARY));

		return result(diary);
	}

	/**
	 * 다이어리 수정
	 * @since 2024.01.23
	 * @return updateDiary
	 * @author 최정윤
	 */

	@Override
	public void updateDiary(Long userId, Long diaryId, DiaryUpdateRequest request) {
		UserEntity savedUser = findUserById(userId);
		DiaryEntity savedDiary = findDiaryById(diaryId);

		savedDiary.diaryUpdate(savedUser, request.getContent());
	}

	/**
	 * 다이어리 삭제
	 * @since 2024.01.23
	 * @return deleteDiary
	 * @author 최정윤
	 */
	@Override
	public void deleteDiary(Long userId, Long diaryId) {
		UserEntity savedUser = findUserById(userId);
		DiaryEntity savedDiary = findDiaryById(diaryId);

		savedDiary.validateUserIsWriter(savedUser);
		diaryJpaRepository.deleteById(savedDiary.getId());
	}

	private UserEntity findUserById(Long userId) {
		return userRepository.findById(userId)
			.orElseThrow(() -> new ApplicationException(UserErrorCode.NOT_EXIST));
	}

	private DiaryEntity findDiaryById(Long diaryId) {
		return diaryRepository.findById(diaryId)
			.orElseThrow(() -> new ApplicationException(DiaryErrorCode.NO_DIARY));
	}

}

좋아요 API 구현

profile
개발 기록장
post-custom-banner

0개의 댓글