Details
Description
We should add a ServerResponse.BodyBuilder.body(Object) method, to make it easier for users to set the response body to a non-Publisher type. Currently, this task can be accomplished via body(BodyInserters.fromObject(Object)), but because this method requires a static import of BodyInserters, the discoverability of it is not as high as body(Publisher, Class)). As such, users will go this route:
return ServerResponse.ok().body(Mono.just("Hello World"), String.class);
instead of the more elegant:
return ServerResponse.ok().body(fromObject("Hello World"));
However, adding the method has a serious consequence: there is the potential for accidental method overloading between a the new Object method and the existing Publisher body method. As a result, users will accidentally write a response with the publisher itself, rather than its contents:
Flux<String> flux = ... return ServerResponse.ok().body(flux); // Whoops, should have been body(flux, String.class);
Of course, we cannot automatically call the correct method, because of the lacking Class argument. There are, however, a couple of other ways we can resolve this.
1. Give the method a different name, such as bodyFromObject. If we go this route, we should be consistent and also rename the existing Publisher-based body method to bodyFromPublisher. As such, it has serious consequences for the brevity and UX of the API.
2. Perform a runtime-check to see whether the Object passed to body is a Publisher, and throw an exception if so, warning the user of the error of their ways.
3. Do not add the method. Since this a Reactive web framework, the case can be made that returning non-reactive types as a response is not a main design goal. Returning a String makes for a great demo, but might not be as necessary for real-life reactive scenarios.
Attachments
Issue Links
- is related to
-
SPR-15467 ServerResponse.BodyBuilder.body(Object) shadows body(Publisher) in Kotlin ServerResponseExtensions
-
- Closed
-