반응형
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
반응형
'programing' 카테고리의 다른 글
Spring mongo 데이터 저장소 인터페이스를 위한 "16진수 표현 추가" (0) | 2023.07.06 |
---|---|
SQL 조회에서 카운트 캡처 (0) | 2023.07.06 |
공동작업자를 Firebase 앱에 추가하는 방법은 무엇입니까? (0) | 2023.07.06 |
오라클 SQL에서 join 키워드와 inner join 키워드의 차이점은 무엇입니까? (0) | 2023.07.06 |
git 저장소에 "node_modules" 폴더를 포함해야 하는지 여부 (0) | 2023.07.06 |