Hello world
Hello world

Reputation: 353

Writing 'reactive' WebFlux controller

I'm trying to convert WebMVC controller to WebFlux controller returning Mono<Resource>.

The old WebMVC controller looks like below.

@GetMapping("/resources/{id}")
public ResponseEntity<Resource> getCustomer(@RequestParam String id) {
    if(id.length != 10) {
        // set ResponseEntity status 400 and then return it
    }

    val resource = resourceService.getResourceById(id);    
    return ResponseEntity.ok().body(resource);
}

How can I have if block more compatible with the Reactive Programming?

Upvotes: 0

Views: 974

Answers (2)

U need to create the handler,router for webflux functional flow

@Component

public class SampleHandlerFunction {

public Mono<ServerResponse> flux(ServerRequest serverRequest) {

    return ServerResponse.ok()
            .contentType(MediaType.APPLICATION_JSON)
            .body(
                    Flux.just(1, 2, 3, 4)
                            .log(), Integer.class
            );
}

public Mono<ServerResponse> mono(ServerRequest serverRequest) {

    return ServerResponse.ok()
            .contentType(MediaType.APPLICATION_JSON)
            .body(
                    Mono.just(1)
                            .log(), Integer.class
            );
}

router

@Configuration

public class RouterFunctionConfig {

@Bean
public RouterFunction<ServerResponse> route(com.Reactive.SpringReactive.handler.SampleHandlerFunction handlerFunction){

    return RouterFunctions
            .route(GET("/functional/flux").and(accept(MediaType.APPLICATION_JSON)),handlerFunction::flux)
            .andRoute(GET("/functional/mono").and(accept(MediaType.APPLICATION_JSON)),handlerFunction::mono);

}

}

Upvotes: 0

Nipuna Saranga
Nipuna Saranga

Reputation: 1200

If you are using Functional endpoints you could do something like that.

public Mono<ServerResponse> getCustomer(ServerRequest serverRequest) {

  if (serverRequest.pathVariable("id").length() != 10) {

    return ServerResponse
        .status(400)
        .build();

  } else {

    return ServerResponse
        .ok()
        .body(
            resourceService.getResourceById(serverRequest.pathVariable("id")),
            Resource.class
        );

  }

}

Above mentioned is more readable for me. But you could start with Mono.just(serverRequest.pathVariable("id")), if you really want to maintain stream even within methods, as below.

return Mono.just(serverRequest.pathVariable("id"))
  .filter(id -> id.length() == 10)
  .flatMap(resourceService::getResourceById)
  .flatMap(resource -> ServerResponse
      .ok()
      .body(
          resourceService.getResourceById(serverRequest.pathVariable("id")),
          Resource.class
      )
  )
  .switchIfEmpty(ServerResponse.status(400).build());

Similarly if you are using annotated controllers, something like below seems more readable (for me :)).

@GetMapping(path = "/resources/{id}")
public ResponseEntity<Mono<Resource>> getCustomer(@PathVariable String id) {

  if (id.length() != 10) {

    return ResponseEntity
            .status(400)
            .build();

  } else {

    return ResponseEntity
        .ok()
        .body(resourceService
            .getResourceById(id));

  }

}

Official documentation is a good enough reference: Two relevant sections in documentation

  1. https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html#webflux-controller
  2. https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html#webflux-fn

Upvotes: 3

Related Questions