Barath
Barath

Reputation: 5283

spring webflux: how to send Mono<T> in response body with body inserters

This documentation says: https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html

ServerResponse provides access to the HTTP response. Since it is immutable, you create a ServerResponse with a builder. The builder allows you to set the response status, add response headers, and provide a body. For instance, this is how to create a response with a 200 OK status, a JSON content-type, and a body:

Mono<Person> person = ...
ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(person);

Similarly I tired to pass Mono<T> to the body method of ServerReponse Builder but I get following error :

enter image description here

Code snippet :

Compilation error:

Mono<Inventory> inventoryMono=request.bodyToMono(Inventory.class);        
 return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(inventoryMono);

However it works with below code:

ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(inventoryMono.doOnNext(inventoryRepository::save).log(),Inventory.class)

What am I missing ?

Upvotes: 3

Views: 7269

Answers (2)

AjCodez
AjCodez

Reputation: 378

Your situation can be explained based on the documentation. Since you're trying to return a Mono (which inherits from the Publisher class), you must specify the class as the second parameter in the body method as follows.

.body(inventoryMono, Inventory.class)

In your second code snippet, you have the Inventory.class as a second parameter, that's why it works. Simply add it to your first code snippet

Upvotes: 1

Ilya Rodionov
Ilya Rodionov

Reputation: 389

I'm sure that it's a problem with docs because ServerResponse.BodyBuilder doesn't contain such method. There is only one one-argument method called body which takes BodyInserter, so you have to transform Mono to BodyInserter (using BodyInserters.fromObject for example).

Upvotes: 0

Related Questions