我需要有关 Java 中 Vavr 的帮助。 我有一个更新图书实体的业务流程,并且我想在每次更新之前进行验证。
步骤:
BookUpdateDto
。BookById
;如果存在则返回 Book 或使用 BOOK_NOT_FOUND
.BookUpdateDto
到 BookCreateDto
进行映射并验证。Validation<Seq<String>, BookCreateDto>
,这就是我的问题。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());
}
我不知道如何将验证中的错误和域错误映射到代码中的空白处。或者也许我解决问题的架构是错误的。
BOOK_NOT_FOUND
与
Validation.toEither
结合可以做到这一点。toEither 将 flatMap
更改为
Validation
,而 Either 上的 Either<List<String>, BookCreateDto>
将任一者的左侧从 mapLeft
更改为 List<String>
。BookError
public Either<BookError, BookCreateDto> updateBookById(final Long bookId, final BookUpdateDto toUpdate) {
return findBookById(bookId)
.toEither(BOOK_NOT_FOUND)
.map(Book::response)
.map(bookValidation::validate)
// This should perform the desired conversion
.flatMap(validation -> validation.toEither().mapLeft(this::validationErrorsToBookError))
.map(book -> book.mapToUpdate(toUpdate))
.map(book -> book.update(toUpdate))
.map(book -> bookRepository.save(book).response());
}
是一个负责将验证列表转换为
validationErrorsToBookError
的函数。大概是这样的:BookError