简体   繁体   中英

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. The idea is to have the user pass the filter when it doesn't exist and thus can be created :

//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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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