Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a Mono<ResponseEntity> where the response entity can be of two different types

I am new to Spring Webflux / Reactor Core and am trying to perform the following functionality:

  1. call userservice.LoginWebApp()

  2. If a user is returned, return ResponseEntity of type "User". If empty, Return ResponseEntity of type "String"

The following code gives a type error as .defaultIfEmpty() expects ResponseEntity of type user. Can you please advise on the correct operator / method to implement this functionality.

@PostMapping("api/user/login/webApp")
public Mono<ResponseEntity> login(@RequestBody Credentials credentials, ServerWebExchange serverWebExchange) {
     return userService.loginWebApp(credentials, serverWebExchange)
             .map(user -> ResponseEntity.status(HttpStatus.OK).body(user))
             .defaultIfEmpty(ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid username or password"));
}
like image 562
David Herod Avatar asked Oct 15 '25 14:10

David Herod


1 Answers

You can use the cast operator to downcast out of the generic, and I believe WebFlux will still be able to marshal the User and the String:

@PostMapping("api/user/login/webApp")
public Mono<ResponseEntity> login(@RequestBody Credentials credentials, ServerWebExchange serverWebExchange) {
     return userService.loginWebApp(credentials, serverWebExchange)
             .map(user -> ResponseEntity.status(HttpStatus.OK).body(user))
             .cast(ResponseEntity.class)
             .defaultIfEmpty(ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid username or password"));
}
like image 120
Simon Baslé Avatar answered Oct 18 '25 03:10

Simon Baslé