簡體   English   中英

Reactor-編寫兩個流的值檢查的更好方法

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

我的代碼中有以下方法。 如您所見,它包含用於檢查用戶名是否已存在於數據庫中的嵌套映射。 我想以更優雅的方式寫出來,但我不知道如何寫。 有什么建議么?

   @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);
                                    }
                                });
                    }
                })

    }

您可以使用filterWhen ,但是您需要撤銷存在的檢查。 想法是讓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