programing

WebFlux 기능:빈 플럭스를 감지하고 404를 반환하는 방법은 무엇입니까?

skycolor 2023. 7. 6. 22:02
반응형

WebFlux 기능:빈 플럭스를 감지하고 404를 반환하는 방법은 무엇입니까?

저는 다음과 같은 단순화된 핸들러 기능(Spring WebFlux 및 Kotlin을 이용한 기능 API)을 가지고 있습니다.하지만 플럭스가 비어 있을 때 404에 대해 빈 플럭스를 감지한 다음 noContent()를 사용하는 방법에 대한 힌트가 필요합니다.

fun findByLastname(request: ServerRequest): Mono<ServerResponse> {
    val lastnameOpt = request.queryParam("lastname")
    val customerFlux = if (lastnameOpt.isPresent) {
        service.findByLastname(lastnameOpt.get())
    } else {
        service.findAll()
    }
    // How can I detect an empty Flux and then invoke noContent() ?
    return ok().body(customerFlux, Customer::class.java)
}

에서Mono:

return customerMono
           .flatMap(c -> ok().body(BodyInserters.fromObject(c)))
           .switchIfEmpty(notFound().build());

에서Flux:

return customerFlux
           .collectList()
           .flatMap(l -> {
               if(l.isEmpty()) {
                 return notFound().build();

               }
               else {
                 return ok().body(BodyInserters.fromObject(l)));
               }
           });

참고:collectList메모리의 데이터를 버퍼링하므로 큰 목록에는 이 방법이 적합하지 않을 수 있습니다.이것을 해결할 더 좋은 방법이 있을지도 모릅니다.

사용하다Flux.hasElements() : Mono<Boolean>함수:

return customerFlux.hasElements()
                   .flatMap {
                     if (it) ok().body(customerFlux)
                     else noContent().build()
                   }

목록을 항상 빈 상태로 확인하지 않으려면 Brian 솔루션 외에도 확장 기능을 만들 수 있습니다.

fun <R> Flux<R>.collectListOrEmpty(): Mono<List<R>> = this.collectList().flatMap {
        val result = if (it.isEmpty()) {
            Mono.empty()
        } else {
            Mono.just(it)
        }
        result
    }

모노를 위해 하는 것처럼 불러보세요.

return customerFlux().collectListOrEmpty()
                     .switchIfEmpty(notFound().build())
                     .flatMap(c -> ok().body(BodyInserters.fromObject(c)))

왜 아무도 모노를 반환하는 Flux.java의 hasElements() 함수를 사용하는 것에 대해 이야기하지 않는지 잘 모르겠습니다.

언급URL : https://stackoverflow.com/questions/45903813/webflux-functional-how-to-detect-an-empty-flux-and-return-404

반응형