Rajat
Rajat

Reputation: 51

How to define dependencies on two client calls in quarkus reactive programming

I have two Client APIs that return an Uni.

Uni<Customer> getCustomer(customerID)  
Uni<Address> getAddress(addressID)

And I want to open a REST API

Uni<FullCustomer> getFullCustomer(String customerID)

The logic is to make the Customer Client call first. If the returned customer object has addressID then make the second Address Client call and get shipping address details. If shipping address is not available then just wrap the customer in FullCustomer object and return else wrap both customer and address in FullCustomer object and return.

I dont want to block the thread on client call (await().indefinitely()), hence i am using onItem and transfer method call. But my code returns a Uni<Uni> and i want it to return a Uni.

     @GET
    @Path("api/customer/{id}")
    @Produces({ "application/json" })
    Uni<Uni<FullCustomer>> getFullCustomer(@PathParam("id") String customerID){
        Uni<Customer> customerResponse = getCustomer(customerID);
        Uni<Uni<FullCustomer>> asyncResponse = customerResponse.onItem().transform(customer -> {
            if (customer.getAddressId() != null) {
                Uni<Address> addressResponse = getAddress(customer.getAddressId());
                Uni<FullCustomer> fullCustomer = addressResponse.onItem().transform(address -> {
                    if (address.getShippingAddress() != null) {
                        return new FullCustomer(customer, address.getShippingAddress());
                    } else {
                        return new FullCustomer(customer);
                    }
                });
            }
            return Uni.createFrom().item(new FullCustomer(customer));
        });
        return asyncResponse;
    }

How can I rewrite my code so that it returns Uni keeping reactive ( async client ) calls

Upvotes: 1

Views: 143

Answers (1)

Rajat
Rajat

Reputation: 51

Got the solution. Thanks Ladicek for comments.

public Uni<FullCustomer> getFullCustomer(@PathParam("id") String customerID) {
        return getCustomer(customerID)
                .onItem()
                .transformToUni(customer -> {
                    if (customer.getAddressId() != null) {
                        return getAddress(customer.getAddressId()).onItem().transform(address -> {
                            if (address.getShippingAddress() != null) {
                                return new FullCustomer(customer, address.getShippingAddress());
                            } else {
                                return new FullCustomer(customer);
                            }
                        });
                    } else {
                        return Uni.createFrom().item(new FullCustomer(customer));
                    }
                });
    }

Upvotes: 1

Related Questions