From 30ad9534cef36ce39b9b96fecd1de91f2b9cf922 Mon Sep 17 00:00:00 2001 From: sarajaned Date: Fri, 11 Aug 2023 21:35:51 +0100 Subject: [PATCH] SD/feat/#59 refactored resource not found in AuthorService --- .../onlinebookstore/author/AuthorService.java | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/online-book-store/src/main/java/com/amigoscode/cohort2d/onlinebookstore/author/AuthorService.java b/online-book-store/src/main/java/com/amigoscode/cohort2d/onlinebookstore/author/AuthorService.java index a17e97c..2992152 100644 --- a/online-book-store/src/main/java/com/amigoscode/cohort2d/onlinebookstore/author/AuthorService.java +++ b/online-book-store/src/main/java/com/amigoscode/cohort2d/onlinebookstore/author/AuthorService.java @@ -36,16 +36,15 @@ public AuthorDTO getAuthorById(Long id) { return AuthorDTOMapper.INSTANCE.modelToDTO( authorDAO.findById(id) .orElseThrow( - () -> new ResourceNotFoundException("Author with id [%s] not found.".formatted(id)))); + () -> getResourceNotFoundException(id))); } public void updateAuthor(Long id, AuthorDTO updateRequest) { // find book - check exists Author existingAuthor = authorDAO.findById(id) - .orElseThrow(() -> new ResourceNotFoundException( - "Author with id [%s] not found.".formatted(id) - )); + .orElseThrow( + () -> getResourceNotFoundException(id)); // check if there are any changes if(AuthorDTOMapper.INSTANCE.modelToDTO(existingAuthor).equals(updateRequest)){ @@ -69,11 +68,19 @@ public void updateAuthor(Long id, AuthorDTO updateRequest) { public void deleteAuthorById(Long id) { // if author does not exist throw - if(!authorDAO.existsAuthorById(id)){ - throw new ResourceNotFoundException("Author with id [%s] not found.".formatted(id)); - } + checkIfAuthorExistsOrThrow(id); //delete authorDAO.deleteAuthorById(id); } + + private void checkIfAuthorExistsOrThrow(Long id) { + if(!authorDAO.existsAuthorById(id)) { + throw getResourceNotFoundException(id); + } + } + + private static ResourceNotFoundException getResourceNotFoundException(Long id) { + return new ResourceNotFoundException("Author with id [%s] not found.".formatted(id)); + } }