代码之家  ›  专栏  ›  技术社区  ›  Aliaksei

保存前进行WebFlux检查

  •  0
  • Aliaksei  · 技术社区  · 2 年前

    WebFlux的新成员。

    在保存前告诉我如何执行验证

    如果没有 顾客 用这个 电子邮件 || 电话 然后保存,如果有运行时错误

    我没有找到确切的解决方案,我希望它是美丽的

      public Mono<CustomerDto> createCustomer(CustomerDto customerDto) {
        return customerRepository.findByEmailOrPhone(customerDto.getEmail(), customerDto.getPhone())
            .switchIfEmpty(Mono.just(customerConverter.convertDto(customerDto))
                .flatMap(customerRepository::save)
            )
            .map(customerConverter::convertDocument);
      }
    
    0 回复  |  直到 2 年前
        1
  •  0
  •   Aliaksandr Arashkevich    2 年前

    这应该通过ID的复合密钥实现:

    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public class CustomerId implements Serializable {
      
      private String email;
    
      private String phone;
    }
    
    @Data
    @Document
    public class Customer {
      
      @org.springframework.data.annotation.Id
      private CustomerId id;
    }
    

    您将替换默认值 ObjectId 使用自定义复合密钥并获得所有数据库约束,如唯一和非空。

    根本不需要对服务层进行任何检查。您必须将db异常转换为业务逻辑异常,最后向用户显示一个弹出窗口,用户无法使用电子邮件或电话,因为它已经存在。

    请考虑此处也可以使用的相对较新的验证功能: https://www.mongodb.com/docs/manual/core/schema-validation/