Memo API (5)


Get Memo


MemoController

    @GetMapping("/{memoId}")
    @ResponseStatus(HttpStatus.OK)
    fun getMemo(
        @PathVariable memoId: Int
    ) = GetMemoResponse(memoService.getMemo(memoId))
  class GetMemoResponse(
      val memo: GetMemoDto
  )

MemoService

    @Transactional(readOnly = true)
    fun getMemo(memoId: Int): GetMemoDto {
        val memo = memoRepository.findByIdAndIsDeletedIsFalse(memoId).orElseThrow { MemoNotFoundException(memoId) }

        val tags = memo.tags.stream()
            .map {
                GetTagsDto(it)
            }.collect(Collectors.toList())

        val images = memo.images.stream()
            .map {
                GetImagesDto(it)
            }.collect(Collectors.toList())

        return GetMemoDto(memo, tags, images)
    }
  class MemoNotFoundException(memoId: Int) : RuntimeException("${memoId}번 메모가 존재하지 않습니다.")
  class GetTagsDto(tag: Tag) {
      val content = tag.content
  }
  class GetImagesDto(image: Image) {
      val id = image.id!!
      val fileName = image.fileName
  }
  class GetMemoDto(
      memo: Memo,
      val tags: List<GetTagsDto>,
      val images: List<GetImagesDto>
  ) {
      val id = memo.id!!
      val title = memo.title
      val content = memo.content
      val updatedAt = memo.updatedAt
  }
memoIdでmemoをクエリーし、memoがない場合は例外を放出します.
クエリーのmemoのtagsとimagesをそれぞれGetTagsDtoとGetImagesDtoにマッピングし、最後にGetMemoDtoにマッピングして戻ります.

MemoRepository

  fun findByIdAndIsDeletedIsFalse(memoId: Int): Optional<Memo>

MemoExceptionHandler

  @RestControllerAdvice
  @Order(Ordered.HIGHEST_PRECEDENCE)
  class MemoExceptionHandler {
      @ExceptionHandler(MemoNotFoundException::class)
      @ResponseStatus(HttpStatus.NOT_FOUND)
      fun handleMemoNotFound(exception: MemoNotFoundException): ErrorResponse {
          return ErrorResponse(HttpStatus.NOT_FOUND, "Memo-001", exception.message!!)
      }
  }
class ErrorResponse(
    val timeStamp: LocalDateTime,
    val status: Int,
    val error: String,
    val message: String
) {
    constructor(httpStatus: HttpStatus, errorCode: String, message: String) : this(
        timeStamp = LocalDateTime.now(),
        status = httpStatus.value(),
        error = errorCode,
        message = message
    )
}
サービス内のすべての例外はExceptionHandlerで処理されます.
ErrorResponseを作成して、異常が発生した情報を格納します.

Request & Response



存在しないmemoIdを使用してクエリーを行う場合は、エラーレスポンスが返されることを確認できます.