春WebfluxコントローラにフラックスとResponseEntityを結合する方法

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.optionsFlux

更新:リポジトリはこちら ReactiveCrudRepository

jannis:

使用switchIfEmptyユーザーが存在しない場合に例外をスローします:

return repository
    .findById(userId)
    .switchIfEmpty(Mono.error(NotFoundException("User not found")))
    .flatMapIterable{ it.options }
    .map { OptionDto.from(it) }

その後で例外ハンドラ 404応答にそれを翻訳。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=192653&siteId=1