paul
paul

Reputation: 13471

render http response in callback

I have been reading the Micronaut documentation but I cannot find the way to render the http response in a callback as I can do it for instance with Jax-Rs Jersey.

Here what I want to achieve

@Get("/scalaFuture")
public void getScalaFuture() {
    Futures.successful(new SpringBootEntityDaoDTO())
            .onComplete(result -> {
                if (result.isSuccess()) {
                    return HttpResponse.ok(result.get());
                } else {
                    return HttpResponse.serverError(result.failed().get());
                }
            }, ExecutorContextUtil.defaultExecutionContext());
}

Basically render the response in the callback of the future.

Something similar as I do with JaxRS in the Observable callback using AsyncResponse

@POST
@Path("/bla")
public void foo(@Suspended final AsyncResponse asyncResponse) {
    Observable<EntityDaoDTO> observable = observableFosConnectorManager.execute("EntityAggregateRoot", "database", getEntityDaoDTO(), null, MethodDTO.CREATE);
    observable
            .subscribeOn(Schedulers.computation())
            .subscribe(result -> {
                EntityPayLoad entityPayLoad = new EntityPayLoad();
                entityPayLoad.setTitle(result.getTitle());
                entityPayLoad.setDescription(result.getDescription());
                asyncResponse.resume(Response.status(Response.Status.OK.getStatusCode()).entity(entityPayLoad).build());
            }, t -> asyncResponse.resume(Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build()),
            () -> getLogger().info(null, "Subscription done"));
}

Regards

Upvotes: 1

Views: 364

Answers (1)

hmatt1
hmatt1

Reputation: 5159

Micronaut allows different return types including reactive responses.

For example, you can return a CompletableFuture:

@Controller("/people")
public class PersonController {

    Map<String, Person> inMemoryDatastore = new ConcurrentHashMap<>();

    @Post("/saveFuture")
    public CompletableFuture<HttpResponse<Person>> save(@Body CompletableFuture<Person> person) {
        return person.thenApply(p -> {
                    inMemoryDatastore.put(p.getFirstName(), p);
                    return HttpResponse.created(p);
                }
        );
    }

}

Convert your scala future to a Java completable future: https://stackoverflow.com/a/46695386/2534803

https://docs.micronaut.io/latest/guide/index.html#_binding_using_completablefuture

Upvotes: 1

Related Questions