I am new to RXjava functional programming. I am writing a post endpoint with multiple conditions:
- When the post endpoint is hit with products
- If the cart for the logged in user does not exist in DB then create a new cart
- If the cart is already present in couch base extract that record and check the products JSON whether the given productid is already there in the products JSON.
- If it is not available in the products JSON the new product has to be created
- The cart should be updated with the newly created productId
- If it is present in the products JSON then fetch the product record and verify the quantity.
- If the quantity is same then do nothing
- Otherwise, update the record.
I am facing a challenge to write these if else conditions in functional programming. tried with switchifEmpty
and not able to write the code in that.
Here is a sample code.
public Mono<Product> createProduct(final Tuple2<String, productdto> tuple2) {
final Product productdto = tuple2.getT2();
return Mono.just(tuple2.getT1())
.map(cartRepository::findById)
.defaultIfEmpty(cartRepository.save(
cart.builder()
.id(tuple2.getT1())
.build()))
.flatMap(cartres -> cartres)
.flatMap(cartres -> {
final Product product = Product.builder()
.id(1234)
.productId(productDTO.getProductId())
.productName(productDTO.getProductName())
.build();
return productRepository.save(product)
.map(saveCart -> cart.builder()
.id(cartres.getId()).build())
.flatMap(cartRepository::save);
});
}).then(Mono.just(productDto));
}