Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning list of elements with Spring Webflux

I'am trying to create a simple example of a CRUD with Spring Webflux, but I'am getting stucked in some concepts.

I know that I can return a Flux in my controller request mapping method. But sometimes I would like to return a 404 status, so I can handle in the front-end somehow.

I found a example in the official documentation to use the ServerResponse object:

        public Mono<ServerResponse> listPeople(ServerRequest request) { 
                Flux<Person> people = repository.allPeople();
                return ServerResponse.ok().contentType(APPLICATION_JSON).body(people, Person.class);
        }

As you can see, even when the return is a list (Flux) o persons, the ServerResponse.ok.body creates a Mono.

So my question: Is that the way it is? In other words, it does not matter if I have a Flux, does Spring always return a Mono of ServerResponse (or other similar class)?

For my 404 status I could use something like

.switchIfEmpty(ServerResponse.notFound().build());

But I was thinking in something more streaming way. That I could handle the list of objects element by element, for instance.

like image 529
Igor Veloso Avatar asked Oct 29 '22 07:10

Igor Veloso


1 Answers

I think you need the function collectList() and flatMap(). like this:

public Mono<ServerResponse> listPeople(ServerRequest request) { 
                Flux<Person> people = repository.allPeople();
                return people.collectList().flatMap(p->
                    p.size() < 1 ?
                        ServerResponse.status(404).build()
                       :ServerResponse.ok().contentType(APPLICATION_JSON).body(fromObject(p))
                ); 
        }
like image 189
MiaoYu Avatar answered Nov 15 '22 11:11

MiaoYu