Search code examples
springspring-webfluxspring-restcontroller

Merge two mono objects and return responseEntity object?


I have the following controller

@RestController
@RequestMapping("/view")
public class ManiController {
@GetMapping("/{channelId}/**")
public Mono<ResponseEntity<String>> manifest(@RequestParam(name = "sid", required = false) String sessionId) {
    return redisController.getData(sessionId).flatMap(sessionInfo -> {
        if(sessionInfo!=null){
            redisController.confirm(sessionInfo).map(data->{
                return new ResponseEntity<>(data, HttpStatus.OK);
            });
        }
    });
}
}

I do not get callback on redisController.confirm(sessionInfo).map and controller returns blank response.


Solution

  • Reactor does not accept null values.

    Most likely, redisController.getData(sessionId) returns an empty Mono.

    Empty publisher will not emit any values, only a completion signal. Therefore, none of your operations past the empty publisher would be called. To define a fallback, you can either provide an alternate operation using switchIfEmpty (there's also a defaultIfEmpty method to provide a pre-computed fallback).

    Your snippet might be adapted to something like this:

    redisController.getData(sessionId)
                   .flatMap(redisController::confirm)
                   .map(ResponseEntity::ok)
                   .switchIfEmpty(Mono.error(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "Expired or unexisting session")));
    

    In this example, if your redisController does not send back any data, a bad request Response will be sent back.