ovn*_*nia 9 java spring kotlin project-reactor spring-webflux
我在 Webflux 控制器中使用Monos 和ResponseEntitys 来操作标头和其他响应信息。例如:
@GetMapping("/{userId}")
fun getOneUser(@PathVariable userId: UserId): Mono<ResponseEntity<UserDto>> {
return repository.findById(userId)
.map(User::asDto)
.map { ResponseEntity.ok(it) }
.defaultIfEmpty(ResponseEntity.notFound().build())
}
@GetMapping
fun getAllUsers(): Flux<UserDto> {
return repository.findAllActive().map(User::asDto)
}
Run Code Online (Sandbox Code Playgroud)
两者都可以正常工作,但在某些情况下也需要ResponseEntity结合使用Flux。响应类型应该是什么?使用正确ResponseEntity<Flux<T>>吗?
例如:
@GetMapping("/{userId}/options")
fun getAllUserOptions(@PathVariable userId: UserId): ??? {
return repository.findById(userId)
.flatMapIterable{ it.options }
.map { OptionDto.from(it) }
// if findById -> empty Mono then:
// return ResponseEntity.notFound().build() ?
// else:
// return the result of `.map { OptionDto.from(it) }` ?
}
Run Code Online (Sandbox Code Playgroud)
我想在这里实现的行为是 getAllUserOptions 返回404ifrepository.findById(userId)为空Mono,否则返回user.optionsas Flux。
更新:这里的存储库是 ReactiveCrudRepository
用于switchIfEmpty在用户不存在的情况下引发异常:
return repository
.findById(userId)
.switchIfEmpty(Mono.error(NotFoundException("User not found")))
.flatMapIterable{ it.options }
.map { OptionDto.from(it) }
Run Code Online (Sandbox Code Playgroud)
然后使用异常处理程序将其转换为 404 响应。
| 归档时间: |
|
| 查看次数: |
12643 次 |
| 最近记录: |