如何返回 Mono<ResponseEntity>,其中响应实体可以是两种不同类型

Dav*_*rod 1 functional-programming reactive-programming project-reactor spring-webflux

我是 Spring Webflux / Reactor Core 的新手,正在尝试执行以下功能:

  1. 调用 userservice.LoginWebApp()

  2. 如果返回用户,则返回“用户”类型的 ResponseEntity。如果为空,则返回“String”类型的 ResponseEntity

以下代码给出了一个类型错误,因为 .defaultIfEmpty() 需要类型为 user 的 ResponseEntity。您能否就实现此功能的正确操作员/方法提出建议。

@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"));
}
Run Code Online (Sandbox Code Playgroud)

Sim*_*slé 10

您可以使用cast操作符来降低泛型,我相信 WebFlux 仍然能够编组UserString

@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"));
}
Run Code Online (Sandbox Code Playgroud)