OVNI:
私が使用Mono
してのResponseEntity
ヘッダーおよび他の応答情報を操作するために、私のWebfluxコントローラで秒。例えば:
@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)
}
両方の罰金を動作しますが、あることが要求される場合がある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) }` ?
}
私がここに実現したい動作は、そのgetAllUserOptionsリターンである404
場合にはrepository.findById(userId)
空でMono
そう返す、user.options
とFlux
。
更新:リポジトリはこちら ReactiveCrudRepository
jannis:
使用switchIfEmpty
ユーザーが存在しない場合に例外をスローします:
return repository
.findById(userId)
.switchIfEmpty(Mono.error(NotFoundException("User not found")))
.flatMapIterable{ it.options }
.map { OptionDto.from(it) }
その後で例外ハンドラ 404応答にそれを翻訳。