I need help with Vavr in Java. I have a business process to update a book entity and I want to make validations before every update.
Steps:
- Request from RestController with Data to make Update as
BookUpdateDto. - Try to find
BookById; return Book if exists or return Either withBOOK_NOT_FOUND. - I make mapping from
BookUpdateDtotoBookCreateDtoand validate. - My validation return
Validation<Seq<String>, BookCreateDto>and that's my problem. - My question is: How I could pack my errors from validation with business error when a book does not exist?
public Either<BookError, BookCreateDto> updateBookById(final Long bookId, final BookUpdateDto toUpdate) {
return findBookById(bookId)
.toEither(BOOK_NOT_FOUND)
.map(Book::response)
.map(bookValidation::validate)
.map(book -> book.mapToUpdate(toUpdate))
.map(book -> book.update(toUpdate))
.map(book -> bookRepository.save(book).response());
}
I do not know how to map my errors from validation and domain error that BOOK_NOT_FOUND in empty space in code. Or maybe my architecture to solve my problem is wrong.
It looks like
Validation.toEithercombined with aflatMapcould do the trick.The toEither changes the
Validationinto anEither<List<String>, BookCreateDto>and themapLefton that either changes the left side of the either fromList<String>to aBookError.The
validationErrorsToBookErrorwould be a function that is responsible for turning a list of validations into aBookError. Probably something along these lines: