skip to Main Content

I want to check that the user has not been created yet before creating a new one, if there is then create an error… I found a similar question, but I can’t remake it =(

Spring WebFlux: Emit exception upon null value in Spring Data MongoDB reactive repositories?

  public Mono<CustomerDto> createCustomer(Mono<CustomerDto> dtoMono) {
    //How Create Mono error???
    Mono<Customer> fallback = Mono.error(new DealBoardException("Customer with email: " + dtoMono ???));

    return dtoMono.map(customerConverter::convertDto) //convert from DTO to Document
        .map(document -> {
          customerRepository.findByEmailOrPhone(document.getEmail(), document.getPhone())
        })
        .switchIfEmpty() //How check such customer doesn't exists?
        .map(document -> { //Filling in additional information from other services
          var customerRequest = customerConverter.convertDocumentToStripe(document);
          var customerStripe = customerExternalService.createCustomer(customerRequest);
          document.setCustomerId(customerStripe.getId());
          return document;
        })
        .flatMap(customerRepository::save) //Save to MongoDB
        .map(customerConverter::convertDocument); //convert from Document to Dto
  }

2

Answers


  1. Add the following index declaration on the top of your Customer class:

    @CompoundIndex(def = "{'email': 1, 'phone': 1}", unique = true)
    

    That will prevent duplicate entries to be inserted in the database.

    You can catch your org.springframework.dao.DuplicateKeyException with the following construct:

    customerService.save(newCustomer).onErrorMap(...);
            
    

    Ref: MongoDB Compound Indexes official documentation

    Login or Signup to reply.
  2. public Mono<User> create(String username, String password) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(encoder.encode(password));
        return userRepo.existsUserByUsername(username)
                .flatMap(exists -> (exists) ? Mono.error(UserAlreadyExists::new) : userRepo.save(user));
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search