我的代码中有以下方法。正如您所看到的,它包含嵌套映射,用于检查数据库中是否已存在用户名。我想以更优雅的方式写它,但我不知道如何。有什么建议吗?
@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
,但您需要反转现有检查。这个想法是让用户
在过滤器
不存在时传递该过滤器,从而可以创建:
//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)
关于java - Reactor - 为两个流编写值检查的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52007975/