spring - 如果 webflux mono 的条件在 kotlin 中为真,则仅在 mongo db 中存储用户

标签 spring mongodb kotlin spring-data-mongodb spring-webflux

我有以下问题。只有当用户的电子邮件不存在时,我才想通过响应式(Reactive) Spring 数据存储库将用户保存到 mongo db 中。

@Component("userService")
class UserService(private val repository: UserRepository){

        fun checkIfEMailExists(email: String): Mono<Boolean> {
                return repository.findByEMail(email).hasElement()
        }

        fun create(user: User): Mono<User> {
               //not sure how to do this bit here
               this.checkIfEMailExists(user.email)
               .filter{ it -> it == true}
               .map{repository.save(user)}  
        }  

}

所以,基本上我不确定我如何处理 bool 的 Mono 只有当它的值为真时才做某事(否则抛出异常)

最佳答案

首先,您的 MongoDB 存储库应该是响应式存储库并返回 Mono<User>Flux<User>对于那种签名:

public interface UserRepository extends ReactiveMongoRepository<User, String> {

    Mono<User> findByEmail(String email);
}

然后,您可以将该 react 类型与其他运算符链接起来,如下所示:
@Service
public class UserService {

    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public Mono<User> create(User user) {
        return this.userRepository.findByEmail(user.getEmail())
                .flatMap(existingUser -> Mono.error(new UserAlreadyPresentException(existingUser.getEmail())))
                .then(this.userRepository.save(user));
    }

    class UserAlreadyPresentException extends RuntimeException {

        public UserAlreadyPresentException(String email) {
            super("User already present with email " + email);
        }
    }
}

关于spring - 如果 webflux mono 的条件在 kotlin 中为真,则仅在 mongo db 中存储用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49710384/

相关文章:

spring - @Scope ("prototype") bean 范围未创建新 bean

mongodb - 我们如何在 Mongodb 中实现 "Select For Update"?

javascript - jQuery 不在 AJAX POST 请求上发送 JSON

Kotlin 等同于 Swift 的 `@autoclosure`

spring - CORS Spring 安全过滤器与 WebMvcConfigurer.addCorsMappings

spring - 使用 JPA 实体作为域实体的洋葱架构

android - Lateinit 属性 mScrollView 尚未初始化

kotlin - 更高种类的类型作为类型参数

Mysql:在 Spring 中禁用每次插入时的自动提交

java - 快速搜索,无需标记化