如何使用 Validation 和 DomainError 来映射 Either 的左侧与两种不同类型的错误

问题描述 投票:0回答:1

我需要有关 Java 中 Vavr 的帮助。 我有一个更新图书实体的业务流程,并且我想在每次更新之前进行验证。

步骤:

  1. 来自 RestController 的带有数据的请求,将更新设为
    BookUpdateDto
  2. 尝试找到
    BookById
    ;如果存在则返回 Book 或使用
    BOOK_NOT_FOUND
    .
  3. 返回 Either
  4. 我从
    BookUpdateDto
    BookCreateDto
    进行映射并验证。
  5. 我的验证返回
    Validation<Seq<String>, BookCreateDto>
    ,这就是我的问题。
  6. 我的问题是:当一本书不存在时,如何将验证中的错误与业务错误打包在一起?
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());
    }

我不知道如何将验证中的错误和域错误映射到代码中的空白处。或者也许我解决问题的架构是错误的。

    

java spring-boot validation vavr
1个回答
0
投票
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

© www.soinside.com 2019 - 2024. All rights reserved.