no

How to Return a CompletableFuture in a RESTEasy Endpoint

1. Introduction This tutorial is all about using the CompletableFuture class in Quarkus RestEasy endpoints. 2. Asynchronous Endpoint in Sp...

1. Introduction

This tutorial is all about using the CompletableFuture class in Quarkus RestEasy endpoints.

2. Asynchronous Endpoint in Spring

Perhaps you are a Spring developer just like me who is used to asynchronous programming by chaining operations and results using CompletableFuture.

For example, if we have an endpoint for user registration that:

  1. Receive a DTO as input.
  2. Convert the DTO to POJO.
  3. Pass the POJO to the service layer
  4. Return a POJO.
  5. Convert the POJO to DTO.
  6. Return the POJO to the client caller.
Then we can code the endpoint like this:
@PostMapping(path = EndpointConstants.PATH_USER_REGISTRATIONS, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public CompletableFuture<RegisteredUserV1> registerUser(@Valid @RequestBody RegisterUserV1 user) {

	log.info("register user={}", user);

	return ssoService.registerUser(web2ServiceMapper.toUserPojo(user))
		.thenApply(service2WebMapper::toUserDto);
}

// The userService
@Override
@Transactional
public CompletableFuture<UserPojo> registerUser(UserPojo userPojo) {
  return CompletableFuture.completedFuture(new UserPojo());
}
web2ServiceMapper and service2WebMapper are MapStruct interfaces that convert a DTO to POJO and vice versa.

3. Asynchronous Endpoint using RestEasy

RestEasy is a project that provides various frameworks to build RESTful web services. And this project is the one used in Quarkus, another Java framework similar to Spring. Instead of using @PostMapping (Spring), we used @Path/@POST annotations.

Let's convert the endpoint and service method that we have above.

@POST
@Path(PATH_USER_REGISTRATIONS)
public CompletableFuture<RegisteredUserV1> registerUser(@Valid RegisterUserV1 user, @Suspended final AsyncResponse asyncResponse) {

	log.info("register user={}", user);

	ssoService.registerUser(web2ServiceMapper.toUserPojo(user)) // converts to pojo
		.thenApply(service2WebMapper::toUserDto) // converts back to dto
        .thenApply(asyncResponse::resume); // async return
}

The service method and mappers are the same in Spring. CompletableFuture is a Java class after all, and not from Spring or RestEasy/Quarkus.

Related

spring-rest 1490443896852745835

Post a Comment Default Comments

item