简体   繁体   English

Reactor-编写两个流的值检查的更好方法

[英]Reactor - a better way to write value checking for two streams

I have following method in my code. 我的代码中有以下方法。 As you see it contains nested mapping for checking if username already exists in database. 如您所见,它包含用于检查用户名是否已存在于数据库中的嵌套映射。 I want to write that in more elegant way but I don't know how. 我想以更优雅的方式写出来,但我不知道如何写。 Any suggestions? 有什么建议么?

   @Override
    public Mono<User> registerUser(User user) {

      return emailExists(user.getEmail())
                .flatMap(emailExists -> {
                    if(emailExists) {
                        return Mono.error(new EmailExistsException(
                                "There is an account with that email address: "
                                        + user.getEmail() ));
                    } else {
                        return usernameExists(user.getUsername())
                                .flatMap(usernameExists -> {
                                    if(usernameExists) {
                                        return Mono.error(new UsernameExistsException(
                                                "There is an account with that username: "
                                                        + user.getUsername() ));
                                    } else {
                                        return userRepository.save(user);
                                    }
                                });
                    }
                })

    }

You could use filterWhen , but you'd need to reverse the exist checks. 您可以使用filterWhen ,但是您需要撤销存在的检查。 The idea is to have the user pass the filter when it doesn't exist and thus can be created : 想法是让user通过不存在filter ,从而可以创建 filter

//start from the user itself
Mono.just(user)
    //check if it exists, and if so fail the filter => empty mono
    .filterWhen(u -> emailExists(u.getEmail()).map(exist -> !exist))
    //on an empty Mono at this point, we know it's a duplicate email
    .switchIfEmpty(Mono.error(new EmailExistsException(
                "There is an account with that email address: " + user.getEmail() )))
    //now check if username exists, and similarly fail the filter
    .filterWhen(u -> userNameExists(u.getUsername()).map(exist -> !exist))
    //if empty at this point we know it's a duplicate username
    .switchIfEmpty(Mono.error(new UsernameExistsException(
                "There is an account with that username: " + user.getUsername() )))
    //otherwise it's not empty and it means that User can be saved
    .flatMap(userRepository::save)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM