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.
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))
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With