reikje
reikje

Reputation: 3064

How do I header to a ResponseEntity conditionally if a Flux is empty

In a reactive spring-boot Controller, given the following method (kotlin)

fun rows(): ResponseEntity<Flux<ResultRow>> {
    val elements: Flux<ResultRow> = service.fetchRows() // not shown

    return ResponseEntity
        .ok()
        .header(
            ResultRowPagination.NEXT_PAGE_HEADER, "value")
        )
        .body(elements)
}

Is there a way to not set the ResultRowPagination.NEXT_PAGE_HEADER at all if the Flux is empty (A) or contains less than 10 items (B)?

Upvotes: 0

Views: 513

Answers (1)

Alexander Pankin
Alexander Pankin

Reputation: 3955

You should collect list from your Flux if you want to compare it's size to 10.

Maybe this could help you:

Mono<ResponseEntity<List<ResultRow>>> rows() {
    Flux<ResultRow> elements = ...;

    return elements
            .collectList()
            .map(resultRows -> prepareHeaders(resultRows)
                    .body(resultRows))
            .switchIfEmpty(Mono.just(ResponseEntity.ok()
                    .build()));
}

ResponseEntity.BodyBuilder prepareHeaders(List<ResultRow> resultRows) {
    if (resultRows.isEmpty() || resultRows.size() < 10)
        return ResponseEntity.ok();
    return ResponseEntity.ok()
            .header(ResultRowPagination.NEXT_PAGE_HEADER, "value");
}

Upvotes: 1

Related Questions