Skip to content

Commit 3f3995f

Browse files
GeorgePap-719sdeleuze
authored andcommitted
Add ServerRequest.pathVariableOrNull Kotlin extension
Closes gh-32738
1 parent 02b3801 commit 3f3995f

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

spring-webflux/src/main/kotlin/org/springframework/web/reactive/function/server/ServerRequestExtensions.kt

+11-1
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ import kotlin.reflect.KClass
3535
* Extension for [ServerRequest.bodyToMono] providing a `bodyToMono<Foo>()` variant
3636
* leveraging Kotlin reified type parameters. This extension is not subject to type
3737
* erasure and retains actual generic type arguments.
38-
*
38+
*
3939
* @author Sebastien Deleuze
4040
* @since 5.0
4141
*/
@@ -192,3 +192,13 @@ fun ServerRequest.Headers.contentLengthOrNull(): Long? =
192192
*/
193193
fun ServerRequest.Headers.contentTypeOrNull(): MediaType? =
194194
contentType().orElse(null)
195+
196+
/**
197+
* Nullable variant of [ServerRequest.pathVariable].
198+
*
199+
* @author George Papadopoulos
200+
* @since 6.2
201+
*/
202+
fun ServerRequest.pathVariableOrNull(name: String): String? {
203+
return pathVariables()[name]
204+
}

spring-webflux/src/test/kotlin/org/springframework/web/reactive/function/server/ServerRequestExtensionsTests.kt

+14
Original file line numberDiff line numberDiff line change
@@ -222,5 +222,19 @@ class ServerRequestExtensionsTests {
222222
verify { headers.contentType() }
223223
}
224224

225+
@Test
226+
fun `pathVariableOrNull with value`() {
227+
every { request.pathVariables() } returns hashMapOf("name" to "123")
228+
assert(request.pathVariableOrNull("name") == "123")
229+
verify { request.pathVariables() }
230+
}
231+
232+
@Test
233+
fun `pathVariableOrNull with null`() {
234+
every { request.pathVariables() } returns emptyMap()
235+
assert(request.pathVariableOrNull("name") == null)
236+
verify { request.pathVariables() }
237+
}
238+
225239
class Foo
226240
}

0 commit comments

Comments
 (0)