what is the best practice to return total of obects with webflux?

Viewed 31

I am developing api with web flux.

@GetMapping(value = "/shipments/containernumbers")
    @Operation(summary = "Returns a list of related container numbers", description = "Return related container numbers based on input")
    public Flux<ContainerNumber> containerNumbers(final String searchTerm, final Pageable pageable) {
        return shipmentService.containerNumbers(searchTerm, pageable)
                .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND, "these is not container number with your input ")));
    }

This will return list of objects with paging. But this will not tell front end how many object it has. The front end need know the total number of object to prepare pages.I checked some samples but did not find right way to do it. What it the best way to realize this requirement means return list of object with paging function as well as total number of object with webflux?

thanks in advance.

1 Answers

The only way I can think of would be to create a second endpoint like:

    @GetMapping(value = "/shipments/containernumbers/count")
    @Operation(summary = "Returns a list of related container numbers", description = "Return related container numbers based on input")
    public Mono<Long> containerNumbers(final String searchTerm) {
        return shipmentService.containerNumbersCount(searchTerm)
                .collectList()
                .map(list -> list.size())
                .switchIfEmpty(Mono.just(0L));
    }

There is no other way if you want server side pagination. You need one endpoint to query the data. This endpoint will employ a Pageable parameter just as you did in your question above.

But to display the number of pages in the frontend, you need a full count of the objects. No big deal, just a few additional lines of code. I suggest a second endpoint for that as shown here.

The database query can be made even simpler if you use spring data. Then you create a countByXyz() query and don't need the collectList() and list.size() part of my code example.

Related