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
,因此可以创建 :
//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)
我的代码中有以下方法。如您所见,它包含用于检查用户名是否已存在于数据库中的嵌套映射。我想用更优雅的方式来写,但我不知道该怎么做。有什么建议吗?
@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
,因此可以创建 :
//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)