如何返回响应实体可以是两种不同类型的单响应实体(&L;)

人气:909 发布:2022-10-16 标签: functional-programming reactive-programming spring-webflux project-reactor

问题描述

我是新手,我正在尝试执行以下功能:

调用userservice.LoginWebApp()

如果返回User,则返回User类型的ResponseEntity。如果为空,则返回"字符串"类型的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"));
}

推荐答案

您可以使用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"));
}

870