WebFlux添加阻止逻辑

时间:2019-07-09 08:46:10

标签: spring-boot reactive-programming spring-webflux project-reactor

我想知道如何在创建新对象之前进行一些验证检查吗?

@Override
public Mono<Child> create(CreateChildRequest specs) {

    final String parentId = specs.getParentId();
    // TODO: Check if parent exists
    // parentRepository.getById(parentId) -> returns Mono<Parent>

    final Child newChild = new Child(specs.getParentId(), specs.getName());
    return childRepository.insert(newChild)
            .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.BAD_REQUEST, "Failed to create child")));
}

如何以非阻塞方式添加验证检查?

2 个答案:

答案 0 :(得分:1)

如果您只需要进行简单的无阻塞检查,即检查某些字段(或者通常不需要播放其他Mono / Flux),则可以在{{1} }运算符,并轻松提取到另一种方法。在此块中引发的任何异常都将转换为doOnNext

Mono.error

如果执行检查需要涉及另一个final String parentId = specs.getParentId(); parentRepository.getById(parentId) .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.BAD_REQUEST, "Parent does not exist"))) .doOnNext(parent -> { if (parent.getSomeField() == null) { //this can be easily extracted for readability throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Some field must not be null"); } }) .then(Mono.just(new Child(specs.getParentId(), specs.getName())) .flatMap(childRepository::insert) .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.BAD_REQUEST, "Failed to create child"))); / Mono(例如,调用另一个Web服务),则将需要使用“订阅”运算符,例如FluxflatMap

zip

答案 1 :(得分:0)

也许是这样,没有运行代码,但是您可以理解它的要旨。

@Override
public Mono<Child> create(CreateChildRequest specs) {

    final String parentId = specs.getParentId();
    return parentRepository.getById(parentId)
        .doOnSuccess(parent -> {
            verify(parent).doOnSuccess(() -> {
                childRepository.insert(newChild).doOnError(throwable -> {
                    throw new ResponseStatusException(
                        HttpStatus.BAD_REQUEST,
                        "Failed to create child")
                }).doOnError(throwable -> {
                    // some error handling here if not passing validation.
                })
            })
        })
}

private Mono<Void> verify(Parent parent) {

    if(parent == null)
        return Mono.error(// some error here);
    else
        Mono.empty();
}