Provide orNull extensions for WebFlux ServerRequest

Closes gh-23761
This commit is contained in:
Sébastien Deleuze
2019-11-13 16:58:48 +01:00
parent 22211a01ce
commit 6fa9871a70
2 changed files with 146 additions and 0 deletions

View File

@@ -21,11 +21,14 @@ import kotlinx.coroutines.reactive.awaitFirstOrNull
import kotlinx.coroutines.reactive.awaitSingle
import kotlinx.coroutines.reactive.asFlow
import org.springframework.core.ParameterizedTypeReference
import org.springframework.http.MediaType
import org.springframework.http.codec.multipart.Part
import org.springframework.util.CollectionUtils
import org.springframework.util.MultiValueMap
import org.springframework.web.server.WebSession
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import java.net.InetSocketAddress
import java.security.Principal
/**
@@ -112,3 +115,56 @@ suspend fun ServerRequest.awaitPrincipal(): Principal? =
*/
suspend fun ServerRequest.awaitSession(): WebSession =
session().awaitSingle()
/**
* Nullable variant of [ServerRequest.remoteAddress]
*
* @author Sebastien Deleuze
* @since 5.2.2
*/
fun ServerRequest.remoteAddressOrNull(): InetSocketAddress? = remoteAddress().orElse(null)
/**
* Nullable variant of [ServerRequest.attribute]
*
* @author Sebastien Deleuze
* @since 5.2.2
*/
fun ServerRequest.attributeOrNull(name: String): Any? = attributes()[name]
/**
* Nullable variant of [ServerRequest.queryParam]
*
* @author Sebastien Deleuze
* @since 5.2.2
*/
fun ServerRequest.queryParamOrNull(name: String): String? {
val queryParamValues = queryParams()[name]
return if (CollectionUtils.isEmpty(queryParamValues)) {
null
} else {
var value: String? = queryParamValues!![0]
if (value == null) {
value = ""
}
value
}
}
/**
* Nullable variant of [ServerRequest.Headers.contentLength]
*
* @author Sebastien Deleuze
* @since 5.2.2
*/
fun ServerRequest.Headers.contentLengthOrNull(): Long? =
contentLength().run { if (isPresent) asLong else null }
/**
* Nullable variant of [ServerRequest.Headers.contentType]
*
* @author Sebastien Deleuze
* @since 5.2.2
*/
fun ServerRequest.Headers.contentTypeOrNull(): MediaType? =
contentType().orElse(null)