From 39cf3f0cfa912d36867566ebb60bbd4a22f25bce Mon Sep 17 00:00:00 2001 From: Valentin Date: Thu, 25 Mar 2021 22:34:40 +0100 Subject: [PATCH] awaitBodyOrNull function to handle empty body Created awaitBodyOrNull function to handle empty body suspend inline fun WebClient.ResponseSpec.awaitBody() : T does not handle nullable body suspend fun WebClient.ResponseSpec.awaitBodilessEntity() ignores body completely even when the content-length is above zero --- .../reactive/function/client/WebClientExtensions.kt | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/spring-webflux/src/main/kotlin/org/springframework/web/reactive/function/client/WebClientExtensions.kt b/spring-webflux/src/main/kotlin/org/springframework/web/reactive/function/client/WebClientExtensions.kt index d48b0b020761..74cb81af9231 100644 --- a/spring-webflux/src/main/kotlin/org/springframework/web/reactive/function/client/WebClientExtensions.kt +++ b/spring-webflux/src/main/kotlin/org/springframework/web/reactive/function/client/WebClientExtensions.kt @@ -143,6 +143,17 @@ suspend inline fun WebClient.ResponseSpec.awaitBody() : T = else -> bodyToMono().awaitSingle() } +/** + * Coroutines variant of [WebClient.ResponseSpec.bodyToMono]. + * + * @author Valentin Shakhov + */ +suspend inline fun WebClient.ResponseSpec.awaitBodyOrNull() : T? = + when (T::class) { + Unit::class -> awaitBodilessEntity().let { Unit as T } + else -> bodyToMono().awaitSingleOrNull() + } + /** * Coroutines variant of [WebClient.ResponseSpec.toBodilessEntity]. */