Dav*_*rod 1 functional-programming reactive-programming project-reactor spring-webflux
我是 Spring Webflux / Reactor Core 的新手,正在尝试执行以下功能:
调用 userservice.LoginWebApp()
如果返回用户,则返回“用户”类型的 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 仍然能够编组User和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"));
}
Run Code Online (Sandbox Code Playgroud)