I am new to Spring Webflux / Reactor Core and am trying to perform the following functionality:
call userservice.LoginWebApp()
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"));
}
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"));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With