Aliaksei
Aliaksei

Reputation: 1457

Save Mono to two repostiroy

Can you help me

What is the correct way to work with Mono in order to convert it into two different documents and save it to two different repositories?

  public Mono<OrderDto> makePayment(String orderId, PaymentPayPalRequest request) {
    return orderRepository.findById(new ObjectId(orderId))
        .doOnNext(order -> {
          var response = paymentPayPalService.makePayment(request);
          order.setStatus(response.getStatus());
          order.setPayments(Map.of(PaymentSystem.PAYPAL, response.getPaymentId()));
        })
        .flatMap(orderRepository::save)
        .map("HERE I want transform "response" to mongo document  and save to another repository")
        .map(orderConverter::convertDocument);
  }

UPD1

I rewrite my code. Is it good in terms of WebFlux?

  public Mono<OrderDto> makePayment(String orderId, PaymentPayPalRequest request) {
    return Mono.just(paymentPayPalService.makePayment(request))
        .flatMap(response -> saveToPayPalPayment(response).then(saveToOrder(orderId, response)))
        .map(orderConverter::convertDocument);
  }

  private Mono<Order> saveToOrder(String orderId, PaymentPayPalResponse response) {
    return orderRepository.findById(new ObjectId(orderId))
        .doOnNext(order -> {
          order.setStatus(response.getStatus());
          order.setPayments(Map.of(PaymentSystem.PAYPAL, response.getPaymentId()));
        })
        .flatMap(orderRepository::save);
  }

  private Mono<PayPalPayment> saveToPayPalPayment(PaymentPayPalResponse response) {
    var payPalPayment = payPalTransactionConverter.convertPayPalPaymentToDocument(response);
    return payPalTransactionRepository.save(payPalPayment);
  }

Upvotes: 0

Views: 118

Answers (1)

Alex
Alex

Reputation: 5972

There are several potential issues with the updated code

  1. Wrapping non-reactive code
  • use Mono.fromCallable instead of Mono.just that handles exceptions transforming them into Mono.error
  • consider running blocking (non-reactive) code on a separate scheduler (e.g. boundedElastic)
return Mono.fromCallable(() -> paymentPayPalService.makePayment(request))
    .subscribeOn(Schedulers.boundedElastic());
  1. Use map instead of doOnNext. doOn... are so called side-effect operators that typically used for logging or telemetry.
return orderRepository.findById(new ObjectId(orderId))
        .map(order -> {
            order.setStatus(response.getStatus());
            order.setPayments(Map.of(PaymentSystem.PAYPAL, response.getPaymentId()));
            return order;
        })

Upvotes: 1

Related Questions