Search code examples
javalagom

How to return a status code in a Lagom Service call


I want to implement a typical rest POST call in Lagom. The POST creates an object, and returns it, with a status code of 201.

However, the default return code is 200. It is possible to set a status code, as shown here (https://www.lagomframework.com/documentation/1.3.x/java/ServiceImplementation.html#Handling-headers).

However, I cannot figure out how to do it for a more complicated case. My create is asynchronious, and I return an object instead of a String.

This is the code I have:

    @Override
public HeaderServiceCall<OrderRequest.CreateOrderRequest, Order> createOrder() {
    UUID orderId = UUID.randomUUID();
    ResponseHeader responseHeader = ResponseHeader.OK.withStatus(201);

    return (requestHeader, request) -> {
        CompletionStage<Order> stage = registry.refFor(OrderEntity.class, orderId.toString())
                .ask(buildCreateOrder(orderId, request))
                .thenApply(reply -> toApi(reply));

        return CompletableFuture.completedFuture(Pair.create(responseHeader, stage.toCompletableFuture()));
    };
}

However, the return value should be Pair<ResponseHeader, Order>, not Pair<ResponseHeader, CompletionStage<Order>> which I have now, so it does not compile.

I could of course extract the Order myself, by putting the completionStage into an CompletableFuture and getting that, but that would make the call synchronous and force me to deal with InterruptExceptions etc, which seems a bit complex for something that should be trivial.

What is the correct way to set a status code in Lagom?


Solution

  • You almost have it solved. Instead of creating a new completedFuture you could compose stage with a lambda that builds the final Pair like this:

    return stage.thenApply( order -> Pair.create(responseHeader, order));
    

    And putting all the pieces together:

    registry.refFor(OrderEntity.class, orderId.toString())
                .ask(buildCreateOrder(orderId, request))
                .thenApply( reply -> toApi(reply)); 
                .thenApply( order -> Pair.create(responseHeader, order));