'WebFlux check before save

New to WebFlux.

Tell me how to implement validation before saving

If there is no Customer with this Email || Phone then save, if there is then RuntimeError

I did not find the exact solution, I want it to be beautiful

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


Solution 1:[1]

This should be implemented via composite key for 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;
}

You will replace default ObjectId with custom composite key and gain all database constrains like unique and non-null.

There would be no need for any checks on service layer at all. You would have to translate db exception to business logic exception and finally show a popup to user that he can't use email or phone cause it already exists.

Please take into the account relatively new validation feature that could be used in here as well: https://www.mongodb.com/docs/manual/core/schema-validation/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aliaksandr Arashkevich